@hamzasaleemorg/convex-kv 1.0.0

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 (52) hide show
  1. package/README.md +108 -0
  2. package/dist/client/_generated/_ignore.d.ts +1 -0
  3. package/dist/client/_generated/_ignore.d.ts.map +1 -0
  4. package/dist/client/_generated/_ignore.js +3 -0
  5. package/dist/client/_generated/_ignore.js.map +1 -0
  6. package/dist/client/index.d.ts +129 -0
  7. package/dist/client/index.d.ts.map +1 -0
  8. package/dist/client/index.js +153 -0
  9. package/dist/client/index.js.map +1 -0
  10. package/dist/component/_generated/api.d.ts +34 -0
  11. package/dist/component/_generated/api.d.ts.map +1 -0
  12. package/dist/component/_generated/api.js +31 -0
  13. package/dist/component/_generated/api.js.map +1 -0
  14. package/dist/component/_generated/component.d.ts +61 -0
  15. package/dist/component/_generated/component.d.ts.map +1 -0
  16. package/dist/component/_generated/component.js +11 -0
  17. package/dist/component/_generated/component.js.map +1 -0
  18. package/dist/component/_generated/dataModel.d.ts +46 -0
  19. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  20. package/dist/component/_generated/dataModel.js +11 -0
  21. package/dist/component/_generated/dataModel.js.map +1 -0
  22. package/dist/component/_generated/server.d.ts +121 -0
  23. package/dist/component/_generated/server.d.ts.map +1 -0
  24. package/dist/component/_generated/server.js +78 -0
  25. package/dist/component/_generated/server.js.map +1 -0
  26. package/dist/component/convex.config.d.ts +3 -0
  27. package/dist/component/convex.config.d.ts.map +1 -0
  28. package/dist/component/convex.config.js +3 -0
  29. package/dist/component/convex.config.js.map +1 -0
  30. package/dist/component/kv.d.ts +62 -0
  31. package/dist/component/kv.d.ts.map +1 -0
  32. package/dist/component/kv.js +220 -0
  33. package/dist/component/kv.js.map +1 -0
  34. package/dist/component/schema.d.ts +22 -0
  35. package/dist/component/schema.d.ts.map +1 -0
  36. package/dist/component/schema.js +15 -0
  37. package/dist/component/schema.js.map +1 -0
  38. package/package.json +91 -0
  39. package/src/client/_generated/_ignore.ts +1 -0
  40. package/src/client/index.test.ts +24 -0
  41. package/src/client/index.ts +197 -0
  42. package/src/client/setup.test.ts +26 -0
  43. package/src/component/_generated/api.ts +50 -0
  44. package/src/component/_generated/component.ts +95 -0
  45. package/src/component/_generated/dataModel.ts +60 -0
  46. package/src/component/_generated/server.ts +156 -0
  47. package/src/component/convex.config.ts +3 -0
  48. package/src/component/kv.test.ts +51 -0
  49. package/src/component/kv.ts +249 -0
  50. package/src/component/schema.ts +16 -0
  51. package/src/component/setup.test.ts +11 -0
  52. package/src/test.ts +18 -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,3 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ export default defineComponent("convexKv");
@@ -0,0 +1,51 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ import { describe, expect, test } from "vitest";
4
+ import { api } from "./_generated/api.js";
5
+ import { initConvexTest } from "./setup.test.js";
6
+
7
+
8
+ describe("component kv", () => {
9
+ test("basic kv operations", async () => {
10
+ const t = initConvexTest();
11
+
12
+ // Set and get
13
+ await t.mutation(api.kv.set, { key: ["users", "1"], value: { name: "Alice" } });
14
+ const user = await t.query(api.kv.get, { key: ["users", "1"] });
15
+ expect(user?.value).toEqual({ name: "Alice" });
16
+
17
+
18
+ // Has
19
+ const exists = await t.query(api.kv.has, { key: ["users", "1"] });
20
+ expect(exists).toBe(true);
21
+ const missing = await t.query(api.kv.has, { key: ["users", "2"] });
22
+ expect(missing).toBe(false);
23
+
24
+ // List with prefix
25
+ await t.mutation(api.kv.set, { key: ["users", "2"], value: { name: "Bob" } });
26
+ await t.mutation(api.kv.set, { key: ["posts", "1"], value: { title: "Post 1" } });
27
+
28
+ const users = await t.query(api.kv.list, { prefix: ["users"] });
29
+ expect(users.entries).toHaveLength(2);
30
+
31
+ const all = await t.query(api.kv.getAll, { prefix: [] });
32
+ expect(all).toHaveLength(3);
33
+
34
+ // Verify hierarchical isolation
35
+ await t.mutation(api.kv.set, { key: ["a"], value: "parent" });
36
+ await t.mutation(api.kv.set, { key: ["a", "b"], value: "child" });
37
+ await t.mutation(api.kv.set, { key: ["aa"], value: "sibling" });
38
+
39
+ const aPrefix = await t.query(api.kv.getAll, { prefix: ["a"] });
40
+ // Should contain ["a"] and ["a", "b"] but NOT ["aa"]
41
+ expect(aPrefix.map(e => e.key)).toContainEqual(["a"]);
42
+ expect(aPrefix.map(e => e.key)).toContainEqual(["a", "b"]);
43
+ expect(aPrefix.map(e => e.key)).not.toContainEqual(["aa"]);
44
+ expect(aPrefix.length).toBe(2);
45
+
46
+ // Delete
47
+ await t.mutation(api.kv.remove, { key: ["users", "1"] });
48
+ const userAfterDelete = await t.query(api.kv.get, { key: ["users", "1"] });
49
+ expect(userAfterDelete).toBeNull();
50
+ });
51
+ });
@@ -0,0 +1,249 @@
1
+ import { v } from "convex/values";
2
+ import {
3
+ mutation,
4
+ query,
5
+ } from "./_generated/server.js";
6
+ import { api } from "./_generated/api.js";
7
+
8
+ const DELIMITER = "\x00";
9
+
10
+ function joinKey(key: string[]): string {
11
+ return key.join(DELIMITER);
12
+ }
13
+
14
+ /**
15
+ * Removes up to 100 expired keys.
16
+ * Can be scheduled periodically or called by a manager.
17
+ */
18
+ export const vacuum = mutation({
19
+ args: {},
20
+ handler: async (ctx) => {
21
+ const now = Date.now();
22
+ // Only fetch keys that EXPLICITLY have an expiresAt field and it is in the past
23
+ const expired = await ctx.db
24
+ .query("kv")
25
+ .withIndex("expiresAt", (q) => q.lt("expiresAt", now))
26
+ .take(100);
27
+
28
+ let deleted = 0;
29
+ for (const doc of expired) {
30
+ // Double check safety: never delete if expiresAt is missing or in the future
31
+ if (doc.expiresAt && doc.expiresAt < now) {
32
+ await ctx.db.delete(doc._id);
33
+ deleted++;
34
+ }
35
+ }
36
+ return { count: deleted };
37
+ },
38
+ });
39
+
40
+ export const get = query({
41
+ args: { key: v.array(v.string()) },
42
+ returns: v.union(v.null(), v.object({
43
+ key: v.array(v.string()),
44
+ value: v.any(),
45
+ metadata: v.optional(v.any()),
46
+ updatedAt: v.number(),
47
+ expiresAt: v.optional(v.number()),
48
+ })),
49
+ handler: async (ctx, args) => {
50
+ const path = joinKey(args.key);
51
+ const entry = await ctx.db
52
+ .query("kv")
53
+ .withIndex("path", (q) => q.eq("path", path))
54
+ .unique();
55
+ if (!entry) return null;
56
+
57
+ // Filter expired
58
+ if (entry.expiresAt && entry.expiresAt < Date.now()) {
59
+ return null;
60
+ }
61
+
62
+ return {
63
+ key: entry.key,
64
+ value: entry.value,
65
+ metadata: entry.metadata,
66
+ updatedAt: entry.updatedAt,
67
+ expiresAt: entry.expiresAt,
68
+ };
69
+ },
70
+ });
71
+
72
+ export const has = query({
73
+ args: { key: v.array(v.string()) },
74
+ returns: v.boolean(),
75
+ handler: async (ctx, args) => {
76
+ const path = joinKey(args.key);
77
+ const entry = await ctx.db
78
+ .query("kv")
79
+ .withIndex("path", (q) => q.eq("path", path))
80
+ .unique();
81
+ if (!entry) return false;
82
+ // Filter expired
83
+ if (entry.expiresAt && entry.expiresAt < Date.now()) {
84
+ return false;
85
+ }
86
+ return true;
87
+ },
88
+ });
89
+
90
+ export const set = mutation({
91
+ args: {
92
+ key: v.array(v.string()),
93
+ value: v.any(),
94
+ metadata: v.optional(v.any()),
95
+ ttl: v.optional(v.number()),
96
+ expiresAt: v.optional(v.number()),
97
+ },
98
+ returns: v.null(),
99
+ handler: async (ctx, args) => {
100
+ const path = joinKey(args.key);
101
+ const existing = await ctx.db
102
+ .query("kv")
103
+ .withIndex("path", (q) => q.eq("path", path))
104
+ .unique();
105
+
106
+ let expiresAt = args.expiresAt;
107
+ if (args.ttl !== undefined) {
108
+ expiresAt = Date.now() + args.ttl;
109
+ }
110
+
111
+ if (existing) {
112
+ await ctx.db.patch(existing._id, {
113
+ value: args.value,
114
+ metadata: args.metadata,
115
+ updatedAt: Date.now(),
116
+ // Explicitly clear or update expiresAt
117
+ expiresAt: expiresAt ?? (args.ttl === undefined && args.expiresAt === undefined ? undefined : existing.expiresAt),
118
+ });
119
+ } else {
120
+ await ctx.db.insert("kv", {
121
+ key: args.key,
122
+ path,
123
+ value: args.value,
124
+ metadata: args.metadata,
125
+ updatedAt: Date.now(),
126
+ expiresAt,
127
+ });
128
+ }
129
+
130
+ return null;
131
+ },
132
+ });
133
+
134
+
135
+ export const remove = mutation({
136
+ args: { key: v.array(v.string()) },
137
+ returns: v.null(),
138
+ handler: async (ctx, args) => {
139
+ const path = joinKey(args.key);
140
+ const existing = await ctx.db
141
+ .query("kv")
142
+ .withIndex("path", (q) => q.eq("path", path))
143
+ .unique();
144
+ if (existing) {
145
+ await ctx.db.delete(existing._id);
146
+ }
147
+ return null;
148
+ },
149
+ });
150
+
151
+ /**
152
+ * Strict hierarchical range:
153
+ * If prefix is ["a"], path is "a".
154
+ * We want "a" and any "a\x00...".
155
+ * Lexicographically, "a\x00" < "a\x01".
156
+ * And "ab" > "a\x01".
157
+ * So [pathPrefix, pathPrefix + "\x01") correctly captures exactly the hierarchy.
158
+ */
159
+ function getPrefixRange(q: any, pathPrefix: string) {
160
+ if (pathPrefix.length === 0) return q;
161
+ return q.gte("path", pathPrefix).lt("path", pathPrefix + "\x01");
162
+ }
163
+
164
+ export const list = query({
165
+ args: {
166
+ prefix: v.array(v.string()),
167
+ limit: v.optional(v.number()),
168
+ cursor: v.optional(v.string()),
169
+ includeValues: v.optional(v.boolean()),
170
+ },
171
+ handler: async (ctx, args) => {
172
+ const pathPrefix = joinKey(args.prefix);
173
+ const query = ctx.db.query("kv").withIndex("path", (q) => getPrefixRange(q, pathPrefix));
174
+
175
+ const results = await query.paginate({
176
+ numItems: args.limit ?? 100,
177
+ cursor: args.cursor ?? null,
178
+ });
179
+
180
+ const now = Date.now();
181
+ return {
182
+ entries: results.page
183
+ .filter(e => !e.expiresAt || e.expiresAt > now)
184
+ .map(e => ({
185
+ key: e.key,
186
+ ...(args.includeValues !== false ? { value: e.value } : {}),
187
+ metadata: e.metadata,
188
+ updatedAt: e.updatedAt,
189
+ expiresAt: e.expiresAt,
190
+ })),
191
+ continueCursor: results.continueCursor,
192
+ isDone: results.isDone,
193
+ };
194
+ },
195
+ });
196
+
197
+ export const getAll = query({
198
+ args: {
199
+ prefix: v.array(v.string()),
200
+ includeValues: v.optional(v.boolean()),
201
+ },
202
+ handler: async (ctx, args) => {
203
+ const pathPrefix = joinKey(args.prefix);
204
+ const entries = await ctx.db.query("kv").withIndex("path", (q) =>
205
+ getPrefixRange(q, pathPrefix)
206
+ ).take(1000);
207
+
208
+ const now = Date.now();
209
+ return entries
210
+ .filter(e => !e.expiresAt || e.expiresAt > now)
211
+ .map(e => ({
212
+ key: e.key,
213
+ ...(args.includeValues !== false ? { value: e.value } : {}),
214
+ metadata: e.metadata,
215
+ updatedAt: e.updatedAt,
216
+ expiresAt: e.expiresAt,
217
+ }));
218
+ },
219
+ });
220
+
221
+
222
+
223
+ export const deleteAll = mutation({
224
+ args: { prefix: v.array(v.string()) },
225
+ handler: async (ctx, args) => {
226
+ const pathPrefix = joinKey(args.prefix);
227
+ const entries = await ctx.db.query("kv").withIndex("path", (q) =>
228
+ getPrefixRange(q, pathPrefix)
229
+ ).take(101);
230
+
231
+ const toDelete = entries.slice(0, 100);
232
+ const hasMore = entries.length > 100;
233
+
234
+ for (const entry of toDelete) {
235
+ await ctx.db.delete(entry._id);
236
+ }
237
+
238
+ if (hasMore) {
239
+ await ctx.scheduler.runAfter(0, api.kv.deleteAll, {
240
+ prefix: args.prefix,
241
+ });
242
+ }
243
+
244
+ return {
245
+ deletedCount: toDelete.length,
246
+ hasMore,
247
+ };
248
+ },
249
+ });
@@ -0,0 +1,16 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ export default defineSchema({
5
+ kv: defineTable({
6
+ key: v.array(v.string()), // The hierarchical key as an array of segments
7
+ path: v.string(), // The key segments joined by a delimiter for prefix scans
8
+ value: v.any(), // The stored value
9
+ metadata: v.optional(v.any()), // Internal metadata (e.g., for validation)
10
+ updatedAt: v.number(),
11
+ expiresAt: v.optional(v.number()),
12
+ })
13
+ .index("path", ["path"])
14
+ .index("expiresAt", ["expiresAt"]),
15
+ });
16
+
@@ -0,0 +1,11 @@
1
+ /// <reference types="vite/client" />
2
+ import { test } from "vitest";
3
+ import schema from "./schema.js";
4
+ import { convexTest } from "convex-test";
5
+ export const modules = import.meta.glob("./**/*.*s");
6
+
7
+ export function initConvexTest() {
8
+ const t = convexTest(schema, modules);
9
+ return t;
10
+ }
11
+ test("setup", () => {});
package/src/test.ts ADDED
@@ -0,0 +1,18 @@
1
+ /// <reference types="vite/client" />
2
+ import type { TestConvex } from "convex-test";
3
+ import type { GenericSchema, SchemaDefinition } from "convex/server";
4
+ import schema from "./component/schema.js";
5
+ const modules = import.meta.glob("./component/**/*.ts");
6
+
7
+ /**
8
+ * Register the component with the test convex instance.
9
+ * @param t - The test convex instance, e.g. from calling `convexTest`.
10
+ * @param name - The name of the component, as registered in convex.config.ts.
11
+ */
12
+ export function register(
13
+ t: TestConvex<SchemaDefinition<GenericSchema, boolean>>,
14
+ name: string = "convexKv",
15
+ ) {
16
+ t.registerComponent(name, schema, modules);
17
+ }
18
+ export default { register, schema, modules };