@vllnt/convex-flags 0.1.0-canary.bf53746 → 0.1.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.
- package/README.md +84 -25
- package/dist/client/index.d.ts +62 -16
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +54 -15
- package/dist/client/index.js.map +1 -1
- package/dist/client/types.d.ts +30 -4
- package/dist/client/types.d.ts.map +1 -1
- package/dist/component/_generated/api.d.ts +19 -1
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js +16 -0
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +174 -24
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/_generated/server.d.ts +12 -0
- package/dist/component/_generated/server.d.ts.map +1 -1
- package/dist/component/_generated/server.js +2 -0
- package/dist/component/_generated/server.js.map +1 -1
- package/dist/component/convex.config.d.ts.map +1 -1
- package/dist/component/mutations.d.ts +90 -5
- package/dist/component/mutations.d.ts.map +1 -1
- package/dist/component/mutations.js +144 -10
- package/dist/component/mutations.js.map +1 -1
- package/dist/component/queries.d.ts +90 -13
- package/dist/component/queries.d.ts.map +1 -1
- package/dist/component/queries.js +58 -12
- package/dist/component/queries.js.map +1 -1
- package/dist/component/schema.d.ts +138 -4
- package/dist/component/schema.d.ts.map +1 -1
- package/dist/component/schema.js +7 -1
- package/dist/component/schema.js.map +1 -1
- package/dist/component/validators.d.ts +354 -14
- package/dist/component/validators.d.ts.map +1 -1
- package/dist/component/validators.js +57 -6
- package/dist/component/validators.js.map +1 -1
- package/dist/react/index.d.ts +29 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +35 -0
- package/dist/react/index.js.map +1 -0
- package/dist/shared.d.ts +102 -4
- package/dist/shared.d.ts.map +1 -1
- package/dist/shared.js +126 -3
- package/dist/shared.js.map +1 -1
- package/package.json +36 -18
- package/src/client/index.ts +145 -20
- package/src/client/types.ts +48 -4
- package/src/component/_generated/api.ts +19 -1
- package/src/component/_generated/component.ts +259 -23
- package/src/component/_generated/server.ts +13 -0
- package/src/component/mutations.ts +160 -19
- package/src/component/queries.ts +74 -12
- package/src/component/schema.ts +7 -1
- package/src/component/validators.ts +87 -6
- package/src/react/index.test.ts +52 -0
- package/src/react/index.ts +69 -0
- package/src/shared.ts +235 -4
- package/src/status-backward-compat.test.ts +51 -0
package/src/component/queries.ts
CHANGED
|
@@ -1,17 +1,48 @@
|
|
|
1
1
|
import { v } from "convex/values";
|
|
2
2
|
import { query } from "./_generated/server.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import type { Doc } from "./_generated/dataModel.js";
|
|
4
|
+
import type { QueryCtx } from "./_generated/server.js";
|
|
5
|
+
import { evalContext, evaluation, flagDoc, variantValue } from "./validators.js";
|
|
6
|
+
import {
|
|
7
|
+
EVAL_REASON,
|
|
8
|
+
evaluateFlag,
|
|
9
|
+
withStatus,
|
|
10
|
+
type EvalContext,
|
|
11
|
+
type FlagEvaluation,
|
|
12
|
+
type VariantValue,
|
|
13
|
+
} from "../shared.js";
|
|
14
|
+
|
|
15
|
+
/** Resolve a single flag: a per-subject override wins, otherwise the engine. */
|
|
16
|
+
async function resolve(
|
|
17
|
+
ctx: QueryCtx,
|
|
18
|
+
flag: Doc<"flags">,
|
|
19
|
+
context: EvalContext,
|
|
20
|
+
): Promise<FlagEvaluation> {
|
|
21
|
+
const subjectRef = context.subjectRef;
|
|
22
|
+
if (subjectRef !== undefined) {
|
|
23
|
+
const override = await ctx.db
|
|
24
|
+
.query("overrides")
|
|
25
|
+
.withIndex("by_key_subject", (q) =>
|
|
26
|
+
q.eq("key", flag.key).eq("subjectRef", subjectRef),
|
|
27
|
+
)
|
|
28
|
+
.unique();
|
|
29
|
+
if (override !== null) {
|
|
30
|
+
return { value: override.value, reason: EVAL_REASON.override };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return evaluateFlag(flag.key, flag, context);
|
|
34
|
+
}
|
|
5
35
|
|
|
6
36
|
/** Fetch a single flag definition by key. */
|
|
7
37
|
export const get = query({
|
|
8
38
|
args: { key: v.string() },
|
|
9
39
|
returns: v.union(v.null(), flagDoc),
|
|
10
40
|
handler: async (ctx, args) => {
|
|
11
|
-
|
|
41
|
+
const flag = await ctx.db
|
|
12
42
|
.query("flags")
|
|
13
43
|
.withIndex("by_key", (q) => q.eq("key", args.key))
|
|
14
44
|
.unique();
|
|
45
|
+
return flag === null ? null : withStatus(flag);
|
|
15
46
|
},
|
|
16
47
|
});
|
|
17
48
|
|
|
@@ -20,13 +51,22 @@ export const list = query({
|
|
|
20
51
|
args: {},
|
|
21
52
|
returns: v.array(flagDoc),
|
|
22
53
|
handler: async (ctx) => {
|
|
23
|
-
return await ctx.db.query("flags").collect();
|
|
54
|
+
return (await ctx.db.query("flags").collect()).map(withStatus);
|
|
24
55
|
},
|
|
25
56
|
});
|
|
26
57
|
|
|
27
|
-
/**
|
|
58
|
+
/**
|
|
59
|
+
* Evaluate one flag against optional context. Resolution order: per-subject
|
|
60
|
+
* override → archived → targeting rules → fallthrough rollout → flag value. An
|
|
61
|
+
* unknown key serves the caller `default` (reason `default`) or `false`
|
|
62
|
+
* (reason `unknown`).
|
|
63
|
+
*/
|
|
28
64
|
export const evaluate = query({
|
|
29
|
-
args: {
|
|
65
|
+
args: {
|
|
66
|
+
key: v.string(),
|
|
67
|
+
context: v.optional(evalContext),
|
|
68
|
+
default: v.optional(variantValue),
|
|
69
|
+
},
|
|
30
70
|
returns: evaluation,
|
|
31
71
|
handler: async (ctx, args): Promise<FlagEvaluation> => {
|
|
32
72
|
const flag = await ctx.db
|
|
@@ -34,21 +74,43 @@ export const evaluate = query({
|
|
|
34
74
|
.withIndex("by_key", (q) => q.eq("key", args.key))
|
|
35
75
|
.unique();
|
|
36
76
|
if (flag === null) {
|
|
37
|
-
return
|
|
77
|
+
return args.default !== undefined
|
|
78
|
+
? { value: args.default, reason: EVAL_REASON.default }
|
|
79
|
+
: { value: false, reason: EVAL_REASON.unknown };
|
|
38
80
|
}
|
|
39
|
-
return
|
|
81
|
+
return await resolve(ctx, flag, args.context ?? {});
|
|
40
82
|
},
|
|
41
83
|
});
|
|
42
84
|
|
|
43
|
-
/**
|
|
85
|
+
/**
|
|
86
|
+
* Evaluate every flag at once against optional context — the bootstrap payload
|
|
87
|
+
* for a reactive client. Per-subject overrides for the context's `subjectRef`
|
|
88
|
+
* are applied (loaded in a single query, never inside the loop).
|
|
89
|
+
*/
|
|
44
90
|
export const all = query({
|
|
45
|
-
args: {},
|
|
91
|
+
args: { context: v.optional(evalContext) },
|
|
46
92
|
returns: v.record(v.string(), evaluation),
|
|
47
|
-
handler: async (ctx) => {
|
|
93
|
+
handler: async (ctx, args) => {
|
|
94
|
+
const context = args.context ?? {};
|
|
48
95
|
const flags = await ctx.db.query("flags").collect();
|
|
96
|
+
const overrideValues: Record<string, VariantValue> = {};
|
|
97
|
+
const subjectRef = context.subjectRef;
|
|
98
|
+
if (subjectRef !== undefined) {
|
|
99
|
+
const overrides = await ctx.db
|
|
100
|
+
.query("overrides")
|
|
101
|
+
.withIndex("by_subject", (q) => q.eq("subjectRef", subjectRef))
|
|
102
|
+
.collect();
|
|
103
|
+
for (const override of overrides) {
|
|
104
|
+
overrideValues[override.key] = override.value;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
49
107
|
const result: Record<string, FlagEvaluation> = {};
|
|
50
108
|
for (const flag of flags) {
|
|
51
|
-
|
|
109
|
+
const overridden = overrideValues[flag.key];
|
|
110
|
+
result[flag.key] =
|
|
111
|
+
overridden !== undefined
|
|
112
|
+
? { value: overridden, reason: EVAL_REASON.override }
|
|
113
|
+
: evaluateFlag(flag.key, flag, context);
|
|
52
114
|
}
|
|
53
115
|
return result;
|
|
54
116
|
},
|
package/src/component/schema.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { defineSchema, defineTable } from "convex/server";
|
|
2
|
-
import { flagFields } from "./validators.js";
|
|
2
|
+
import { flagFields, overrideFields } from "./validators.js";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Sandboxed tables — the component's own concern only. A flag is keyed by an
|
|
@@ -7,4 +7,10 @@ import { flagFields } from "./validators.js";
|
|
|
7
7
|
*/
|
|
8
8
|
export default defineSchema({
|
|
9
9
|
flags: defineTable(flagFields).index("by_key", ["key"]),
|
|
10
|
+
// Per-subject overrides: force a flag's value for one subject. Indexed for
|
|
11
|
+
// both the single-flag read (by_key_subject) and the bulk `all` read
|
|
12
|
+
// (by_subject), so neither path queries inside a loop.
|
|
13
|
+
overrides: defineTable(overrideFields)
|
|
14
|
+
.index("by_key_subject", ["key", "subjectRef"])
|
|
15
|
+
.index("by_subject", ["subjectRef"]),
|
|
10
16
|
});
|
|
@@ -1,5 +1,57 @@
|
|
|
1
1
|
import { v } from "convex/values";
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* A flag/variant value — typed primitives only (boolean, string, number). The
|
|
5
|
+
* client class is generic over the host's concrete value type; the component
|
|
6
|
+
* stores the typed union. No `v.any()`.
|
|
7
|
+
*/
|
|
8
|
+
export const variantValue = v.union(v.boolean(), v.string(), v.number());
|
|
9
|
+
|
|
10
|
+
/** An attribute value usable in a targeting comparison. */
|
|
11
|
+
export const attributeValue = v.union(v.boolean(), v.string(), v.number());
|
|
12
|
+
|
|
13
|
+
/** Comparison operators available to a targeting condition. */
|
|
14
|
+
export const conditionOp = v.union(
|
|
15
|
+
v.literal("eq"),
|
|
16
|
+
v.literal("neq"),
|
|
17
|
+
v.literal("in"),
|
|
18
|
+
v.literal("nin"),
|
|
19
|
+
v.literal("contains"),
|
|
20
|
+
v.literal("gt"),
|
|
21
|
+
v.literal("gte"),
|
|
22
|
+
v.literal("lt"),
|
|
23
|
+
v.literal("lte"),
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
/** One targeting condition: `<attribute> <op> <values>`. */
|
|
27
|
+
export const condition = v.object({
|
|
28
|
+
attribute: v.string(),
|
|
29
|
+
op: conditionOp,
|
|
30
|
+
values: v.array(attributeValue),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** One weighted entry in a rollout's distribution. */
|
|
34
|
+
export const split = v.object({ value: variantValue, weight: v.number() });
|
|
35
|
+
|
|
36
|
+
/** A deterministic weighted distribution across variant values. */
|
|
37
|
+
export const rollout = v.object({
|
|
38
|
+
splits: v.array(split),
|
|
39
|
+
by: v.optional(v.string()),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** A declared variant (metadata for tooling / labels). */
|
|
43
|
+
export const variant = v.object({ value: variantValue, label: v.optional(v.string()) });
|
|
44
|
+
|
|
45
|
+
/** A targeting rule: all conditions AND; first matching rule (in order) wins. */
|
|
46
|
+
export const rule = v.object({
|
|
47
|
+
conditions: v.array(condition),
|
|
48
|
+
value: v.optional(variantValue),
|
|
49
|
+
rollout: v.optional(rollout),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** Lifecycle status of a flag. */
|
|
53
|
+
export const flagStatus = v.union(v.literal("active"), v.literal("archived"));
|
|
54
|
+
|
|
3
55
|
/**
|
|
4
56
|
* Column validators for a stored flag document (excluding Convex system fields).
|
|
5
57
|
* Shared between the schema and the query return validators.
|
|
@@ -7,20 +59,49 @@ import { v } from "convex/values";
|
|
|
7
59
|
export const flagFields = {
|
|
8
60
|
key: v.string(),
|
|
9
61
|
description: v.optional(v.string()),
|
|
10
|
-
value:
|
|
62
|
+
value: variantValue,
|
|
63
|
+
variants: v.optional(v.array(variant)),
|
|
64
|
+
rules: v.optional(v.array(rule)),
|
|
65
|
+
rollout: v.optional(rollout),
|
|
66
|
+
status: v.optional(flagStatus),
|
|
11
67
|
createdAt: v.number(),
|
|
12
68
|
updatedAt: v.number(),
|
|
13
69
|
};
|
|
14
70
|
|
|
15
|
-
/** Public shape of a flag document returned by queries.
|
|
71
|
+
/** Public shape of a flag document returned by queries. `status` is materialized
|
|
72
|
+
* (a legacy row's absent status reads as active), so it is required here even
|
|
73
|
+
* though the stored column is optional. */
|
|
16
74
|
export const flagDoc = v.object({
|
|
17
75
|
_id: v.id("flags"),
|
|
18
76
|
_creationTime: v.number(),
|
|
19
77
|
...flagFields,
|
|
78
|
+
status: flagStatus,
|
|
20
79
|
});
|
|
21
80
|
|
|
22
|
-
/**
|
|
23
|
-
export const
|
|
24
|
-
|
|
25
|
-
|
|
81
|
+
/** Column validators for a stored per-subject override. */
|
|
82
|
+
export const overrideFields = {
|
|
83
|
+
key: v.string(),
|
|
84
|
+
subjectRef: v.string(),
|
|
85
|
+
value: variantValue,
|
|
86
|
+
createdAt: v.number(),
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** Host-supplied, per-evaluation context. */
|
|
90
|
+
export const evalContext = v.object({
|
|
91
|
+
subjectRef: v.optional(v.string()),
|
|
92
|
+
attributes: v.optional(v.record(v.string(), attributeValue)),
|
|
26
93
|
});
|
|
94
|
+
|
|
95
|
+
/** Stable evaluation reason codes (kept in sync with `EVAL_REASON` in shared.ts). */
|
|
96
|
+
export const evalReason = v.union(
|
|
97
|
+
v.literal("flag"),
|
|
98
|
+
v.literal("rule"),
|
|
99
|
+
v.literal("rollout"),
|
|
100
|
+
v.literal("override"),
|
|
101
|
+
v.literal("disabled"),
|
|
102
|
+
v.literal("default"),
|
|
103
|
+
v.literal("unknown"),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
/** Result of evaluating one flag: the value plus a reason code. */
|
|
107
|
+
export const evaluation = v.object({ value: variantValue, reason: evalReason });
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { renderHook } from "@testing-library/react";
|
|
3
|
+
import { makeFunctionReference } from "convex/server";
|
|
4
|
+
import { beforeEach, expect, test, vi } from "vitest";
|
|
5
|
+
import { useFlag, useFlags, type AllRef, type EvaluateRef } from "./index.js";
|
|
6
|
+
|
|
7
|
+
const { useQuerySpy } = vi.hoisted(() => ({ useQuerySpy: vi.fn() }));
|
|
8
|
+
vi.mock("convex/react", () => ({ useQuery: useQuerySpy }));
|
|
9
|
+
|
|
10
|
+
const evalRef: EvaluateRef = makeFunctionReference<"query">("flags:evaluate");
|
|
11
|
+
const allRef: AllRef = makeFunctionReference<"query">("flags:all");
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
useQuerySpy.mockReset();
|
|
15
|
+
useQuerySpy.mockReturnValue({ value: true, reason: "flag" });
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test("useFlag forwards key + context + default and returns the query result", () => {
|
|
19
|
+
const { result } = renderHook(() =>
|
|
20
|
+
useFlag(evalRef, "new-checkout", {
|
|
21
|
+
context: { subjectRef: "u1", attributes: { plan: "pro" } },
|
|
22
|
+
default: "off",
|
|
23
|
+
}),
|
|
24
|
+
);
|
|
25
|
+
expect(useQuerySpy).toHaveBeenCalledWith(evalRef, {
|
|
26
|
+
key: "new-checkout",
|
|
27
|
+
context: { subjectRef: "u1", attributes: { plan: "pro" } },
|
|
28
|
+
default: "off",
|
|
29
|
+
});
|
|
30
|
+
expect(result.current).toEqual({ value: true, reason: "flag" });
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("useFlag works with no options", () => {
|
|
34
|
+
renderHook(() => useFlag(evalRef, "k"));
|
|
35
|
+
expect(useQuerySpy).toHaveBeenCalledWith(evalRef, {
|
|
36
|
+
key: "k",
|
|
37
|
+
context: undefined,
|
|
38
|
+
default: undefined,
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("useFlags forwards context", () => {
|
|
43
|
+
useQuerySpy.mockReturnValue({ k: { value: true, reason: "flag" } });
|
|
44
|
+
const { result } = renderHook(() => useFlags(allRef, { subjectRef: "u1" }));
|
|
45
|
+
expect(useQuerySpy).toHaveBeenCalledWith(allRef, { context: { subjectRef: "u1" } });
|
|
46
|
+
expect(result.current).toEqual({ k: { value: true, reason: "flag" } });
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("useFlags works with no context", () => {
|
|
50
|
+
renderHook(() => useFlags(allRef));
|
|
51
|
+
expect(useQuerySpy).toHaveBeenCalledWith(allRef, { context: undefined });
|
|
52
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional React layer for `@vllnt/convex-flags`.
|
|
3
|
+
*
|
|
4
|
+
* Thin, tree-shakeable hooks over `convex/react`'s `useQuery`. They wrap the
|
|
5
|
+
* host's own re-exported `evaluate` / `all` query refs — the component never
|
|
6
|
+
* owns the host's `api`. `react` and `convex/react` are optional peer deps: a
|
|
7
|
+
* backend-only consumer never imports this entry and pulls in zero React.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```tsx
|
|
11
|
+
* // convex/flags.ts (host) re-exports the query refs from its wrappers, then:
|
|
12
|
+
* const evaluation = useFlag(api.flags.evaluate, "new-checkout", { context: { subjectRef } });
|
|
13
|
+
* if (evaluation?.value === true) { ... }
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
import { useQuery } from "convex/react";
|
|
17
|
+
import type { FunctionReference } from "convex/server";
|
|
18
|
+
import type { EvalContext, FlagEvaluation, VariantValue } from "../shared.js";
|
|
19
|
+
|
|
20
|
+
/** The host's re-exported `evaluate` query reference. */
|
|
21
|
+
export type EvaluateRef = FunctionReference<
|
|
22
|
+
"query",
|
|
23
|
+
"public",
|
|
24
|
+
{ key: string; context?: EvalContext; default?: VariantValue },
|
|
25
|
+
FlagEvaluation
|
|
26
|
+
>;
|
|
27
|
+
|
|
28
|
+
/** The host's re-exported `all` query reference. */
|
|
29
|
+
export type AllRef = FunctionReference<
|
|
30
|
+
"query",
|
|
31
|
+
"public",
|
|
32
|
+
{ context?: EvalContext },
|
|
33
|
+
Record<string, FlagEvaluation>
|
|
34
|
+
>;
|
|
35
|
+
|
|
36
|
+
/** Options for {@link useFlag}. */
|
|
37
|
+
export interface UseFlagOptions {
|
|
38
|
+
context?: EvalContext;
|
|
39
|
+
default?: VariantValue;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Reactively evaluate a single flag. Returns `undefined` while the query loads,
|
|
44
|
+
* then the {@link FlagEvaluation}. Re-renders whenever the flag changes.
|
|
45
|
+
*/
|
|
46
|
+
export function useFlag(
|
|
47
|
+
query: EvaluateRef,
|
|
48
|
+
key: string,
|
|
49
|
+
options?: UseFlagOptions,
|
|
50
|
+
): FlagEvaluation | undefined {
|
|
51
|
+
return useQuery(query, {
|
|
52
|
+
key,
|
|
53
|
+
context: options?.context,
|
|
54
|
+
default: options?.default,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Reactively evaluate every flag against optional context. Returns `undefined`
|
|
60
|
+
* while loading, then a map of flag key → {@link FlagEvaluation}.
|
|
61
|
+
*/
|
|
62
|
+
export function useFlags(
|
|
63
|
+
query: AllRef,
|
|
64
|
+
context?: EvalContext,
|
|
65
|
+
): Record<string, FlagEvaluation> | undefined {
|
|
66
|
+
return useQuery(query, { context });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type { EvalContext, FlagEvaluation, VariantValue };
|
package/src/shared.ts
CHANGED
|
@@ -1,21 +1,252 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Shared constants, types, and the pure evaluation engine used by both
|
|
3
|
+
* `client/` and `component/`.
|
|
4
|
+
*
|
|
5
|
+
* The engine is intentionally pure — no `ctx`, no database — so it can be
|
|
6
|
+
* reused by the component queries and exercised exhaustively end-to-end. Per-
|
|
7
|
+
* subject overrides and unknown-key handling live in the query layer (they need
|
|
8
|
+
* a database read); everything from a flag document downward lives here.
|
|
9
|
+
*/
|
|
2
10
|
|
|
3
11
|
/**
|
|
4
12
|
* Why an evaluation returned the value it did. Stable string codes so hosts can
|
|
5
13
|
* branch on the reason without parsing prose.
|
|
6
14
|
*/
|
|
7
15
|
export const EVAL_REASON = {
|
|
8
|
-
/**
|
|
16
|
+
/** Served the flag's fallthrough value — no rule or rollout matched. */
|
|
9
17
|
flag: "flag",
|
|
10
|
-
/**
|
|
18
|
+
/** A targeting rule matched and served a fixed value. */
|
|
19
|
+
rule: "rule",
|
|
20
|
+
/** A percentage rollout deterministically assigned the value. */
|
|
21
|
+
rollout: "rollout",
|
|
22
|
+
/** A per-subject override forced the value. */
|
|
23
|
+
override: "override",
|
|
24
|
+
/** The flag is archived; targeting was skipped and its base value served. */
|
|
25
|
+
disabled: "disabled",
|
|
26
|
+
/** Unknown key; the caller-supplied default was served. */
|
|
27
|
+
default: "default",
|
|
28
|
+
/** Unknown key and no caller default; the safe default (`false`) was served. */
|
|
11
29
|
unknown: "unknown",
|
|
12
30
|
} as const;
|
|
13
31
|
|
|
14
32
|
/** The set of evaluation reason codes. */
|
|
15
33
|
export type EvalReason = (typeof EVAL_REASON)[keyof typeof EVAL_REASON];
|
|
16
34
|
|
|
35
|
+
/**
|
|
36
|
+
* A flag/variant value. Typed primitives only — never `v.any()`. JSON-object
|
|
37
|
+
* variants are a documented future last resort (tracked in the roadmap).
|
|
38
|
+
*/
|
|
39
|
+
export type VariantValue = boolean | string | number;
|
|
40
|
+
|
|
41
|
+
/** An attribute value usable in a targeting comparison. */
|
|
42
|
+
export type AttributeValue = boolean | string | number;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Host-supplied, per-evaluation context. Opaque to the component: the host owns
|
|
46
|
+
* what `subjectRef` and the attribute names/values mean.
|
|
47
|
+
*/
|
|
48
|
+
export interface EvalContext {
|
|
49
|
+
/** Stable identifier used for rollout bucketing (e.g. a user or session ref). */
|
|
50
|
+
subjectRef?: string;
|
|
51
|
+
/** Targeting attributes, keyed by host-chosen names. */
|
|
52
|
+
attributes?: Record<string, AttributeValue>;
|
|
53
|
+
}
|
|
54
|
+
|
|
17
55
|
/** Result of evaluating a single flag. */
|
|
18
56
|
export interface FlagEvaluation {
|
|
19
|
-
value:
|
|
57
|
+
value: VariantValue;
|
|
20
58
|
reason: EvalReason;
|
|
21
59
|
}
|
|
60
|
+
|
|
61
|
+
/** Comparison operators available to a targeting condition. */
|
|
62
|
+
export type ConditionOp =
|
|
63
|
+
| "eq"
|
|
64
|
+
| "neq"
|
|
65
|
+
| "in"
|
|
66
|
+
| "nin"
|
|
67
|
+
| "contains"
|
|
68
|
+
| "gt"
|
|
69
|
+
| "gte"
|
|
70
|
+
| "lt"
|
|
71
|
+
| "lte";
|
|
72
|
+
|
|
73
|
+
/** One targeting condition: `<attribute> <op> <values>`. */
|
|
74
|
+
export interface Condition {
|
|
75
|
+
attribute: string;
|
|
76
|
+
op: ConditionOp;
|
|
77
|
+
values: AttributeValue[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** One weighted entry in a rollout's distribution. */
|
|
81
|
+
export interface Split {
|
|
82
|
+
value: VariantValue;
|
|
83
|
+
/** Relative weight; normalized across the rollout's splits. */
|
|
84
|
+
weight: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A deterministic weighted distribution across variant values. */
|
|
88
|
+
export interface Rollout {
|
|
89
|
+
splits: Split[];
|
|
90
|
+
/** Context attribute to bucket by; defaults to `subjectRef` when omitted. */
|
|
91
|
+
by?: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A declared variant (metadata for tooling / labels). */
|
|
95
|
+
export interface Variant {
|
|
96
|
+
value: VariantValue;
|
|
97
|
+
label?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* A targeting rule. All `conditions` must match (AND); rules are evaluated in
|
|
102
|
+
* order and the first match wins. The outcome is a fixed `value` or a `rollout`.
|
|
103
|
+
*/
|
|
104
|
+
export interface Rule {
|
|
105
|
+
conditions: Condition[];
|
|
106
|
+
value?: VariantValue;
|
|
107
|
+
rollout?: Rollout;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The evaluatable shape of a stored flag (the engine's input). */
|
|
111
|
+
export interface EvaluableFlag {
|
|
112
|
+
value: VariantValue;
|
|
113
|
+
status?: "active" | "archived";
|
|
114
|
+
rules?: Rule[];
|
|
115
|
+
rollout?: Rollout;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Operator implementations. A table (not a switch) so there is no unreachable
|
|
119
|
+
* default branch — every operator resolves to one of these. */
|
|
120
|
+
const OPERATORS: Record<
|
|
121
|
+
ConditionOp,
|
|
122
|
+
(actual: AttributeValue, values: AttributeValue[]) => boolean
|
|
123
|
+
> = {
|
|
124
|
+
eq: (actual, values) => actual === values[0],
|
|
125
|
+
neq: (actual, values) => actual !== values[0],
|
|
126
|
+
in: (actual, values) => values.includes(actual),
|
|
127
|
+
nin: (actual, values) => !values.includes(actual),
|
|
128
|
+
contains: (actual, values) =>
|
|
129
|
+
typeof actual === "string" &&
|
|
130
|
+
typeof values[0] === "string" &&
|
|
131
|
+
actual.includes(values[0]),
|
|
132
|
+
gt: (actual, values) =>
|
|
133
|
+
typeof actual === "number" && typeof values[0] === "number" && actual > values[0],
|
|
134
|
+
gte: (actual, values) =>
|
|
135
|
+
typeof actual === "number" && typeof values[0] === "number" && actual >= values[0],
|
|
136
|
+
lt: (actual, values) =>
|
|
137
|
+
typeof actual === "number" && typeof values[0] === "number" && actual < values[0],
|
|
138
|
+
lte: (actual, values) =>
|
|
139
|
+
typeof actual === "number" && typeof values[0] === "number" && actual <= values[0],
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/** Does a single condition hold for the given context? A missing attribute never
|
|
143
|
+
* matches (mirrors how mainstream flag SDKs treat absent targeting data). */
|
|
144
|
+
function matchesCondition(condition: Condition, context: EvalContext): boolean {
|
|
145
|
+
const actual = context.attributes?.[condition.attribute];
|
|
146
|
+
if (actual === undefined) {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
return OPERATORS[condition.op](actual, condition.values);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Do all of a rule's conditions hold? An empty condition list always matches
|
|
153
|
+
* (a catch-all rule). */
|
|
154
|
+
function matchesRule(rule: Rule, context: EvalContext): boolean {
|
|
155
|
+
return rule.conditions.every((condition) => matchesCondition(condition, context));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Deterministic 32-bit FNV-1a hash of a string → uint32. */
|
|
159
|
+
export function hashString(input: string): number {
|
|
160
|
+
let hash = 0x811c9dc5;
|
|
161
|
+
for (let i = 0; i < input.length; i++) {
|
|
162
|
+
hash ^= input.charCodeAt(i);
|
|
163
|
+
hash = Math.imul(hash, 0x01000193);
|
|
164
|
+
}
|
|
165
|
+
return hash >>> 0;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Deterministically pick a split's value by hashing `flagKey:subject` across the
|
|
170
|
+
* cumulative weights. Returns `null` when no split has positive weight.
|
|
171
|
+
*/
|
|
172
|
+
export function pickSplit(
|
|
173
|
+
flagKey: string,
|
|
174
|
+
subject: string,
|
|
175
|
+
splits: Split[],
|
|
176
|
+
): VariantValue | null {
|
|
177
|
+
const positive = splits.filter((split) => split.weight > 0);
|
|
178
|
+
const total = positive.reduce((sum, split) => sum + split.weight, 0);
|
|
179
|
+
if (total === 0) {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
const point = hashString(`${flagKey}:${subject}`) % total;
|
|
183
|
+
let cumulative = 0;
|
|
184
|
+
let chosen: VariantValue | null = null;
|
|
185
|
+
for (const split of positive) {
|
|
186
|
+
cumulative += split.weight;
|
|
187
|
+
if (chosen === null && point < cumulative) {
|
|
188
|
+
chosen = split.value;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return chosen;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Resolve a rollout to a value, or `null` if it cannot bucket (no rollout, no
|
|
195
|
+
* bucketing subject, or no positive-weight split). */
|
|
196
|
+
function resolveRollout(
|
|
197
|
+
flagKey: string,
|
|
198
|
+
rollout: Rollout | undefined,
|
|
199
|
+
context: EvalContext,
|
|
200
|
+
): VariantValue | null {
|
|
201
|
+
if (rollout === undefined) {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
const subject =
|
|
205
|
+
rollout.by !== undefined ? context.attributes?.[rollout.by] : context.subjectRef;
|
|
206
|
+
if (subject === undefined) {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
return pickSplit(flagKey, String(subject), rollout.splits);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Evaluate a flag against context. Pure — given the same flag document and
|
|
214
|
+
* context it always returns the same result.
|
|
215
|
+
*/
|
|
216
|
+
export function evaluateFlag(
|
|
217
|
+
flagKey: string,
|
|
218
|
+
flag: EvaluableFlag,
|
|
219
|
+
context: EvalContext,
|
|
220
|
+
): FlagEvaluation {
|
|
221
|
+
if (flag.status === "archived") {
|
|
222
|
+
return { value: flag.value, reason: EVAL_REASON.disabled };
|
|
223
|
+
}
|
|
224
|
+
for (const rule of flag.rules ?? []) {
|
|
225
|
+
if (matchesRule(rule, context)) {
|
|
226
|
+
if (rule.value !== undefined) {
|
|
227
|
+
return { value: rule.value, reason: EVAL_REASON.rule };
|
|
228
|
+
}
|
|
229
|
+
const picked = resolveRollout(flagKey, rule.rollout, context);
|
|
230
|
+
if (picked !== null) {
|
|
231
|
+
return { value: picked, reason: EVAL_REASON.rollout };
|
|
232
|
+
}
|
|
233
|
+
return { value: flag.value, reason: EVAL_REASON.flag };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const picked = resolveRollout(flagKey, flag.rollout, context);
|
|
237
|
+
if (picked !== null) {
|
|
238
|
+
return { value: picked, reason: EVAL_REASON.rollout };
|
|
239
|
+
}
|
|
240
|
+
return { value: flag.value, reason: EVAL_REASON.flag };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Materialize a flag's lifecycle status for return to callers: a legacy row
|
|
245
|
+
* written before `status` existed has none and reads as `"active"`. Keeps the
|
|
246
|
+
* stored column optional (deploy-safe) while the public shape stays concrete.
|
|
247
|
+
*/
|
|
248
|
+
export function withStatus<T extends { status?: "active" | "archived" }>(
|
|
249
|
+
flag: T,
|
|
250
|
+
): T & { status: "active" | "archived" } {
|
|
251
|
+
return { ...flag, status: flag.status ?? "active" };
|
|
252
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { flagFields } from "./component/validators.js";
|
|
3
|
+
import { evaluateFlag, withStatus } from "./shared.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Regression guard for #5 — a required `status` field broke deploys for any
|
|
7
|
+
* consumer with flag rows written before `status` existed. The expand fix makes
|
|
8
|
+
* `status` optional and reads an absent status as `"active"`.
|
|
9
|
+
*/
|
|
10
|
+
describe("status backward compatibility (#5)", () => {
|
|
11
|
+
test("the schema validator accepts a row without `status` (legacy data)", () => {
|
|
12
|
+
expect(flagFields.status.isOptional).toBe("optional");
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test("a flag with no `status` is evaluated as active, not disabled", () => {
|
|
16
|
+
expect(evaluateFlag("legacy", { value: true }, {})).toEqual({
|
|
17
|
+
value: true,
|
|
18
|
+
reason: "flag",
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("a status-less flag still runs targeting (absent status !== archived)", () => {
|
|
23
|
+
expect(
|
|
24
|
+
evaluateFlag(
|
|
25
|
+
"legacy",
|
|
26
|
+
{ value: "BASE", rules: [{ conditions: [], value: "RULE" }] },
|
|
27
|
+
{},
|
|
28
|
+
),
|
|
29
|
+
).toEqual({ value: "RULE", reason: "rule" });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("an explicitly archived flag is still disabled", () => {
|
|
33
|
+
expect(evaluateFlag("k", { value: "BASE", status: "archived" }, {})).toEqual({
|
|
34
|
+
value: "BASE",
|
|
35
|
+
reason: "disabled",
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("withStatus materializes an absent status as active for returned docs", () => {
|
|
40
|
+
const legacyRow: { key: string; value: boolean; status?: "active" | "archived" } = {
|
|
41
|
+
key: "legacy",
|
|
42
|
+
value: true,
|
|
43
|
+
};
|
|
44
|
+
expect(withStatus(legacyRow).status).toBe("active");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("withStatus preserves an explicit status", () => {
|
|
48
|
+
const archivedRow = { key: "k", value: true, status: "archived" as const };
|
|
49
|
+
expect(withStatus(archivedRow).status).toBe("archived");
|
|
50
|
+
});
|
|
51
|
+
});
|