Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cli-multi-org.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@reflag/cli": patch
---

Fix app discovery for users who belong to multiple organizations. `reflag apps list` shows each app's organization, `reflag init` lets you choose an organization, and existing configs resolve their `appId` without requiring an `orgId`. Use `orgId` or `--org-id` to restrict the CLI to one organization. API keys remain scoped to their app.
43 changes: 22 additions & 21 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ Here are all the configuration options available in the `reflag.config.json` fil
"$schema": "https://unpkg.com/@reflag/cli@latest/schema.json",
"baseUrl": "https://app.reflag.com",
"apiUrl": "https://app.reflag.com/api",
"appId": "ap123456789",
"appId": "ap123456789012",
"orgId": "or123456789012",
"typesOutput": [
{
"path": "gen/flags.d.ts",
Expand All @@ -91,39 +92,35 @@ Here are all the configuration options available in the `reflag.config.json` fil
| `baseUrl` | Base URL for Reflag services. | "https://app.reflag.com" |
| `apiUrl` | API URL for Reflag services (overrides baseUrl for API calls). | "https://app.reflag.com/api" |
| `appId` | Your Reflag application ID. | Required |
| `orgId` | Restrict the CLI to one organization. Find the ID with `reflag apps list`. | Optional |
| `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" |

You can override these settings using command-line options for individual commands.
You can override these settings using command-line options. With a personal login and no `orgId`, the CLI finds your configured `appId` across all organizations you can access. With `orgId` set, the CLI rejects apps outside that organization instead of switching to another one. This setting does not scope remote MCP connections.

## Commands

### `reflag init`

Initialize a new Reflag configuration in your project. This creates a `reflag.config.json` file with your settings and prompts for any required information not provided via options.
Initialize a new `reflag.config.json`. If you can access multiple organizations, the CLI asks you to choose an organization and then an app. Pass `--org-id` to pin an organization in the new config, or `--appId` to choose the app directly.

```bash
npx reflag init [--overwrite]
npx reflag init [--overwrite] [--org-id <org-id>] [--appId <app-id>]
```

Options:

- `--overwrite`: Overwrite existing configuration file if one exists.
- `--app-id <id>`: Set the application ID.
- `--key-format <format>`: Set the key format for flags.
Use `--overwrite` to replace an existing configuration.

### `reflag new [flagName]`

All-in-one command to get started quickly. This command combines `init`, flag creation, and type generation in a single step. Use this for the fastest way to get up and running with Reflag.

```bash
npx reflag new "My Flag" [--app-id ap123456789] [--key my-flag] [--key-format custom] [--out gen/flags.ts] [--format react]
npx reflag new "My Flag" [--appId <app-id>] [--key my-flag] [--out gen/flags.ts] [--format react]
```

Options:

- `--key`: Specific key for the flag.
- `--app-id`: App ID to use.
- `--key-format`: Format for flag keys (custom, snake, camel, etc.).
- `--appId`: App ID to use.
- `--out`: Path to generate TypeScript types.
- `--format`: Format of the generated types (react, node, or vue).

Expand Down Expand Up @@ -154,44 +151,47 @@ Manage your Reflag flags with these subcommands:
Create a new flag in your Reflag app. The command guides you through the flag creation process with interactive prompts if options are not provided.

```bash
npx reflag flags create "My Flag" [--app-id ap123456789] [--key my-flag] [--key-format custom]
npx reflag flags create "My Flag" [--appId <app-id>] [--key my-flag]
```

Options:

- `--key`: Specific key for the flag.
- `--app-id`: App ID to use.
- `--key-format`: Format for flag keys.
- `--appId`: App ID to use. The app's organization determines the key format.

#### `reflag flags list`

List all flags for the current app. This helps you visualize what flags are available and their current configurations.

```bash
npx reflag flags list [--app-id ap123456789]
npx reflag flags list [--appId <app-id>]
```

Options:

- `--app-id`: App ID to use.
- `--appId`: App ID to use.

#### `reflag flags types`

Generate TypeScript types for your flags. This ensures type safety when using Reflag flags in your TypeScript/JavaScript applications.

```bash
npx reflag flags types [--app-id ap123456789] [--out gen/flags.ts] [--format react]
npx reflag flags types [--appId <app-id>] [--out gen/flags.ts] [--format react]
```

Options:

- `--app-id`: App ID to use.
- `--appId`: App ID to use.
- `--out`: Path to generate TypeScript types.
- `--format`: Format of the generated types (react, node, or vue).

### `reflag apps`
### `reflag apps list`

List available apps with their organization names and IDs. Without an organization filter, a personal login lists apps across all your organizations. An API key still lists only its own app.

Commands for managing Reflag apps.
```bash
npx reflag apps list [--org-id <org-id>]
```

## Global Options

Expand All @@ -201,6 +201,7 @@ These options can be used with any command:
- `--base-url <url>`: Set the base URL for Reflag API.
- `--api-url <url>`: Set the API URL directly (overrides base URL).
- `--api-key <key>`: Reflag API key for non-interactive authentication.
- `--org-id <org-id>`: Restrict app discovery and commands to one organization. Overrides `orgId` in `reflag.config.json`.
- `--help`: Display help information for a command.

## AI-Assisted Development
Expand Down
15 changes: 12 additions & 3 deletions packages/cli/commands/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import chalk from "chalk";
import { Command } from "commander";
import ora from "ora";

import { listApps } from "../services/bootstrap.js";
import { listApps } from "../services/apps.js";
import { configStore } from "../stores/config.js";
import { handleError } from "../utils/errors.js";

Expand All @@ -11,9 +11,18 @@ export const listAppsAction = async () => {
const spinner = ora(`Loading apps from ${chalk.cyan(baseUrl)}...`).start();

try {
const apps = listApps();
const apps = await listApps();
if (!apps.length) throw new Error("No apps found.");
spinner.succeed(`Loaded apps from ${chalk.cyan(baseUrl)}.`);
console.table(apps.map(({ name, id, demo }) => ({ name, id, demo })));
console.table(
apps.map(({ name, id, org, demo }) => ({
name,
id,
organization: org.name,
orgId: org.id,
demo,
})),
);
} catch (error) {
spinner.fail("Failed to list apps.");
handleError(error, "Apps List");
Expand Down
13 changes: 6 additions & 7 deletions packages/cli/commands/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import chalk from "chalk";
import { Command } from "commander";
import ora, { Ora } from "ora";

import { App, getApp, getOrg } from "../services/bootstrap.js";
import { App, getApp } from "../services/apps.js";
import { createFlag, listFlags, listFlagValues } from "../services/flags.js";
import { configStore } from "../stores/config.js";
import {
Expand Down Expand Up @@ -47,17 +47,16 @@ export const createFlagAction = async (

let app: App;
try {
app = getApp(appId);
app = await getApp(appId);
} catch (error) {
handleError(error, "Flags Create");
}

const production = app.environments.find((e) => e.isProduction);

try {
const org = getOrg();
console.log(
`Creating flag for app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}.`,
`Creating flag for app ${chalk.cyan(app.name)} in ${chalk.cyan(app.org.name)}${baseUrlSuffix(baseUrl)}.`,
);

if (!name) {
Expand All @@ -68,7 +67,7 @@ export const createFlagAction = async (
}

if (!key) {
const keyFormat = org.featureKeyFormat;
const keyFormat = app.org.featureKeyFormat;
const keyValidator = KeyFormatPatterns[keyFormat];
key = await input({
message: "New flag key:",
Expand Down Expand Up @@ -103,7 +102,7 @@ export const listFlagsAction = async () => {
}

try {
const app = getApp(appId);
const app = await getApp(appId);
const production = app.environments.find((e) => e.isProduction);
if (!production) {
handleError(new MissingEnvIdError(), "Flags Types");
Expand Down Expand Up @@ -146,7 +145,7 @@ export const generateTypesAction = async () => {

let app: App;
try {
app = getApp(appId);
app = await getApp(appId);
} catch (error) {
handleError(error, "Flags Types");
}
Expand Down
66 changes: 39 additions & 27 deletions packages/cli/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,65 @@ import chalk from "chalk";
import { Command } from "commander";
import ora, { Ora } from "ora";

import { App, listApps } from "../services/bootstrap.js";
import { getApp, listOrganizations } from "../services/apps.js";
import { configStore } from "../stores/config.js";
import { DEFAULT_TYPES_OUTPUT, TYPE_FORMATS } from "../utils/constants.js";
import { handleError } from "../utils/errors.js";
import { overwriteOption } from "../utils/options.js";
import { appIdOption, overwriteOption } from "../utils/options.js";

type InitArgs = {
appId?: string;
overwrite?: boolean;
};

export const initAction = async (args: InitArgs = {}) => {
export const initAction = async ({
appId: requestedAppId,
overwrite,
}: InitArgs = {}) => {
let spinner: Ora | undefined;
let apps: App[] = [];

try {
// Check if config already exists
const configPath = configStore.getConfigPath();
if (configPath && !args.overwrite) {
if (configPath && !overwrite) {
throw new Error(
"Reflag is already initialized. Use --overwrite to overwrite.",
);
}

console.log("\nWelcome to ◪ Reflag!\n");
const baseUrl = configStore.getConfig("baseUrl");
spinner = ora("Loading organizations and apps...").start();
let appId = requestedAppId;
if (appId !== undefined) {
await getApp(appId);
spinner.stop();
} else {
const orgs = await listOrganizations();
spinner.stop();
if (!orgs.length) throw new Error("No accessible organizations found.");

// Load apps
spinner = ora(`Loading apps from ${chalk.cyan(baseUrl)}...`).start();
apps = listApps();
spinner.succeed(`Loaded apps from ${chalk.cyan(baseUrl)}.`);
} catch (error) {
spinner?.fail("Loading apps failed.");
handleError(error, "Initialization");
}
const org =
orgs.length === 1
? orgs[0]
: await select({
message: "Select an organization",
choices: orgs.map((candidate) => ({
name: `${candidate.name} (${candidate.id})`,
value: candidate,
})),
});

try {
let appId: string | undefined;
const nonDemoApp = apps.find((app) => !app.demo);
if (!org.apps.length) {
throw new Error(
`No apps found in '${org.name}'. Choose another organization or create an app.`,
);
}

if (apps.length === 0) {
throw new Error("You don't have any apps yet. Please create one.");
} else {
const longestName = Math.max(...apps.map((app) => app.name.length));
appId = await select({
message: "Select an app",
default: nonDemoApp?.id,
choices: apps.map((app) => ({
name: `${app.name.padEnd(longestName, " ")}${app.demo ? " [Demo]" : ""}`,
message: `Select an app in ${org.name}`,
default: org.apps.find((app) => !app.demo)?.id,
choices: org.apps.map((app) => ({
name: `${app.name}${app.demo ? " [Demo]" : ""} (${app.id})`,
value: app.id,
})),
});
Expand Down Expand Up @@ -82,13 +93,13 @@ export const initAction = async (args: InitArgs = {}) => {

// Create config file
spinner = ora("Creating configuration...").start();
await configStore.saveConfigFile(args.overwrite);
await configStore.saveConfigFile(overwrite);

spinner.succeed(
`Configuration created at ${chalk.cyan(relative(process.cwd(), configStore.getConfigPath()!))}.`,
);
} catch (error) {
spinner?.fail("Configuration creation failed.");
if (spinner?.isSpinning) spinner.fail();
handleError(error, "Initialization");
}
};
Expand All @@ -98,5 +109,6 @@ export function registerInitCommand(cli: Command) {
.command("init")
.description("Initialize a new Reflag configuration.")
.addOption(overwriteOption)
.addOption(appIdOption)
.action(initAction);
}
30 changes: 13 additions & 17 deletions packages/cli/commands/new.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Command } from "commander";
import { findUp } from "find-up";

import { configStore } from "../stores/config.js";
import { CONFIG_FILE_NAME } from "../utils/constants.js";
import type { TypeFormat } from "../utils/constants.js";
import {
appIdOption,
flagKeyOption,
Expand All @@ -15,17 +14,23 @@ import { initAction } from "./init.js";

type NewArgs = {
appId?: string;
out: string;
out?: string;
format?: TypeFormat;
key?: string;
};

export const newAction = async (name: string | undefined, { key }: NewArgs) => {
if (!(await findUp(CONFIG_FILE_NAME))) {
await initAction();
export const newAction = async (
name: string | undefined,
{ appId, out, format, key }: NewArgs,
) => {
if (!configStore.getConfigPath()) {
await initAction({ appId });
}
await createFlagAction(name, {
key,
configStore.setConfig({
appId,
typesOutput: out ? [{ path: out, format: format || "react" }] : undefined,
});
await createFlagAction(name, { key });
await generateTypesAction();
};

Expand All @@ -41,13 +46,4 @@ export function registerNewCommand(cli: Command) {
.addOption(flagKeyOption)
.addArgument(flagNameArgument)
.action(newAction);

// Update the config with the cli override values
cli.hook("preAction", (command) => {
const { appId, out, format } = command.opts();
configStore.setConfig({
appId,
typesOutput: out ? [{ path: out, format: format || "react" }] : undefined,
});
});
}
Loading
Loading