@vllnt/convex-flags 0.1.0-canary.a2bb74e

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 +123 -0
  3. package/dist/client/index.d.ts +76 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +55 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +19 -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 +20 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +15 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +57 -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 +19 -0
  32. package/dist/component/mutations.d.ts.map +1 -0
  33. package/dist/component/mutations.js +75 -0
  34. package/dist/component/mutations.js.map +1 -0
  35. package/dist/component/queries.d.ts +30 -0
  36. package/dist/component/queries.d.ts.map +1 -0
  37. package/dist/component/queries.js +52 -0
  38. package/dist/component/queries.js.map +1 -0
  39. package/dist/component/schema.d.ts +23 -0
  40. package/dist/component/schema.d.ts.map +1 -0
  41. package/dist/component/schema.js +10 -0
  42. package/dist/component/schema.js.map +1 -0
  43. package/dist/component/validators.d.ts +38 -0
  44. package/dist/component/validators.d.ts.map +1 -0
  45. package/dist/component/validators.js +24 -0
  46. package/dist/component/validators.js.map +1 -0
  47. package/dist/shared.d.ts +19 -0
  48. package/dist/shared.d.ts.map +1 -0
  49. package/dist/shared.js +12 -0
  50. package/dist/shared.js.map +1 -0
  51. package/package.json +97 -0
  52. package/src/client/index.ts +117 -0
  53. package/src/client/types.ts +21 -0
  54. package/src/component/_generated/api.ts +36 -0
  55. package/src/component/_generated/component.ts +74 -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 +89 -0
  60. package/src/component/queries.ts +55 -0
  61. package/src/component/schema.ts +10 -0
  62. package/src/component/validators.ts +26 -0
  63. package/src/shared.ts +21 -0
  64. package/src/test.ts +17 -0
@@ -0,0 +1,117 @@
1
+ import type {
2
+ FunctionArgs,
3
+ FunctionReference,
4
+ FunctionReturnType,
5
+ } from "convex/server";
6
+ import type { FlagDefinition, FlagDoc, FlagEvaluation } from "./types.js";
7
+
8
+ /**
9
+ * The component's function references, as exposed on the host via
10
+ * `components.flags`.
11
+ */
12
+ export interface FlagsComponent {
13
+ mutations: {
14
+ define: FunctionReference<
15
+ "mutation",
16
+ "internal",
17
+ { key: string; value: boolean; description?: string },
18
+ string
19
+ >;
20
+ enable: FunctionReference<"mutation", "internal", { key: string }, null>;
21
+ disable: FunctionReference<"mutation", "internal", { key: string }, null>;
22
+ remove: FunctionReference<"mutation", "internal", { key: string }, null>;
23
+ };
24
+ queries: {
25
+ get: FunctionReference<"query", "internal", { key: string }, FlagDoc | null>;
26
+ list: FunctionReference<"query", "internal", Record<string, never>, FlagDoc[]>;
27
+ evaluate: FunctionReference<
28
+ "query",
29
+ "internal",
30
+ { key: string },
31
+ FlagEvaluation
32
+ >;
33
+ all: FunctionReference<
34
+ "query",
35
+ "internal",
36
+ Record<string, never>,
37
+ Record<string, FlagEvaluation>
38
+ >;
39
+ };
40
+ }
41
+
42
+ interface RunQueryCtx {
43
+ runQuery<Q extends FunctionReference<"query", "internal">>(
44
+ reference: Q,
45
+ args: FunctionArgs<Q>,
46
+ ): Promise<FunctionReturnType<Q>>;
47
+ }
48
+
49
+ interface RunMutationCtx {
50
+ runMutation<M extends FunctionReference<"mutation", "internal">>(
51
+ reference: M,
52
+ args: FunctionArgs<M>,
53
+ ): Promise<FunctionReturnType<M>>;
54
+ }
55
+
56
+ /**
57
+ * Consumer-facing client for `@vllnt/convex-flags`. Construct with the mounted
58
+ * component ref, then call from host queries/mutations/actions. The host owns
59
+ * auth: gate the management methods (`define`, `enable`, `disable`, `remove`)
60
+ * behind your own authorized mutations.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const flags = new Flags(components.flags);
65
+ * if (await flags.isEnabled(ctx, "new-checkout")) { ... }
66
+ * ```
67
+ */
68
+ export class Flags {
69
+ constructor(private readonly component: FlagsComponent) {}
70
+
71
+ /** Create a flag, or update it if the key already exists. Returns its id. */
72
+ define(ctx: RunMutationCtx, definition: FlagDefinition): Promise<string> {
73
+ return ctx.runMutation(this.component.mutations.define, definition);
74
+ }
75
+
76
+ /** Turn a flag on. Throws `FLAG_NOT_FOUND` if the key is undefined. */
77
+ enable(ctx: RunMutationCtx, key: string): Promise<null> {
78
+ return ctx.runMutation(this.component.mutations.enable, { key });
79
+ }
80
+
81
+ /** Turn a flag off. Throws `FLAG_NOT_FOUND` if the key is undefined. */
82
+ disable(ctx: RunMutationCtx, key: string): Promise<null> {
83
+ return ctx.runMutation(this.component.mutations.disable, { key });
84
+ }
85
+
86
+ /** Permanently delete a flag. Throws `FLAG_NOT_FOUND` if the key is undefined. */
87
+ remove(ctx: RunMutationCtx, key: string): Promise<null> {
88
+ return ctx.runMutation(this.component.mutations.remove, { key });
89
+ }
90
+
91
+ /** Fetch a single flag definition, or `null` if undefined. */
92
+ get(ctx: RunQueryCtx, key: string): Promise<FlagDoc | null> {
93
+ return ctx.runQuery(this.component.queries.get, { key });
94
+ }
95
+
96
+ /** List every flag definition. */
97
+ list(ctx: RunQueryCtx): Promise<FlagDoc[]> {
98
+ return ctx.runQuery(this.component.queries.list, {});
99
+ }
100
+
101
+ /** Evaluate a flag, returning its value and the reason it was served. */
102
+ evaluate(ctx: RunQueryCtx, key: string): Promise<FlagEvaluation> {
103
+ return ctx.runQuery(this.component.queries.evaluate, { key });
104
+ }
105
+
106
+ /** Evaluate a flag and return just its boolean value (default `false`). */
107
+ async isEnabled(ctx: RunQueryCtx, key: string): Promise<boolean> {
108
+ return (await this.evaluate(ctx, key)).value;
109
+ }
110
+
111
+ /** Evaluate every flag — the bootstrap payload for a reactive client. */
112
+ all(ctx: RunQueryCtx): Promise<Record<string, FlagEvaluation>> {
113
+ return ctx.runQuery(this.component.queries.all, {});
114
+ }
115
+ }
116
+
117
+ export type { FlagDefinition, FlagDoc, FlagEvaluation };
@@ -0,0 +1,21 @@
1
+ import type { EvalReason, FlagEvaluation } from "../shared.js";
2
+
3
+ /** A flag document as returned by the component queries. */
4
+ export interface FlagDoc {
5
+ _id: string;
6
+ _creationTime: number;
7
+ key: string;
8
+ description?: string;
9
+ value: boolean;
10
+ createdAt: number;
11
+ updatedAt: number;
12
+ }
13
+
14
+ /** A flag definition passed to {@link Flags.define}. */
15
+ export interface FlagDefinition {
16
+ key: string;
17
+ value: boolean;
18
+ description?: string;
19
+ }
20
+
21
+ export type { EvalReason, FlagEvaluation };
@@ -0,0 +1,36 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `api` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type * as mutations from "../mutations.js";
12
+ import type * as queries from "../queries.js";
13
+
14
+ import type {
15
+ ApiFromModules,
16
+ FilterApi,
17
+ FunctionReference,
18
+ } from "convex/server";
19
+ import { anyApi, componentsGeneric } from "convex/server";
20
+
21
+ const fullApi: ApiFromModules<{
22
+ mutations: typeof mutations;
23
+ queries: typeof queries;
24
+ }> = anyApi as any;
25
+
26
+ export const api: FilterApi<
27
+ typeof fullApi,
28
+ FunctionReference<any, "public">
29
+ > = anyApi as any;
30
+
31
+ export const internal: FilterApi<
32
+ typeof fullApi,
33
+ FunctionReference<any, "internal">
34
+ > = anyApi as any;
35
+
36
+ export const components = componentsGeneric();
@@ -0,0 +1,74 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type { FunctionReference } from "convex/server";
12
+
13
+ type FlagDoc = {
14
+ _id: string;
15
+ _creationTime: number;
16
+ key: string;
17
+ description?: string;
18
+ value: boolean;
19
+ createdAt: number;
20
+ updatedAt: number;
21
+ };
22
+
23
+ type FlagEvaluation = { value: boolean; reason: string };
24
+
25
+ /**
26
+ * A utility for referencing a Convex component's exposed API.
27
+ *
28
+ * Useful when expecting a parameter like `components.flags`.
29
+ */
30
+ export type ComponentApi<Name extends string | undefined = string | undefined> =
31
+ {
32
+ mutations: {
33
+ define: FunctionReference<
34
+ "mutation",
35
+ "internal",
36
+ { key: string; value: boolean; description?: string },
37
+ string,
38
+ Name
39
+ >;
40
+ enable: FunctionReference<"mutation", "internal", { key: string }, null, Name>;
41
+ disable: FunctionReference<
42
+ "mutation",
43
+ "internal",
44
+ { key: string },
45
+ null,
46
+ Name
47
+ >;
48
+ remove: FunctionReference<"mutation", "internal", { key: string }, null, Name>;
49
+ };
50
+ queries: {
51
+ get: FunctionReference<
52
+ "query",
53
+ "internal",
54
+ { key: string },
55
+ FlagDoc | null,
56
+ Name
57
+ >;
58
+ list: FunctionReference<"query", "internal", {}, Array<FlagDoc>, Name>;
59
+ evaluate: FunctionReference<
60
+ "query",
61
+ "internal",
62
+ { key: string },
63
+ FlagEvaluation,
64
+ Name
65
+ >;
66
+ all: FunctionReference<
67
+ "query",
68
+ "internal",
69
+ {},
70
+ Record<string, FlagEvaluation>,
71
+ Name
72
+ >;
73
+ };
74
+ };
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -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("flags");
4
+
5
+ // Nest official child components here, e.g.:
6
+ // import sharded from "@convex-dev/sharded-counter/convex.config";
7
+ // component.use(sharded);
8
+
9
+ export default component;
@@ -0,0 +1,89 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "./_generated/server.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import type { MutationCtx } from "./_generated/server.js";
5
+
6
+ async function findByKey(
7
+ ctx: MutationCtx,
8
+ key: string,
9
+ ): Promise<Doc<"flags"> | null> {
10
+ return await ctx.db
11
+ .query("flags")
12
+ .withIndex("by_key", (q) => q.eq("key", key))
13
+ .unique();
14
+ }
15
+
16
+ /** Create a flag, or update its value/description if the key already exists. */
17
+ export const define = mutation({
18
+ args: {
19
+ key: v.string(),
20
+ value: v.boolean(),
21
+ description: v.optional(v.string()),
22
+ },
23
+ returns: v.id("flags"),
24
+ handler: async (ctx, args) => {
25
+ const now = Date.now();
26
+ const existing = await findByKey(ctx, args.key);
27
+ if (existing !== null) {
28
+ await ctx.db.patch(existing._id, {
29
+ value: args.value,
30
+ description: args.description,
31
+ updatedAt: now,
32
+ });
33
+ return existing._id;
34
+ }
35
+ return await ctx.db.insert("flags", {
36
+ key: args.key,
37
+ value: args.value,
38
+ description: args.description,
39
+ createdAt: now,
40
+ updatedAt: now,
41
+ });
42
+ },
43
+ });
44
+
45
+ async function setValue(
46
+ ctx: MutationCtx,
47
+ key: string,
48
+ value: boolean,
49
+ ): Promise<void> {
50
+ const flag = await findByKey(ctx, key);
51
+ if (flag === null) {
52
+ throw new Error("FLAG_NOT_FOUND");
53
+ }
54
+ await ctx.db.patch(flag._id, { value, updatedAt: Date.now() });
55
+ }
56
+
57
+ /** Turn a flag on (set its value to `true`). */
58
+ export const enable = mutation({
59
+ args: { key: v.string() },
60
+ returns: v.null(),
61
+ handler: async (ctx, args) => {
62
+ await setValue(ctx, args.key, true);
63
+ return null;
64
+ },
65
+ });
66
+
67
+ /** Turn a flag off (set its value to `false`). */
68
+ export const disable = mutation({
69
+ args: { key: v.string() },
70
+ returns: v.null(),
71
+ handler: async (ctx, args) => {
72
+ await setValue(ctx, args.key, false);
73
+ return null;
74
+ },
75
+ });
76
+
77
+ /** Permanently delete a flag. */
78
+ export const remove = mutation({
79
+ args: { key: v.string() },
80
+ returns: v.null(),
81
+ handler: async (ctx, args) => {
82
+ const flag = await findByKey(ctx, args.key);
83
+ if (flag === null) {
84
+ throw new Error("FLAG_NOT_FOUND");
85
+ }
86
+ await ctx.db.delete(flag._id);
87
+ return null;
88
+ },
89
+ });
@@ -0,0 +1,55 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "./_generated/server.js";
3
+ import { evaluation, flagDoc } from "./validators.js";
4
+ import { EVAL_REASON, type FlagEvaluation } from "../shared.js";
5
+
6
+ /** Fetch a single flag definition by key. */
7
+ export const get = query({
8
+ args: { key: v.string() },
9
+ returns: v.union(v.null(), flagDoc),
10
+ handler: async (ctx, args) => {
11
+ return await ctx.db
12
+ .query("flags")
13
+ .withIndex("by_key", (q) => q.eq("key", args.key))
14
+ .unique();
15
+ },
16
+ });
17
+
18
+ /** List every flag definition. */
19
+ export const list = query({
20
+ args: {},
21
+ returns: v.array(flagDoc),
22
+ handler: async (ctx) => {
23
+ return await ctx.db.query("flags").collect();
24
+ },
25
+ });
26
+
27
+ /** Evaluate one flag, returning its value and the reason it was served. */
28
+ export const evaluate = query({
29
+ args: { key: v.string() },
30
+ returns: evaluation,
31
+ handler: async (ctx, args): Promise<FlagEvaluation> => {
32
+ const flag = await ctx.db
33
+ .query("flags")
34
+ .withIndex("by_key", (q) => q.eq("key", args.key))
35
+ .unique();
36
+ if (flag === null) {
37
+ return { value: false, reason: EVAL_REASON.unknown };
38
+ }
39
+ return { value: flag.value, reason: EVAL_REASON.flag };
40
+ },
41
+ });
42
+
43
+ /** Evaluate every flag at once — the bootstrap payload for a reactive client. */
44
+ export const all = query({
45
+ args: {},
46
+ returns: v.record(v.string(), evaluation),
47
+ handler: async (ctx) => {
48
+ const flags = await ctx.db.query("flags").collect();
49
+ const result: Record<string, FlagEvaluation> = {};
50
+ for (const flag of flags) {
51
+ result[flag.key] = { value: flag.value, reason: EVAL_REASON.flag };
52
+ }
53
+ return result;
54
+ },
55
+ });
@@ -0,0 +1,10 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { flagFields } from "./validators.js";
3
+
4
+ /**
5
+ * Sandboxed tables — the component's own concern only. A flag is keyed by an
6
+ * opaque, host-chosen string; the component never models the host's domain.
7
+ */
8
+ export default defineSchema({
9
+ flags: defineTable(flagFields).index("by_key", ["key"]),
10
+ });
@@ -0,0 +1,26 @@
1
+ import { v } from "convex/values";
2
+
3
+ /**
4
+ * Column validators for a stored flag document (excluding Convex system fields).
5
+ * Shared between the schema and the query return validators.
6
+ */
7
+ export const flagFields = {
8
+ key: v.string(),
9
+ description: v.optional(v.string()),
10
+ value: v.boolean(),
11
+ createdAt: v.number(),
12
+ updatedAt: v.number(),
13
+ };
14
+
15
+ /** Public shape of a flag document returned by queries. */
16
+ export const flagDoc = v.object({
17
+ _id: v.id("flags"),
18
+ _creationTime: v.number(),
19
+ ...flagFields,
20
+ });
21
+
22
+ /** Result of evaluating one flag: the boolean value plus a reason code. */
23
+ export const evaluation = v.object({
24
+ value: v.boolean(),
25
+ reason: v.string(),
26
+ });
package/src/shared.ts ADDED
@@ -0,0 +1,21 @@
1
+ /** Shared constants + types used by both `client/` and `component/`. */
2
+
3
+ /**
4
+ * Why an evaluation returned the value it did. Stable string codes so hosts can
5
+ * branch on the reason without parsing prose.
6
+ */
7
+ export const EVAL_REASON = {
8
+ /** A defined flag served its current value. */
9
+ flag: "flag",
10
+ /** No flag exists for the key; the safe default (`false`) was served. */
11
+ unknown: "unknown",
12
+ } as const;
13
+
14
+ /** The set of evaluation reason codes. */
15
+ export type EvalReason = (typeof EVAL_REASON)[keyof typeof EVAL_REASON];
16
+
17
+ /** Result of evaluating a single flag. */
18
+ export interface FlagEvaluation {
19
+ value: boolean;
20
+ reason: EvalReason;
21
+ }