Skip to content

Commit 0fe8795

Browse files
authored
feat(cli): generate SDK v2 flag value types (#817)
## What changes - Generate direct-value TypeScript declarations for the Node.js, React, and Vue v2 SDKs. Boolean flags are typed as `boolean`, and Multivariate flag types are inferred from the current Production variants rather than legacy Remote config wrappers. - Read flags and targeting through the management API. Reject incomplete flag lists and targeting responses from the wrong environment. Preserve JSON value types and escape generated property names. - Update the CLI flag commands, configuration schema, and generated agent instructions for SDK v2. Use the same format list for command options, interactive setup, and generation. ## Compatibility This adds a major Changeset for `@reflag/cli`. Projects using SDK v1 should stay on CLI 1.x for legacy type generation. ## Verification - Synced `main` (`a2389e8`) through merge commit `ba31b03`, preserving history and the generated-declaration CI check. No additional CLI implementation changes were made in this sync. - Fresh local verification on the merged tree: immutable Yarn install, 10 scoped SDK/provider/CLI/Express builds, **1,050 workspace runtime tests** (including **58 CLI tests**), and **48 Browser E2E cases across Chromium/Firefox/WebKit** pass. - Generated declarations and registered-default checks compile against the Node.js, React, and Vue v2 SDKs in the workspace. Package CI runs this check after building the SDKs. - **17 release safeguards**, **five docs-publication tests**, **three docs-transform tests**, the public manifest check, docs generation, formatting and lint pass. Management's checked-in TypeScript sources also compile. Full generator-backed Management/root builds remain a fresh CI gate because Java is unavailable locally; Next.js production-app builds are outside the local scoped build run. - The real Changesets plan selects **only `@reflag/cli`, at `2.0.0-next.1`**, for a major prerelease under `next`. No package publication or dist-tag change was performed. - The JSON-schema review comment is addressed with Zod 4's built-in `z.json()` and its thread is resolved. - [Earlier Package CI for the refactor, before the main sync](https://github.com/reflagcom/javascript/actions/runs/44944537797). --------- Co-authored-by: Ron Cohen <744+roncohen@users.noreply.github.com>
1 parent a2389e8 commit 0fe8795

21 files changed

Lines changed: 786 additions & 543 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@reflag/cli": major
3+
---
4+
5+
Move the CLI to the v2 management flag API and generate direct-value declarations from current production-environment multivariate variants instead of legacy config wrappers. Add Vue generation, JSON-safe empty-shape inference and property escaping, and update generated coding-agent instructions for the v2 APIs. The CLI update requires compatible management endpoints and SDK v2; SDK v1 applications must retain the CLI 1.x generator.

‎.github/workflows/package-ci.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ jobs:
3737
- id: build
3838
name: Build the project
3939
run: yarn build
40+
- name: Check generated CLI declarations
41+
run: node packages/cli/test/generated-types.mjs
4042
- name: Build docs
4143
run: yarn docs
4244
- name: Test documentation publication boundaries

‎packages/cli/README.md‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@ Command-line interface for interacting with Reflag services. The CLI allows you
44
flags, authentication, and generate TypeScript types for your Reflag flags. With this tool,
55
you can streamline your flagging workflow directly from your terminal.
66

7+
## SDK v2 generation
8+
9+
CLI v2 generates types for the **Node, React, and Vue v2 SDKs**. If you use SDK v1, stay on CLI 1.x for legacy type generation.
10+
11+
`reflag flags types` reads Boolean flag headers and current multivariate variants in the app's production environment. Generated `Flags` entries are direct value types, not `.config.payload` wrappers. Regenerate old declarations when migrating. Formats are `node`, `react`, and `vue`; you can configure multiple outputs.
12+
13+
Registered non-null defaults are checked against the generated value type, including required and nested fields. Singular return types still widen from the supplied default. Bare/`undefined` reads remain Boolean; explicit `null` requests arbitrary JSON. Generated schemas reflect current authored variants and do not add nested runtime validation; regenerate when values change. Unconfigured multivariate flags and empty shapes retain JSON-capable types rather than silently becoming Boolean or `any`.
14+
715
## Installation
816

917
Install the CLI as a development dependency in your project:
@@ -77,13 +85,13 @@ Here are all the configuration options available in the `reflag.config.json` fil
7785
}
7886
```
7987

80-
| Option | Description | Default |
81-
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
82-
| `$schema` | Autocompletion for the config. `latest` can be replaced with a specific version. | "https://unpkg.com/@reflag/cli@latest/schema.json" |
83-
| `baseUrl` | Base URL for Reflag services. | "https://app.reflag.com" |
84-
| `apiUrl` | API URL for Reflag services (overrides baseUrl for API calls). | "https://app.reflag.com/api" |
85-
| `appId` | Your Reflag application ID. | Required |
86-
| `typesOutput` | Path(s) where TypeScript types will be generated. Can be a string or an array of objects with `path` and `format` properties. Available formats: `react` and `node`. | "gen/flags.ts" with format "react" |
88+
| Option | Description | Default |
89+
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
90+
| `$schema` | Autocompletion for the config. `latest` can be replaced with a specific version. | "https://unpkg.com/@reflag/cli@latest/schema.json" |
91+
| `baseUrl` | Base URL for Reflag services. | "https://app.reflag.com" |
92+
| `apiUrl` | API URL for Reflag services (overrides baseUrl for API calls). | "https://app.reflag.com/api" |
93+
| `appId` | Your Reflag application ID. | Required |
94+
| `typesOutput` | Path(s) where TypeScript types will be generated. Can be a string or an array of objects with `path` and `format` properties. Available formats: `react`, `node`, and `vue`. | "gen/flags.ts" with format "react" |
8795

8896
You can override these settings using command-line options for individual commands.
8997

@@ -117,7 +125,7 @@ Options:
117125
- `--app-id`: App ID to use.
118126
- `--key-format`: Format for flag keys (custom, snake, camel, etc.).
119127
- `--out`: Path to generate TypeScript types.
120-
- `--format`: Format of the generated types (react or node).
128+
- `--format`: Format of the generated types (react, node, or vue).
121129

122130
If you prefer more control over each step, you can use the individual commands (`init`, `flags create`, `flags types`) instead.
123131

@@ -179,7 +187,7 @@ Options:
179187

180188
- `--app-id`: App ID to use.
181189
- `--out`: Path to generate TypeScript types.
182-
- `--format`: Format of the generated types (react or node).
190+
- `--format`: Format of the generated types (react, node, or vue).
183191

184192
### `reflag apps`
185193

@@ -284,6 +292,9 @@ Example CI workflow:
284292
# Build the CLI
285293
yarn build
286294

295+
# Test generated declarations against the built Node, React, and Vue SDKs
296+
yarn test:generated-types
297+
287298
# Run the CLI locally
288299
yarn reflag [command]
289300

‎packages/cli/commands/flags.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ import { Command } from "commander";
66
import ora, { Ora } from "ora";
77

88
import { App, getApp, getOrg } from "../services/bootstrap.js";
9-
import { createFlag, Flag, listFlags } from "../services/flags.js";
9+
import { createFlag, listFlags, listFlagValues } from "../services/flags.js";
1010
import { configStore } from "../stores/config.js";
1111
import {
1212
handleError,
1313
MissingAppIdError,
1414
MissingEnvIdError,
1515
} from "../utils/errors.js";
1616
import {
17+
type FlagForTypes,
1718
genFlagKey,
1819
genTypes,
1920
indentLines,
@@ -27,7 +28,7 @@ import {
2728
typesFormatOption,
2829
typesOutOption,
2930
} from "../utils/options.js";
30-
import { baseUrlSuffix, featureUrl } from "../utils/urls.js";
31+
import { baseUrlSuffix, flagUrl } from "../utils/urls.js";
3132

3233
type CreateFlagOptions = {
3334
key?: string;
@@ -84,7 +85,7 @@ export const createFlagAction = async (
8485
);
8586
if (production) {
8687
console.log(
87-
indentLines(chalk.magenta(featureUrl(baseUrl, production, flag))),
88+
indentLines(chalk.magenta(flagUrl(baseUrl, production, flag))),
8889
);
8990
}
9091
} catch (error) {
@@ -134,11 +135,10 @@ export const listFlagsAction = async () => {
134135
};
135136

136137
export const generateTypesAction = async () => {
137-
const { baseUrl, appId } = configStore.getConfig();
138-
const typesOutput = configStore.getConfig("typesOutput");
138+
const { baseUrl, appId, typesOutput } = configStore.getConfig();
139139

140140
let spinner: Ora | undefined;
141-
let flags: Flag[] = [];
141+
let flags: FlagForTypes[];
142142

143143
if (!appId) {
144144
handleError(new MissingAppIdError(), "Flags Types");
@@ -161,10 +161,7 @@ export const generateTypesAction = async () => {
161161
`Loading flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}...`,
162162
).start();
163163

164-
flags = await listFlags(appId, {
165-
envId: production.id,
166-
includeRemoteConfigs: true,
167-
}).then((res) => res.data);
164+
flags = await listFlagValues(appId, production.id);
168165

169166
spinner.succeed(
170167
`Loaded flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}.`,

‎packages/cli/commands/init.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import { Command } from "commander";
66
import ora, { Ora } from "ora";
77

88
import { App, listApps } from "../services/bootstrap.js";
9-
import { configStore, typeFormats } from "../stores/config.js";
10-
import { DEFAULT_TYPES_OUTPUT } from "../utils/constants.js";
9+
import { configStore } from "../stores/config.js";
10+
import { DEFAULT_TYPES_OUTPUT, TYPE_FORMATS } from "../utils/constants.js";
1111
import { handleError } from "../utils/errors.js";
1212
import { overwriteOption } from "../utils/options.js";
1313

@@ -67,7 +67,7 @@ export const initAction = async (args: InitArgs = {}) => {
6767
// Get types output format
6868
const typesFormat = await select({
6969
message: "What is the output format?",
70-
choices: typeFormats.map((format) => ({
70+
choices: TYPE_FORMATS.map((format) => ({
7171
name: format,
7272
value: format,
7373
})),

‎packages/cli/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
"build": "tsc && shx chmod +x dist/index.js",
2929
"reflag": "yarn build && ./dist/index.js",
3030
"test": "vitest run",
31+
"test:generated-types": "yarn workspace @reflag/flag-evaluation build && yarn workspace @reflag/node-sdk build && yarn workspace @reflag/browser-sdk build && yarn workspace @reflag/react-sdk build && yarn workspace @reflag/vue-sdk build && yarn build && node test/generated-types.mjs",
3132
"test:watch": "vitest",
3233
"test:ci": "yarn test --reporter=default --reporter=junit --outputFile=junit.xml",
3334
"coverage": "vitest run --coverage",

‎packages/cli/schema.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
"type": "object",
2727
"properties": {
2828
"path": { "type": "string" },
29-
"format": { "type": "string", "enum": ["react", "node"] }
29+
"format": { "type": "string", "enum": ["react", "node", "vue"] }
3030
},
3131
"required": ["path"]
3232
}

‎packages/cli/services/flags.ts‎

Lines changed: 90 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,94 +1,112 @@
11
import { z } from "zod";
22

33
import { authRequest } from "../utils/auth.js";
4-
import { booleanish, EnvironmentQuerySchema } from "../utils/schemas.js";
5-
import { PaginatedResponse } from "../utils/types.js";
4+
import type { FlagForTypes } from "../utils/gen.js";
5+
import { EnvironmentQuerySchema } from "../utils/schemas.js";
66

7-
export type Stage = {
8-
id: string;
9-
name: string;
10-
order: number;
11-
};
12-
13-
export type RemoteConfigVariant = {
14-
key?: string;
15-
payload?: any;
16-
};
17-
18-
export type RemoteConfig = {
19-
variants: [
20-
{
21-
variant: RemoteConfigVariant;
22-
},
23-
];
24-
};
25-
26-
export type FlagName = {
27-
id: string;
28-
name: string;
29-
key: string;
30-
};
31-
32-
export type Flag = FlagName & {
33-
description: string | null;
34-
remoteConfigs: RemoteConfig[];
35-
stage: Stage | null;
36-
};
37-
38-
export type FlagsResponse = PaginatedResponse<Flag>;
7+
const FlagSchema = z.object({
8+
id: z.string().min(1),
9+
name: z.string(),
10+
key: z.string().min(1),
11+
flagType: z.enum(["boolean", "multivariate"]),
12+
stage: z.object({ name: z.string() }).optional(),
13+
});
14+
const FlagsResponseSchema = z.object({
15+
data: z.array(FlagSchema),
16+
totalCount: z.number().int().nonnegative(),
17+
});
18+
const MultivariateVersionsSchema = z.object({
19+
flagId: z.string(),
20+
flagType: z.literal("multivariate"),
21+
versions: z.array(
22+
z.object({
23+
environment: z.object({ id: z.string() }),
24+
currentVersion: z.boolean(),
25+
variants: z.record(z.string(), z.json()),
26+
}),
27+
),
28+
});
3929

4030
export const FlagsQuerySchema = EnvironmentQuerySchema.extend({
41-
sortBy: z.string().default("key").describe("Field to sort features by"),
42-
sortOrder: z
43-
.enum(["asc", "desc"])
44-
.default("asc")
45-
.describe("Sort direction (ascending or descending)"),
46-
includeRemoteConfigs: booleanish
47-
.default(false)
48-
.describe("Include remote configuration data"),
31+
sortBy: z
32+
.enum(["key", "name", "stage"])
33+
.default("key")
34+
.describe("Field to sort flags by"),
35+
sortOrder: z.enum(["asc", "desc"]).default("asc").describe("Sort direction"),
4936
}).strict();
50-
5137
export const FlagCreateSchema = z
5238
.object({
53-
name: z
54-
.string()
55-
.min(1, "Flag name is required")
56-
.describe("Name of the flag"),
57-
key: z
58-
.string()
59-
.min(1, "Flag key is required")
60-
.describe("Unique identifier key for the flag"),
61-
description: z
62-
.string()
63-
.optional()
64-
.describe("Optional description of the flag"),
39+
name: z.string().min(1, "Flag name is required"),
40+
key: z.string().min(1, "Flag key is required"),
41+
description: z.string().optional(),
6542
})
6643
.strict();
44+
const flagsPath = (appId: string) => `/apps/${encodeURIComponent(appId)}/flags`;
6745

68-
export type FlagsQuery = z.input<typeof FlagsQuerySchema>;
69-
export type FlagCreate = z.input<typeof FlagCreateSchema>;
70-
71-
export async function listFlags(appId: string, query: FlagsQuery) {
72-
return authRequest<FlagsResponse>(`/apps/${appId}/features`, {
46+
export async function listFlags(
47+
appId: string,
48+
query: z.input<typeof FlagsQuerySchema>,
49+
) {
50+
const response = await authRequest(flagsPath(appId), {
7351
params: FlagsQuerySchema.parse(query),
7452
});
53+
return FlagsResponseSchema.parse(response);
7554
}
7655

77-
type CreateFlagResponse = {
78-
feature: FlagName & {
79-
description: string | null;
80-
};
81-
};
56+
/** Generate schemas from current values in the selected environment, never legacy remote-config wrappers. */
57+
export async function listFlagValues(
58+
appId: string,
59+
envId: string,
60+
): Promise<FlagForTypes[]> {
61+
const { data, totalCount } = await listFlags(appId, { envId });
62+
if (data.length !== totalCount) {
63+
throw new Error("Cannot generate types from an incomplete flag list");
64+
}
65+
const flags: FlagForTypes[] = [];
66+
for (const { id, key, flagType } of data) {
67+
if (flagType === "boolean") {
68+
flags.push({ key, flagType });
69+
continue;
70+
}
71+
const { flagId, versions } = MultivariateVersionsSchema.parse(
72+
await authRequest(
73+
`${flagsPath(appId)}/${encodeURIComponent(id)}/targeting`,
74+
{
75+
params: { envId },
76+
},
77+
),
78+
);
79+
const [version] = versions;
80+
if (
81+
flagId !== id ||
82+
versions.length > 1 ||
83+
(version && (version.environment.id !== envId || !version.currentVersion))
84+
) {
85+
throw new Error(
86+
`Unexpected current-version response for flag ${JSON.stringify(key)}`,
87+
);
88+
}
89+
flags.push({
90+
key,
91+
flagType,
92+
values: Object.values(version?.variants ?? {}),
93+
});
94+
}
95+
return flags;
96+
}
8297

83-
export async function createFlag(appId: string, featureData: FlagCreate) {
84-
return authRequest<CreateFlagResponse>(`/apps/${appId}/features`, {
98+
export async function createFlag(
99+
appId: string,
100+
flag: z.input<typeof FlagCreateSchema>,
101+
) {
102+
const response = await authRequest(flagsPath(appId), {
85103
method: "POST",
86-
headers: {
87-
"Content-Type": "application/json",
88-
},
104+
headers: { "Content-Type": "application/json" },
89105
body: JSON.stringify({
90106
source: "event",
91-
...FlagCreateSchema.parse(featureData),
107+
flagType: "boolean",
108+
...FlagCreateSchema.parse(flag),
92109
}),
93-
}).then(({ feature }) => feature);
110+
});
111+
return z.object({ flag: FlagSchema }).parse(response).flag;
94112
}

0 commit comments

Comments
 (0)