diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index aef1d5bd..ac5ab1d5 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -4,11 +4,16 @@ on: push: branches: - main + # Repository dispatch always uses the default branch. It cannot select the + # workflow or release source from a maintenance branch. + repository_dispatch: + types: [release-cli-v1] concurrency: ${{ github.workflow }}-${{ github.ref }} jobs: release: + if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest permissions: contents: write @@ -81,3 +86,95 @@ jobs: git commit -m "Update released SDK documentation" git push fi + + build-cli-v1: + if: github.event_name == 'repository_dispatch' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Require the reviewed main commit + env: + REVIEWED_SHA: ${{ github.event.client_payload.sha }} + run: | + if [[ "$REVIEWED_SHA" != "$GITHUB_SHA" ]]; then + echo 'The reviewed commit must match the current main commit used by this run.' >&2 + exit 1 + fi + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + - run: corepack enable + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + package-manager-cache: false + - name: Prepare the reviewed CLI v1 source with its original lockfile + run: | + base=1adfced0efaf36f5456707d85907ec8fa591a1ec + source="$RUNNER_TEMP/cli-v1-source" + git merge-base --is-ancestor "$base" HEAD + git worktree add --detach "$source" "$base" + git -C "$source" rm -rq -- packages/cli + cp -R "$GITHUB_WORKSPACE/releases/cli-v1" "$source/packages/cli" + - name: Build, test, and pack only the CLI + working-directory: ${{ runner.temp }}/cli-v1-source + run: | + yarn install --immutable + yarn workspace @reflag/cli test + yarn workspace @reflag/cli build + yarn workspace @reflag/cli pack --out "$RUNNER_TEMP/reflag-cli.tgz" + - name: Check the packaged CLI version and npm latest tag + env: + CLI_VERSION: ${{ github.event.client_payload.version }} + run: | + set -o pipefail + tar -xOf "$RUNNER_TEMP/reflag-cli.tgz" package/package.json | node scripts/cli-v1-release.mjs + - uses: actions/upload-artifact@v4 + if: ${{ toJSON(github.event.client_payload.publish) == 'true' }} + with: + name: reflag-cli-v1 + path: ${{ runner.temp }}/reflag-cli.tgz + if-no-files-found: error + overwrite: true + + publish-cli-v1: + needs: build-cli-v1 + if: ${{ toJSON(github.event.client_payload.publish) == 'true' }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - name: Require a repository administrator to publish + env: + GH_TOKEN: ${{ github.token }} + run: | + # A rerun can be requested by someone other than the dispatch actor. + for actor in "$GITHUB_ACTOR" "$GITHUB_TRIGGERING_ACTOR"; do + permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$actor/permission" --jq .permission) + if [[ "$permission" != admin ]]; then + echo 'Publishing CLI v1 requires a repository administrator.' >&2 + exit 1 + fi + done + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + registry-url: https://registry.npmjs.org + package-manager-cache: false + - uses: actions/download-artifact@v4 + with: + name: reflag-cli-v1 + path: ${{ runner.temp }} + - name: Recheck npm latest and publish CLI v1 + env: + CLI_VERSION: ${{ github.event.client_payload.version }} + run: | + set -o pipefail + tar -xOf "$RUNNER_TEMP/reflag-cli.tgz" package/package.json | node scripts/cli-v1-release.mjs + npm publish "$RUNNER_TEMP/reflag-cli.tgz" --access public --tag latest --ignore-scripts diff --git a/package.json b/package.json index 3039f50b..255cbbf3 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "dev": "lerna run dev --parallel", "build": "lerna run build --stream", "test:ci": "lerna run test:ci --stream", - "test:release": "node --test scripts/release-channel.test.mjs scripts/publish-manifests.test.mjs", + "test:release": "node --test scripts/release-channel.test.mjs scripts/publish-manifests.test.mjs scripts/cli-v1-release.test.mjs", "check:publish-manifests": "node scripts/publish-manifests.mjs", "test": "lerna run test --stream", "format": "yarn fmt:fix && yarn lint:fix", diff --git a/releases/cli-v1/.prettierignore b/releases/cli-v1/.prettierignore new file mode 100644 index 00000000..3dc99d75 --- /dev/null +++ b/releases/cli-v1/.prettierignore @@ -0,0 +1,3 @@ +dist +eslint-report.json +gen diff --git a/releases/cli-v1/CHANGELOG.md b/releases/cli-v1/CHANGELOG.md new file mode 100644 index 00000000..cbf1f9a1 --- /dev/null +++ b/releases/cli-v1/CHANGELOG.md @@ -0,0 +1,8 @@ +# @reflag/cli + +## 1.0.5 + +### Patch Changes + +- ee30ad5: 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. +- 1adfced: Update Express and Zod to patched versions. Preserve CLI schema parsing behavior when migrating to Zod 4. diff --git a/releases/cli-v1/README.md b/releases/cli-v1/README.md new file mode 100644 index 00000000..9f565f68 --- /dev/null +++ b/releases/cli-v1/README.md @@ -0,0 +1,303 @@ +# Reflag CLI + +Command-line interface for interacting with Reflag services. The CLI allows you to manage apps, +flags, authentication, and generate TypeScript types for your Reflag flags. With this tool, +you can streamline your flagging workflow directly from your terminal. + +## Installation + +Install the CLI as a development dependency in your project: + +```bash +# npm +npm install --save-dev @reflag/cli + +# yarn +yarn add --dev @reflag/cli +``` + +Run the `new` command from your project's root directory to initialize the CLI, create a flag, and generate TypeScript types in one step: + +```bash +# npm +npx reflag new + +# yarn +yarn reflag new +``` + +## Migrating from Bucket SDK + +If you're migrating from the Bucket CLI, here are the key changes to be aware of: + +- **Command name**: Changed from `bucket` to `reflag` +- **Type definitions file**: Renamed from `features.d.ts` to `flags.d.ts` (manually remove the old file if it was committed) +- **Authentication file**: Changed from `.bucket-auth` to `.reflag-auth` (rename or remove the old file) +- **Configuration file**: Changed from `bucket.config.json` to `reflag.config.json` (rename or remove the old file) +- **Command**: `features` command is now `flags` +- **Environment variable**: Use `REFLAG_API_KEY` instead of `BUCKET_API_KEY` + +**Important**: Update your scripts, build steps, and `.gitignore` patterns to reflect these changes. + +### Individual Commands + +For more control, you can run each command individually: + +```bash +# Initialize Reflag in your project (if not already setup) +npx reflag init + +# Create a new flag +npx reflag flags create "My Flag" + +# Generate TypeScript types for your flags +npx reflag flags types +``` + +## Configuration + +The CLI creates a `reflag.config.json` file in your project directory when you run `reflag init`. This file contains all the necessary settings for your Reflag integration. + +### Configuration File Structure + +Here are all the configuration options available in the `reflag.config.json` file: + +```json +{ + "$schema": "https://unpkg.com/@reflag/cli@latest/schema.json", + "baseUrl": "https://app.reflag.com", + "apiUrl": "https://app.reflag.com/api", + "appId": "ap123456789012", + "orgId": "or123456789012", + "typesOutput": [ + { + "path": "gen/flags.d.ts", + "format": "react" + } + ] +} +``` + +| Option | Description | Default | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | +| `$schema` | Autocompletion for the config. `latest` can be replaced with a specific version. | "https://unpkg.com/@reflag/cli@latest/schema.json" | +| `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` and `node`. | "gen/flags.ts" with format "react" | + +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.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] [--org-id ] [--appId ] +``` + +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" [--appId ] [--key my-flag] [--out gen/flags.ts] [--format react] +``` + +Options: + +- `--key`: Specific key for the flag. +- `--appId`: App ID to use. +- `--out`: Path to generate TypeScript types. +- `--format`: Format of the generated types (react or node). + +If you prefer more control over each step, you can use the individual commands (`init`, `flags create`, `flags types`) instead. + +### `reflag login` + +Authenticate with your Reflag account. This stores your credentials securely for subsequent operations. + +```bash +npx reflag login +``` + +### `reflag logout` + +Sign out from your Reflag account and remove stored credentials. + +```bash +npx reflag logout +``` + +### `reflag flags` + +Manage your Reflag flags with these subcommands: + +#### `reflag flags create [flagName]` + +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" [--appId ] [--key my-flag] +``` + +Options: + +- `--key`: Specific key for the flag. +- `--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 [--appId ] +``` + +Options: + +- `--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 [--appId ] [--out gen/flags.ts] [--format react] +``` + +Options: + +- `--appId`: App ID to use. +- `--out`: Path to generate TypeScript types. +- `--format`: Format of the generated types (react or node). + +### `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. + +```bash +npx reflag apps list [--org-id ] +``` + +## Global Options + +These options can be used with any command: + +- `--debug`: Enable debug mode for verbose output. +- `--base-url `: Set the base URL for Reflag API. +- `--api-url `: Set the API URL directly (overrides base URL). +- `--api-key `: Reflag API key for non-interactive authentication. +- `--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 + +Reflag provides powerful AI-assisted development capabilities through rules and Model Context Protocol (MCP). These features help your AI development tools better understand your flags and provide more accurate assistance. + +### Reflag Rules (Recommended) + +The `rules` command helps you set up AI-specific rules for your project. These rules enable AI tools to better understand how to work with Reflag flags and how they should be used in your codebase. + +```bash +npx reflag rules [--format ] [--yes] +``` + +Options: + +- `--format`: Format to add rules in: + - `cursor`: Adds rules to `.cursor/rules/reflag.mdc` for Cursor IDE integration. + - `copilot`: Adds rules to `.github/copilot-instructions.md` for GitHub Copilot integration. +- `--yes`: Skip confirmation prompts and overwrite existing files without asking. + +This command adds rules to your project that provide AI tools with context about how to set up and use Reflag flags. For the copilot format, the rules are added to a dedicated section in the file, allowing you to maintain other copilot instructions alongside Reflag's rules. + +## Model Context Protocol + +The Model Context Protocol (MCP) is an open protocol that provides a standardized way to connect AI models to different data sources and tools. In the context of Reflag, MCP enables your code editor to understand your flags, their states, and their relationships within your codebase. This creates a seamless bridge between your flag management workflow and AI-powered development tools. The MCP server is hosted by Reflag, making it easy to get started. + +_\*\*Note: The Reflag `mcp` CLI command was previously used for a \_local_ server. However, in recent versions of the Reflag CLI, the `mcp` command has been repurposed to help you connect to the new remote MCP server.\*\*\_ + +### Setting up MCP + +The `mcp` command helps you configure your editor or AI client to connect with Reflag's remote MCP server. This allows your AI tools to understand your flags and provide more contextual assistance. + +```bash +npx reflag mcp [--editor ] [--scope ] +``` + +Options: + +- `--editor`: The editor/client to configure: + - `cursor`: [Cursor IDE](https://www.cursor.com/) + - `vscode`: [Visual Studio Code](https://code.visualstudio.com/) + - `claude`: [Claude Desktop](https://claude.ai/download) + - `windsurf`: [Windsurf](https://windsurf.com/editor) +- `--scope`: Whether to configure settings globally or locally for the project. + +The command will guide you through: + +1. Selecting which editor/client to configure. +2. Choosing which Reflag app to connect to. +3. Deciding between global or project-local configuration. +4. Setting up the appropriate configuration file for your chosen editor . + +_**Note: The setup uses [mcp-remote](https://github.com/geelen/mcp-remote) as a compatibility layer allowing the remote hosted Reflag MCP server to work with all editors/clients that support MCP STDIO servers. If your editor/client supports HTTP Streaming with OAuth you can connect to the Reflag MCP server directly.**_ + +## Using in CI/CD Pipelines + +The Reflag CLI is designed to work seamlessly in CI/CD pipelines. For automated environments where interactive login is not possible, use the `--api-key` option or specify the API key in the `REFLAG_API_KEY` environment variable. + +```bash +# Generate types in CI/CD +npx reflag apps list --api-key $REFLAG_API_KEY +``` + +**Important restrictions:** + +- When using `--api-key`, the `login` and `logout` commands are disabled +- API keys bypass all interactive authentication flows +- API keys are bound to one app only. Commands such as `apps list` will only return the bound app +- Store API keys securely using your CI/CD platform's secret management + +Example CI workflow: + +```yaml +# GitHub Actions example +- name: Generate types + run: npx reflag flags types --api-key ${{ secrets.REFLAG_API_KEY }} + +# GitHub Actions example (using environment): +- name: Generate types (environment) + run: npx reflag flags types + env: + REFLAG_API_KEY: ${{ secrets.REFLAG_CI_API_KEY }} +``` + +## Development + +```bash +# Build the CLI +yarn build + +# Run the CLI locally +yarn reflag [command] + +# Lint and format code +yarn lint +yarn format +``` + +## Requirements + +- Node.js >=18.0.0 + +## License + +> MIT License +> Copyright (c) 2025 Bucket ApS diff --git a/releases/cli-v1/commands/apps.ts b/releases/cli-v1/commands/apps.ts new file mode 100644 index 00000000..92379937 --- /dev/null +++ b/releases/cli-v1/commands/apps.ts @@ -0,0 +1,42 @@ +import chalk from "chalk"; +import { Command } from "commander"; +import ora from "ora"; + +import { listApps } from "../services/apps.js"; +import { configStore } from "../stores/config.js"; +import { handleError } from "../utils/errors.js"; + +export const listAppsAction = async () => { + const baseUrl = configStore.getConfig("baseUrl"); + const spinner = ora(`Loading apps from ${chalk.cyan(baseUrl)}...`).start(); + + try { + 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, org, demo }) => ({ + name, + id, + organization: org.name, + orgId: org.id, + demo, + })), + ); + } catch (error) { + spinner.fail("Failed to list apps."); + handleError(error, "Apps List"); + } +}; + +export function registerAppCommands(cli: Command) { + const appsCommand = new Command("apps").description("Manage apps."); + + appsCommand + .command("list") + .alias("ls") + .description("List all available apps.") + .action(listAppsAction); + + cli.addCommand(appsCommand); +} diff --git a/releases/cli-v1/commands/auth.ts b/releases/cli-v1/commands/auth.ts new file mode 100644 index 00000000..2900b30b --- /dev/null +++ b/releases/cli-v1/commands/auth.ts @@ -0,0 +1,70 @@ +import chalk from "chalk"; +import { Command } from "commander"; +import ora from "ora"; + +import { authStore } from "../stores/auth.js"; +import { configStore } from "../stores/config.js"; +import { waitForAccessToken } from "../utils/auth.js"; +import { handleError } from "../utils/errors.js"; + +export const loginAction = async () => { + const { baseUrl, apiUrl } = configStore.getConfig(); + const { token, isApiKey } = authStore.getToken(baseUrl); + + if (isApiKey) { + handleError( + "Login is not allowed when an API token was supplied.", + "Login", + ); + } + + if (token) { + console.log("Already logged in, nothing to do."); + return; + } + + try { + const { accessToken } = await waitForAccessToken(baseUrl, apiUrl); + await authStore.setToken(baseUrl, accessToken); + + console.log(`Logged in to ${chalk.cyan(baseUrl)} successfully!`); + } catch (error) { + console.error("Login failed."); + handleError(error, "Login"); + } +}; + +export const logoutAction = async () => { + const baseUrl = configStore.getConfig("baseUrl"); + + const { token, isApiKey } = authStore.getToken(baseUrl); + + if (isApiKey) { + handleError( + "Logout is not allowed when an API token was supplied.", + "Logout", + ); + } + + if (!token) { + console.log("Not logged in, nothing to do."); + return; + } + + const spinner = ora("Logging out...").start(); + + try { + await authStore.setToken(baseUrl, null); + + spinner.succeed("Logged out successfully!"); + } catch (error) { + spinner.fail("Logout failed."); + handleError(error, "Logout"); + } +}; + +export function registerAuthCommands(cli: Command) { + cli.command("login").description("Login to Reflag.").action(loginAction); + + cli.command("logout").description("Logout from Reflag.").action(logoutAction); +} diff --git a/releases/cli-v1/commands/flags.ts b/releases/cli-v1/commands/flags.ts new file mode 100644 index 00000000..2937f7dc --- /dev/null +++ b/releases/cli-v1/commands/flags.ts @@ -0,0 +1,219 @@ +import { relative } from "node:path"; + +import { input } from "@inquirer/prompts"; +import chalk from "chalk"; +import { Command } from "commander"; +import ora, { Ora } from "ora"; + +import { getApp } from "../services/apps.js"; +import { createFlag, Flag, listFlags } from "../services/flags.js"; +import { configStore } from "../stores/config.js"; +import { + handleError, + MissingAppIdError, + MissingEnvIdError, +} from "../utils/errors.js"; +import { + genFlagKey, + genTypes, + indentLines, + KeyFormatPatterns, + writeTypesToFile, +} from "../utils/gen.js"; +import { + appIdOption, + flagKeyOption, + flagNameArgument, + typesFormatOption, + typesOutOption, +} from "../utils/options.js"; +import { baseUrlSuffix, featureUrl } from "../utils/urls.js"; + +type CreateFlagOptions = { + key?: string; +}; + +export const createFlagAction = async ( + name: string | undefined, + { key }: CreateFlagOptions, +) => { + const { baseUrl, appId } = configStore.getConfig(); + let spinner: Ora | undefined; + + if (!appId) { + handleError(new MissingAppIdError(), "Flags Create"); + } + + try { + const app = await getApp(appId); + const production = app.environments.find((e) => e.isProduction); + + console.log( + `Creating flag for app ${chalk.cyan(app.name)} in ${chalk.cyan(app.org.name)}${baseUrlSuffix(baseUrl)}.`, + ); + + if (!name) { + name = await input({ + message: "New flag name:", + validate: (text) => text.length > 0 || "Name is required.", + }); + } + + if (!key) { + const keyFormat = app.org.featureKeyFormat; + const keyValidator = KeyFormatPatterns[keyFormat]; + key = await input({ + message: "New flag key:", + default: genFlagKey(name, keyFormat), + validate: (str) => keyValidator.regex.test(str) || keyValidator.message, + }); + } + + spinner = ora(`Creating flag...`).start(); + const flag = await createFlag(appId, { name, key }); + + spinner.succeed( + `Created flag ${chalk.cyan(flag.name)} with key ${chalk.cyan(flag.key)}:`, + ); + if (production) { + console.log( + indentLines(chalk.magenta(featureUrl(baseUrl, production, flag))), + ); + } + } catch (error) { + spinner?.fail("Flag creation failed."); + handleError(error, "Flags Create"); + } +}; + +export const listFlagsAction = async () => { + const { baseUrl, appId } = configStore.getConfig(); + let spinner: Ora | undefined; + + if (!appId) { + handleError(new MissingAppIdError(), "Flags Create"); + } + + try { + const app = await getApp(appId); + const production = app.environments.find((e) => e.isProduction); + if (!production) { + handleError(new MissingEnvIdError(), "Flags Types"); + } + + spinner = ora( + `Loading flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}...`, + ).start(); + + const flagsResponse = await listFlags(appId, { + envId: production.id, + }); + + spinner.succeed( + `Loaded flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}.`, + ); + + console.table( + flagsResponse.data.map(({ key, name, stage }) => ({ + name, + key, + stage: stage?.name, + })), + ); + } catch (error) { + spinner?.fail("Loading flags failed."); + handleError(error, "Flags List"); + } +}; + +export const generateTypesAction = async () => { + const { baseUrl, appId } = configStore.getConfig(); + const typesOutput = configStore.getConfig("typesOutput"); + + let spinner: Ora | undefined; + let flags: Flag[] = []; + + if (!appId) { + handleError(new MissingAppIdError(), "Flags Types"); + } + + try { + const app = await getApp(appId); + const production = app.environments.find((e) => e.isProduction); + if (!production) { + throw new MissingEnvIdError(); + } + + spinner = ora( + `Loading flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}...`, + ).start(); + + flags = await listFlags(appId, { + envId: production.id, + includeRemoteConfigs: true, + }).then((res) => res.data); + + spinner.succeed( + `Loaded flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}.`, + ); + } catch (error) { + spinner?.fail("Loading flags failed."); + handleError(error, "Flags Types"); + } + + try { + spinner = ora(`Generating flag types...`).start(); + const projectPath = configStore.getProjectPath(); + + // Generate types for each output configuration + for (const output of typesOutput) { + const types = genTypes(flags, output.format); + + const outPath = await writeTypesToFile(types, output.path, projectPath); + spinner.succeed( + `Generated ${output.format} types in ${chalk.cyan(relative(projectPath, outPath))}.`, + ); + } + } catch (error) { + spinner?.fail("Type generation failed."); + handleError(error, "Flags Types"); + } +}; + +export function registerFlagCommands(cli: Command) { + const flagsCommand = new Command("flags").description("Manage flags."); + + flagsCommand + .command("create") + .description("Create a new flag.") + .addOption(appIdOption) + .addOption(flagKeyOption) + .addArgument(flagNameArgument) + .action(createFlagAction); + + flagsCommand + .command("list") + .alias("ls") + .description("List all flags.") + .addOption(appIdOption) + .action(listFlagsAction); + + flagsCommand + .command("types") + .description("Generate flag types.") + .addOption(appIdOption) + .addOption(typesOutOption) + .addOption(typesFormatOption) + .action(generateTypesAction); + + // Update the config with the cli override values + flagsCommand.hook("preAction", (_, command) => { + const { appId, out, format } = command.opts(); + configStore.setConfig({ + appId, + typesOutput: out ? [{ path: out, format: format || "react" }] : undefined, + }); + }); + + cli.addCommand(flagsCommand); +} diff --git a/releases/cli-v1/commands/init.ts b/releases/cli-v1/commands/init.ts new file mode 100644 index 00000000..a22c818c --- /dev/null +++ b/releases/cli-v1/commands/init.ts @@ -0,0 +1,114 @@ +import { relative } from "node:path"; + +import { input, select } from "@inquirer/prompts"; +import chalk from "chalk"; +import { Command } from "commander"; +import ora, { Ora } from "ora"; + +import { getApp, listOrganizations } from "../services/apps.js"; +import { configStore, typeFormats } from "../stores/config.js"; +import { DEFAULT_TYPES_OUTPUT } from "../utils/constants.js"; +import { handleError } from "../utils/errors.js"; +import { appIdOption, overwriteOption } from "../utils/options.js"; + +type InitArgs = { + appId?: string; + overwrite?: boolean; +}; + +export const initAction = async ({ + appId: requestedAppId, + overwrite, +}: InitArgs = {}) => { + let spinner: Ora | undefined; + + try { + // Check if config already exists + const configPath = configStore.getConfigPath(); + if (configPath && !overwrite) { + throw new Error( + "Reflag is already initialized. Use --overwrite to overwrite.", + ); + } + + console.log("\nWelcome to ◪ Reflag!\n"); + 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."); + + const org = + orgs.length === 1 + ? orgs[0] + : await select({ + message: "Select an organization", + choices: orgs.map((candidate) => ({ + name: `${candidate.name} (${candidate.id})`, + value: candidate, + })), + }); + + if (!org.apps.length) { + throw new Error( + `No apps found in '${org.name}'. Choose another organization or create an app.`, + ); + } + + appId = await select({ + 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, + })), + }); + } + + // Get types output path + const typesOutput = await input({ + message: "Where should we generate the types?", + default: DEFAULT_TYPES_OUTPUT, + }); + + // Get types output format + const typesFormat = await select({ + message: "What is the output format?", + choices: typeFormats.map((format) => ({ + name: format, + value: format, + })), + default: "react", + }); + + // Update config + configStore.setConfig({ + appId, + typesOutput: [{ path: typesOutput, format: typesFormat }], + }); + + // Create config file + spinner = ora("Creating configuration...").start(); + await configStore.saveConfigFile(overwrite); + + spinner.succeed( + `Configuration created at ${chalk.cyan(relative(process.cwd(), configStore.getConfigPath()!))}.`, + ); + } catch (error) { + if (spinner?.isSpinning) spinner.fail(); + handleError(error, "Initialization"); + } +}; + +export function registerInitCommand(cli: Command) { + cli + .command("init") + .description("Initialize a new Reflag configuration.") + .addOption(overwriteOption) + .addOption(appIdOption) + .action(initAction); +} diff --git a/releases/cli-v1/commands/mcp.ts b/releases/cli-v1/commands/mcp.ts new file mode 100644 index 00000000..dd8c8f31 --- /dev/null +++ b/releases/cli-v1/commands/mcp.ts @@ -0,0 +1,184 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, join, relative } from "node:path"; + +import { select } from "@inquirer/prompts"; +import chalk from "chalk"; +import { Command } from "commander"; +import { parse as parseJSON, stringify as stringifyJSON } from "comment-json"; +import ora, { type Ora } from "ora"; + +import { + ConfigPaths, + getServersConfig, + resolveConfigPath, + SupportedEditor, + SupportedEditors, +} from "../services/mcp.js"; +import { configStore } from "../stores/config.js"; +import { handleError } from "../utils/errors.js"; +import { fileExists } from "../utils/file.js"; +import { configScopeOption, editorOption } from "../utils/options.js"; + +export const mcpAction = async (options: { + editor?: SupportedEditor; + scope?: "local" | "global"; +}) => { + const config = configStore.getConfig(); + let spinner: Ora | undefined; + let selectedEditor = options.editor; + + // Select Editor/Client + if (!selectedEditor) { + selectedEditor = await select({ + message: "Which editor do you want to configure?", + choices: SupportedEditors.map((value) => ({ + value, + name: ConfigPaths[value].name, + })), + }); + } + + // Determine Config Path + const projectPath = configStore.getProjectPath(); + const globalPath = resolveConfigPath(selectedEditor, false); + const localPath = resolveConfigPath(selectedEditor, true); + const fullLocalPath = localPath ? join(projectPath, localPath) : undefined; + + if (!globalPath) { + throw new Error(`Unsupported platform for editor: ${selectedEditor}`); + } + + let configPathType: "global" | "local" = "global"; + if (fullLocalPath) { + if (options.scope) { + configPathType = options.scope; + } else { + configPathType = await select<"global" | "local">({ + message: "Configure global or project-local settings?", + choices: [ + { + name: `Local (${relative(projectPath, fullLocalPath)})`, + value: "local", + }, + { name: `Global (${globalPath})`, value: "global" }, + ], + }); + } + } + const configPath = configPathType === "local" ? fullLocalPath! : globalPath; + const displayConfigPath = + configPathType === "local" ? relative(projectPath, configPath) : configPath; + + // Read/Parse Config File + spinner = ora( + `Reading configuration file: ${chalk.cyan(displayConfigPath)}...`, + ).start(); + + let editorConfig: any = {}; + if (await fileExists(configPath)) { + const content = await readFile(configPath, "utf-8"); + // Attempt to parse JSON, handle potential comments if needed + try { + editorConfig = parseJSON(content); + } catch { + spinner.fail( + `Failed to parse configuration file ${chalk.cyan(displayConfigPath)}.`, + ); + } + spinner.succeed( + `Read configuration file ${chalk.cyan(displayConfigPath)}.`, + ); + } else { + spinner.info("Configuration file not found, will create a new one."); + editorConfig = {}; // Initialize empty config if file doesn't exist + } + + // Ensure MCP servers object exists + const serversConfig = getServersConfig( + editorConfig, + selectedEditor, + configPathType, + ); + + // Check for existing Reflag servers + const existingReflagEntries = Object.keys(serversConfig).filter((key) => + /reflag/i.test(key), + ); + + // Prompt for Add/Update + let targetEntryKey: string; + const defaultNewKey = `Reflag`; + + if (existingReflagEntries.length === 0) { + targetEntryKey = defaultNewKey; + console.log(`Adding new MCP server entry: ${chalk.cyan(targetEntryKey)}`); + } else { + const choices = [ + { name: `Add: ${defaultNewKey}`, value: "add_new" }, + ...existingReflagEntries.map((key) => ({ + name: `Update: ${key}`, + value: key, + })), + ]; + + const choice = await select({ + message: "Add a new MCP server or update an existing one?", + choices, + }); + + if (choice === "add_new") { + targetEntryKey = defaultNewKey; + console.log(`Adding new MCP server entry: ${chalk.cyan(targetEntryKey)}`); + } else { + targetEntryKey = choice; + console.log( + `Updating existing MCP server entry: ${chalk.cyan(targetEntryKey)}`, + ); + } + } + + // Construct the MCP endpoint URL + const newEntryValue = { + url: config.apiUrl + "/mcp", + }; + + // Update Config Object + serversConfig[targetEntryKey] = newEntryValue; + + // Write Config File + spinner = ora( + `Writing configuration to ${chalk.cyan(displayConfigPath)}...`, + ).start(); + + try { + // Ensure the directory exists before writing + await mkdir(dirname(configPath), { recursive: true }); + const configString = stringifyJSON(editorConfig, null, 2); + + await writeFile(configPath, configString); + spinner.succeed( + `Configuration updated successfully in ${chalk.cyan(displayConfigPath)}.`, + ); + + console.log( + chalk.grey( + "You may need to restart your editor for changes to take effect.", + ), + ); + } catch (error) { + spinner.fail( + `Failed to write configuration file ${chalk.cyan(displayConfigPath)}.`, + ); + + handleError(error, "MCP Configuration"); + } +}; + +export function registerMcpCommand(cli: Command) { + cli + .command("mcp") + .description("Configure Reflag's remote MCP server for your AI assistant.") + .addOption(editorOption) + .addOption(configScopeOption) + .action(mcpAction); +} diff --git a/releases/cli-v1/commands/new.ts b/releases/cli-v1/commands/new.ts new file mode 100644 index 00000000..303abb78 --- /dev/null +++ b/releases/cli-v1/commands/new.ts @@ -0,0 +1,48 @@ +import { Command } from "commander"; + +import { configStore, type TypeFormat } from "../stores/config.js"; +import { + appIdOption, + flagKeyOption, + flagNameArgument, + typesFormatOption, + typesOutOption, +} from "../utils/options.js"; +import { createFlagAction, generateTypesAction } from "./flags.js"; +import { initAction } from "./init.js"; + +type NewArgs = { + appId?: string; + out?: string; + format?: TypeFormat; + key?: string; +}; + +export const newAction = async ( + name: string | undefined, + { appId, out, format, key }: NewArgs, +) => { + if (!configStore.getConfigPath()) { + await initAction({ appId }); + } + configStore.setConfig({ + appId, + typesOutput: out ? [{ path: out, format: format || "react" }] : undefined, + }); + await createFlagAction(name, { key }); + await generateTypesAction(); +}; + +export function registerNewCommand(cli: Command) { + cli + .command("new") + .description( + "Initialize the Reflag CLI, authenticates, and creates a new flag.", + ) + .addOption(appIdOption) + .addOption(typesOutOption) + .addOption(typesFormatOption) + .addOption(flagKeyOption) + .addArgument(flagNameArgument) + .action(newAction); +} diff --git a/releases/cli-v1/commands/rules.ts b/releases/cli-v1/commands/rules.ts new file mode 100644 index 00000000..383048c9 --- /dev/null +++ b/releases/cli-v1/commands/rules.ts @@ -0,0 +1,119 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, join, relative } from "node:path"; + +import { confirm } from "@inquirer/prompts"; +import chalk from "chalk"; +import { Command } from "commander"; +import ora from "ora"; + +import { getCopilotInstructions, getCursorRules } from "../services/rules.js"; +import { configStore } from "../stores/config.js"; +import { handleError } from "../utils/errors.js"; +import { fileExists } from "../utils/file.js"; +import { rulesFormatOption, yesOption } from "../utils/options.js"; + +type RulesArgs = { + format?: string; + yes?: boolean; +}; + +const REFLAG_SECTION_START = ""; +const REFLAG_SECTION_END = ""; + +async function confirmOverwrite( + filePath: string, + yes: boolean, + append: boolean = false, +): Promise { + if (yes) return true; + + if (await fileExists(filePath)) { + const projectPath = configStore.getProjectPath(); + const relativePath = relative(projectPath, filePath); + + return await confirm({ + message: `Rules ${chalk.cyan(relativePath)} already exists. ${ + append ? "Append rules?" : "Overwrite rules?" + }`, + default: false, + }); + } + + return true; +} + +function wrapInMarkers(content: string): string { + return `${REFLAG_SECTION_START}\n\n${content}\n\n${REFLAG_SECTION_END}`; +} + +function replaceOrAppendSection( + existingContent: string, + newContent: string, +): string { + const wrappedContent = wrapInMarkers(newContent); + const sectionRegex = new RegExp( + `${REFLAG_SECTION_START}[\\s\\S]*?${REFLAG_SECTION_END}`, + "g", + ); + + if (sectionRegex.test(existingContent)) { + return existingContent.replace(sectionRegex, wrappedContent); + } + + return `${existingContent}\n\n${wrappedContent}`; +} + +export const rulesAction = async ({ + format = "cursor", + yes = false, +}: RulesArgs = {}) => { + const projectPath = configStore.getProjectPath(); + const appendFormats = ["copilot"]; + let destPath: string; + let content: string; + + // Determine destination and content based on format + if (format === "cursor") { + destPath = join(projectPath, ".cursor", "rules", "reflag.mdc"); + content = getCursorRules(); + } else if (format === "copilot") { + destPath = join(projectPath, ".github", "copilot-instructions.md"); + content = getCopilotInstructions(); + } else { + console.error(`No rules added. Invalid format ${chalk.cyan(format)}.`); + return; + } + + // Check for overwrite and write file + if (await confirmOverwrite(destPath, yes, appendFormats.includes(format))) { + const spinner = ora("Adding rules...").start(); + try { + await mkdir(dirname(destPath), { recursive: true }); + + if (appendFormats.includes(format) && (await fileExists(destPath))) { + const existingContent = await readFile(destPath, "utf-8"); + content = replaceOrAppendSection(existingContent, content); + } + + await writeFile(destPath, content); + spinner.succeed( + `Rules added to ${chalk.cyan(relative(projectPath, destPath))}. +${chalk.grey("These rules should be committed to your project's version control.")}`, + ); + } catch (error) { + spinner.fail("Failed to add rules."); + handleError(error, "Rules"); + } + } else { + console.log("Skipping adding rules."); + } +}; + +export function registerRulesCommand(cli: Command) { + cli + .command("rules") + .description("Add Reflag LLM rules to your project.") + .addOption(rulesFormatOption) + .addOption(yesOption) + .action(rulesAction); +} diff --git a/releases/cli-v1/index.ts b/releases/cli-v1/index.ts new file mode 100755 index 00000000..7cc9d568 --- /dev/null +++ b/releases/cli-v1/index.ts @@ -0,0 +1,115 @@ +#!/usr/bin/env node +import chalk from "chalk"; +import { program } from "commander"; + +import { registerAppCommands } from "./commands/apps.js"; +import { registerAuthCommands } from "./commands/auth.js"; +import { registerFlagCommands } from "./commands/flags.js"; +import { registerInitCommand } from "./commands/init.js"; +import { registerMcpCommand } from "./commands/mcp.js"; +import { registerNewCommand } from "./commands/new.js"; +import { registerRulesCommand } from "./commands/rules.js"; +import { authStore } from "./stores/auth.js"; +import { configStore } from "./stores/config.js"; +import { + apiKeyOption, + apiUrlOption, + baseUrlOption, + debugOption, + orgIdOption, +} from "./utils/options.js"; +import { stripTrailingSlash } from "./utils/urls.js"; +import { checkLatest as checkLatestVersion } from "./utils/version.js"; + +type Options = { + debug?: boolean; + baseUrl?: string; + apiUrl?: string; + apiKey?: string; + orgId?: string; +}; + +async function main() { + // Start a version check in the background + // unhandled promise rejection can happen even without the `await` + // so we need a `catch` here. + const cliVersionCheckPromise = checkLatestVersion().catch(() => ({ + latestVersion: "unknown", + currentVersion: "unknown", + isNewerAvailable: false, + })); + + // Must load tokens and config before anything else + await authStore.initialize(); + await configStore.initialize(); + + // Global options + program.addOption(debugOption); + program.addOption(baseUrlOption); + program.addOption(apiUrlOption); + program.addOption(apiKeyOption); + program.addOption(orgIdOption); + + // Pre-action hook + program.hook("preAction", async () => { + const { + debug, + baseUrl, + apiUrl, + apiKey: explicitApiKey, + orgId, + } = program.opts(); + const cleanedBaseUrl = stripTrailingSlash(baseUrl?.trim()); + const cleanedApiUrl = stripTrailingSlash(apiUrl?.trim()); + + const apiKey = explicitApiKey ?? process.env.REFLAG_API_KEY; + + if (typeof apiKey === "string" && apiKey.length > 0) { + console.info( + chalk.yellow( + "API key supplied. Using it instead of normal personal authentication.", + ), + ); + authStore.useApiKey(apiKey); + } + + configStore.setConfig({ + baseUrl: cleanedBaseUrl, + apiUrl: cleanedApiUrl || (cleanedBaseUrl && `${cleanedBaseUrl}/api`), + orgId: orgId?.trim(), + }); + + const { latestVersion, currentVersion, isNewerAvailable } = + await cliVersionCheckPromise; + + if (isNewerAvailable) { + console.info( + `A new version of the CLI is available: ${chalk.yellow( + currentVersion, + )} -> ${chalk.green(latestVersion)}. Update to ensure you have the latest features and bug fixes.`, + ); + } + + if (debug) { + console.debug(chalk.cyan("\nDebug mode enabled.")); + console.debug( + "Reading config from:", + chalk.cyan(configStore.getConfigPath()), + ); + console.table(configStore.getConfig()); + } + }); + + // Main program + registerNewCommand(program); + registerInitCommand(program); + registerAuthCommands(program); + registerAppCommands(program); + registerFlagCommands(program); + registerMcpCommand(program); + registerRulesCommand(program); + + program.parse(process.argv); +} + +void main(); diff --git a/releases/cli-v1/package.json b/releases/cli-v1/package.json new file mode 100644 index 00000000..77844685 --- /dev/null +++ b/releases/cli-v1/package.json @@ -0,0 +1,72 @@ +{ + "name": "@reflag/cli", + "version": "1.0.5", + "description": "CLI for Reflag service", + "homepage": "https://docs.reflag.com/", + "license": "MIT", + "author": "Reflag.", + "repository": { + "type": "git", + "url": "https://github.com/reflagcom/javascript.git" + }, + "bin": { + "reflag": "./dist/index.js" + }, + "files": [ + "dist", + "schema.json" + ], + "type": "module", + "main": "./dist/index.js", + "exports": { + ".": "./dist/index.js" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "tsc && shx chmod +x dist/index.js", + "reflag": "yarn build && ./dist/index.js", + "test": "vitest run", + "test:watch": "vitest", + "test:ci": "yarn test --reporter=default --reporter=junit --outputFile=junit.xml", + "coverage": "vitest run --coverage", + "lint": "oxlint .", + "lint:ci": "oxlint .", + "format": "yarn fmt:fix && yarn lint:fix", + "preversion": "yarn lint && yarn fmt && yarn vitest run -c vite.config.js && yarn build", + "lint:fix": "oxlint --fix .", + "fmt": "oxfmt --check .", + "fmt:fix": "oxfmt --write ." + }, + "dependencies": { + "@inquirer/prompts": "^7.9.0", + "ajv": "^8.17.1", + "chalk": "^5.3.0", + "change-case": "^5.4.4", + "commander": "^12.1.0", + "comment-json": "^4.2.5", + "express": "^4.22.3", + "fast-deep-equal": "^3.1.3", + "find-up": "^7.0.0", + "open": "^10.1.0", + "ora": "^8.1.0", + "semver": "^7.7.2", + "slug": "^10.0.0", + "zod": "^4.6.7" + }, + "devDependencies": { + "@reflag/tsconfig": "^0.0.2", + "@types/express": "^5.0.0", + "@types/node": "^22.5.1", + "@types/semver": "^7.7.0", + "@types/slug": "^5.0.9", + "shx": "^0.3.4", + "typescript": "^5.5.4", + "vitest": "^4.1.12" + }, + "engines": { + "node": ">=18.0.0" + }, + "packageManager": "yarn@4.1.1" +} diff --git a/releases/cli-v1/schema.json b/releases/cli-v1/schema.json new file mode 100644 index 00000000..9d249c91 --- /dev/null +++ b/releases/cli-v1/schema.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Reflag cli schema", + "type": "object", + "properties": { + "baseUrl": { + "type": "string", + "pattern": "^https?://.*", + "description": "Base URL for the API. Defaults to https://app.reflag.com." + }, + "apiUrl": { + "type": "string", + "pattern": "^https?://.*", + "description": "API URL for the API. Defaults to https://app.reflag.com/api." + }, + "appId": { + "type": "string", + "minLength": 14, + "maxLength": 14, + "description": "Mandatory ID for the Reflag app. You can find it by calling reflag apps list." + }, + "orgId": { + "type": "string", + "minLength": 1, + "description": "Optional organization ID to restrict app discovery and commands. You can find it with reflag apps list." + }, + "typesOutput": { + "type": "array", + "description": "List of paths to output the types. The path is relative to the current working directory.", + "items": { + "type": "object", + "properties": { + "path": { "type": "string" }, + "format": { "type": "string", "enum": ["react", "node"] } + }, + "required": ["path"] + } + } + }, + "required": ["appId"] +} diff --git a/releases/cli-v1/services/apps.ts b/releases/cli-v1/services/apps.ts new file mode 100644 index 00000000..b58b2664 --- /dev/null +++ b/releases/cli-v1/services/apps.ts @@ -0,0 +1,69 @@ +import { authStore } from "../stores/auth.js"; +import { configStore } from "../stores/config.js"; +import { authRequest } from "../utils/auth.js"; +import type { KeyFormat } from "../utils/gen.js"; + +type AppSummary = { + id: string; + name: string; + demo: boolean; + environments: { id: string; name: string; isProduction: boolean }[]; +}; + +type OrgSummary = { + id: string; + name: string; + featureKeyFormat: KeyFormat; +}; + +type Organization = OrgSummary & { apps: AppSummary[] }; +export type App = AppSummary & { org: OrgSummary }; + +let organizations: Promise | undefined; + +async function fetchOrganizations(): Promise { + const { isApiKey } = authStore.getToken(configStore.getConfig("baseUrl")); + if (isApiKey) { + // The membership list is only for personal sign-ins. Bootstrap returns + // just the app associated with this key. + const { org } = await authRequest<{ org: Organization | null }>( + "/bootstrap", + ); + return org ? [org] : []; + } + + const { data } = await authRequest<{ data: Organization[] }>("/orgs"); + return data; +} + +export async function listOrganizations(): Promise { + const orgs = await (organizations ??= fetchOrganizations()); + const orgId = configStore.getConfig("orgId"); + if (orgId === undefined) return orgs; + + const org = orgs.find(({ id }) => id === orgId); + if (!org) { + throw new Error( + `Organization '${orgId}' was not found or is not accessible. Check --org-id or orgId in reflag.config.json.`, + ); + } + return [org]; +} + +export async function listApps(): Promise { + return (await listOrganizations()).flatMap( + ({ id, name, featureKeyFormat, apps }) => + apps.map((app) => ({ ...app, org: { id, name, featureKeyFormat } })), + ); +} + +export async function getApp(id: string): Promise { + const app = (await listApps()).find(({ id: appId }) => appId === id); + if (app) return app; + + const orgId = configStore.getConfig("orgId"); + const scope = orgId === undefined ? "" : ` in organization '${orgId}'`; + throw new Error( + `App '${id}' was not found or is not accessible${scope}. Use \`reflag apps list\` to see available apps.`, + ); +} diff --git a/releases/cli-v1/services/flags.ts b/releases/cli-v1/services/flags.ts new file mode 100644 index 00000000..b23a8001 --- /dev/null +++ b/releases/cli-v1/services/flags.ts @@ -0,0 +1,94 @@ +import { z } from "zod"; + +import { authRequest } from "../utils/auth.js"; +import { booleanish, EnvironmentQuerySchema } from "../utils/schemas.js"; +import { PaginatedResponse } from "../utils/types.js"; + +export type Stage = { + id: string; + name: string; + order: number; +}; + +export type RemoteConfigVariant = { + key?: string; + payload?: any; +}; + +export type RemoteConfig = { + variants: [ + { + variant: RemoteConfigVariant; + }, + ]; +}; + +export type FlagName = { + id: string; + name: string; + key: string; +}; + +export type Flag = FlagName & { + description: string | null; + remoteConfigs: RemoteConfig[]; + stage: Stage | null; +}; + +export type FlagsResponse = PaginatedResponse; + +export const FlagsQuerySchema = EnvironmentQuerySchema.extend({ + sortBy: z.string().default("key").describe("Field to sort features by"), + sortOrder: z + .enum(["asc", "desc"]) + .default("asc") + .describe("Sort direction (ascending or descending)"), + includeRemoteConfigs: booleanish + .default(false) + .describe("Include remote configuration data"), +}).strict(); + +export const FlagCreateSchema = z + .object({ + name: z + .string() + .min(1, "Flag name is required") + .describe("Name of the flag"), + key: z + .string() + .min(1, "Flag key is required") + .describe("Unique identifier key for the flag"), + description: z + .string() + .optional() + .describe("Optional description of the flag"), + }) + .strict(); + +export type FlagsQuery = z.input; +export type FlagCreate = z.input; + +export async function listFlags(appId: string, query: FlagsQuery) { + return authRequest(`/apps/${appId}/features`, { + params: FlagsQuerySchema.parse(query), + }); +} + +type CreateFlagResponse = { + feature: FlagName & { + description: string | null; + }; +}; + +export async function createFlag(appId: string, featureData: FlagCreate) { + return authRequest(`/apps/${appId}/features`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + source: "event", + ...FlagCreateSchema.parse(featureData), + }), + }).then(({ feature }) => feature); +} diff --git a/releases/cli-v1/services/mcp.ts b/releases/cli-v1/services/mcp.ts new file mode 100644 index 00000000..9bb28136 --- /dev/null +++ b/releases/cli-v1/services/mcp.ts @@ -0,0 +1,91 @@ +import { resolvePath } from "../utils/file.js"; + +export const SupportedEditors = [ + "cursor", + "vscode", + "claude", + "windsurf", +] as const; +export type SupportedEditor = (typeof SupportedEditors)[number]; + +type ConfigPaths = { + name: string; + global: + | { + mac: string; + windows: string; + linux?: string; + } + | string; + local?: string; +}; + +export const ConfigPaths: Record = { + cursor: { + name: "Cursor", + global: "~/.cursor/mcp.json", + local: ".cursor/mcp.json", + }, + vscode: { + name: "Visual Studio Code", + global: { + mac: "~/Library/Application Support/Code/User/settings.json", + linux: "~/.config/Code/User/settings.json", + windows: "@/Code/User/settings.json", + }, + local: ".vscode/mcp.json", + }, + claude: { + name: "Claude Desktop", + global: { + mac: "~/Library/Application Support/Claude/claude_desktop_config.json", + windows: "@/Claude/claude_desktop_config.json", + }, + }, + windsurf: { + name: "Windsurf", + global: "~/.codeium/windsurf/mcp_config.json", + }, +}; + +export function resolveConfigPath(editor: SupportedEditor, local = false) { + const editorConfig = ConfigPaths[editor]; + const paths = local ? editorConfig.local : editorConfig.global; + + if (!paths) return undefined; + + if (typeof paths === "string") { + return resolvePath(paths); + } + + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (process.platform) { + case "darwin": + return resolvePath(paths.mac); + case "win32": + return resolvePath(paths.windows); + case "linux": + return paths.linux ? resolvePath(paths.linux) : undefined; + default: + return undefined; + } +} + +export function getServersConfig( + editorConfig: any, + selectedEditor: SupportedEditor, + configPathType: "global" | "local", +) { + if (selectedEditor === "vscode") { + if (configPathType === "global") { + editorConfig.mcp = editorConfig.mcp || {}; + editorConfig.mcp.servers = editorConfig.mcp.servers || {}; + return editorConfig.mcp.servers; + } else { + editorConfig.servers = editorConfig.servers || {}; + return editorConfig.servers; + } + } + editorConfig.mcpServers = editorConfig.mcpServers || {}; + return editorConfig.mcpServers; +} diff --git a/releases/cli-v1/services/rules.ts b/releases/cli-v1/services/rules.ts new file mode 100644 index 00000000..919bb30f --- /dev/null +++ b/releases/cli-v1/services/rules.ts @@ -0,0 +1,302 @@ +export function getCursorRules() { + return ` +--- +description: Guidelines for implementing flagging using Reflag feature management service +globs: "**/*.ts, **/*.tsx, **/*.js, **/*.jsx" +--- + +${rules} +`.trim(); +} + +export function getCopilotInstructions() { + return rules; +} + +const rules = /* markdown */ ` +# Reflag Flag Management Service for LLMs + +Reflag is a comprehensive feature management service offering flags, user feedback collection, adoption tracking, and remote configuration for your applications across various JavaScript frameworks, particularly React, Next.js, Node.js, vanilla browser, CLI, and OpenFeature environments. Follow these best practices for flagging. + +## Follow Official Documentation + +- Refer to [Reflag's official documentation](mdc:https:/docs.reflag.com) for implementation details. +- Adhere to Reflag's recommended patterns for each framework. + +## Reflag SDK Usage + +- Configure \`ReflagProvider\` or \`ReflagClient\` properly at application entry points. +- Leverage Reflag CLI for generating type-safe feature definitions. +- Write clean, type-safe code when applying Reflag flags. +- Follow established patterns in the project. + +## Flag Implementation + +- Create reusable hooks and utilities for consistent feature management. +- Write clear comments for usage and checks of a flag. +- Properly handle feature loading states to prevent UI flashing. +- Implement proper error fallbacks when flag services are unavailable. + +## Flag Targeting + +- Use release stages to manage feature rollout (for example, development, staging, production). +- Use targeting modes effectively: + - \`none\`: Flag is disabled for all targets. + - \`some\`: Flag is enabled only for specified targets. + - \`everyone\`: Flag is enabled for all targets. +- Target features to specific users, companies, or segments. + +## Analytics and Feedback + +- Track feature usage with Reflag analytics. +- Collect user feedback on features. +- Monitor feature adoption and health. + +## Common Concepts + +### Targeting Rules + +Targeting rules are entities used in Reflag to describe the target audience of a given feature. The target audience refers to the users who can interact with the feature within your application. Additionally, each targeting rule contains a value that is used for the target audience. + +### Flag Stages + +Release stages in Reflag allow setting up app-wide feature access targeting rules. Each release stage defines targeting rules for each available environment. Later, during the development of new features, you can apply all those rules automatically by selecting an available release stage. + +Release stages are useful tools when a standard release workflow is used in your organization. + +Predefined stages: + +- In development +- Internal +- Beta +- General Availability + +### Segments + +A segment entity in Reflag is a dynamic collection of companies. Segments' dynamic nature results from the fact that they use filters to evaluate which companies are included in them. + +#### Segment filters can be constructed using any combination of the following rules: + +- company attributes +- user feature access +- feature metrics +- other segments + +### Integrations + +Connect Reflag with your existing tools: + +- Linear +- Datadog +- Segment +- PostHog +- Amplitude +- Mixpanel +- AWS S3 +- Slack + +## React SDK Implementation + +### Installation + +\`\`\`bash +npm i @reflag/react-sdk +\`\`\` + +### Key Features + +- Flag toggling with fine-grained targeting +- User feedback collection +- Flag usage tracking +- Remote configuration +- Type-safe feature management + +### Basic Setup + +1. Add the \`ReflagProvider\` to wrap your application: + +\`\`\`jsx +import { ReflagProvider } from "@reflag/react-sdk"; + + + +; +\`\`\` + +1. Create a feature and generate type-safe definitions: + +\`\`\`bash +npm i --save-dev @reflag/cli +npx reflag new "Flag name" +\`\`\` + +\`\`\`typescript +// DO NOT EDIT THIS FILE. IT IS GENERATED BY THE BUCKET CLI AND WILL BE OVERWRITTEN. +// eslint-disable +// prettier-ignore +import "@reflag/react-sdk"; + +declare module "@reflag/react-sdk" { + export interface Flags { + "flag-key": { + config: { + payload: { + tokens: number; + }; + }; + }; + } +} +\`\`\` + +1. Use features in your components: + +\`\`\`jsx +import { useFlag } from "@reflag/react-sdk"; + +function StartHuddleButton() { + const { + isLoading, // true while features are being loaded + isEnabled, // boolean indicating if the feature is enabled + config: { + // feature configuration + key, // string identifier for the config variant + payload, // type-safe configuration object + }, + track, // function to track feature usage + requestFeedback, // function to request feedback for this feature + } = useFlag("huddle"); + + if (isLoading) { + return ; + } + + if (!isEnabled) { + return null; + } + + return ( + <> + + + + ); +} +\`\`\` + +### Core React Hooks + +- \`useFlag()\` - Access feature status, config, and tracking +- \`useTrack()\` - Send custom events to Reflag +- \`useRequestFeedback()\` - Open feedback dialog for a feature +- \`useSendFeedback()\` - Programmatically send feedback +- \`useUpdateUser()\` / \`useUpdateCompany()\` - Update user/company data +- \`useUpdateOtherContext()\` - Update session-only context data +- \`useClient()\` - Access the underlying Reflag client + +## Node.js SDK Implementation + +### Installation + +\`\`\`bash +npm i @reflag/node-sdk +\`\`\` + +### Key Features + +- Server-side flag evaluation +- User and company context management +- Flexible integration options +- Event tracking + +### Basic Setup + +\`\`\`javascript +import { ReflagClient } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, +}); + +// Check if a feature is enabled +const isEnabled = await client.isEnabled("flag-key", { + user: { id: "user_123", role: "admin" }, + company: { id: "company_456", plan: "enterprise" }, +}); +\`\`\` + +### Context Management + +\`\`\`javascript +// Set user and company context +await client.setContext({ + user: { + id: "user_123", + email: "user@example.com", + role: "admin", + }, + company: { + id: "company_456", + name: "Acme Inc", + plan: "enterprise", + }, +}); + +// Check feature after setting context +const isEnabled = await client.isEnabled("flag-key"); +\`\`\` + +### Flag Configuration + +\`\`\`javascript +// Get feature configuration +const config = await client.getConfig("flag-key", { + user: { id: "user_123" }, + company: { id: "company_456" }, +}); + +// Use the configuration +console.log(config.payload.maxDuration); +\`\`\` + +### Event Tracking + +\`\`\`javascript +// Track feature usage +await client.track("flag-key", { + user: { id: "user_123" }, + company: { id: "company_456" }, + metadata: { action: "completed" }, +}); + +// Track custom events +await client.trackEvent("custom-event", { + user: { id: "user_123" }, + company: { id: "company_456" }, + metadata: { value: 42 }, +}); +\`\`\` + +## Further Resources + +- [Official Documentation](mdc:https:/docs.reflag.com) +- [Docs llms.txt](mdc:https:/docs.reflag.com/llms.txt) +- [GitHub Repository](mdc:https:/github.com/reflagcom/javascript) +- [Example React App](mdc:https:/github.com/reflagcom/javascript/tree/main/packages/react-sdk/dev) +`.trim(); diff --git a/releases/cli-v1/stores/auth.ts b/releases/cli-v1/stores/auth.ts new file mode 100644 index 00000000..142ccb3a --- /dev/null +++ b/releases/cli-v1/stores/auth.ts @@ -0,0 +1,64 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; + +import { AUTH_FILE } from "../utils/constants.js"; + +class AuthStore { + protected tokens: Map = new Map(); + protected apiKey: string | undefined; + + async initialize() { + await this.loadTokenFile(); + } + + protected async loadTokenFile() { + try { + const content = await readFile(AUTH_FILE, "utf-8"); + this.tokens = new Map( + content + .split("\n") + .filter(Boolean) + .map((line) => { + const [baseUrl, token] = line.split("|"); + return [baseUrl, token]; + }), + ); + } catch { + // No tokens file found + } + } + + protected async saveTokenFile(newTokens: Map) { + const content = Array.from(newTokens.entries()) + .map(([baseUrl, token]) => `${baseUrl}|${token}`) + .join("\n"); + + await mkdir(dirname(AUTH_FILE), { recursive: true }); + await writeFile(AUTH_FILE, content); + + this.tokens = newTokens; + } + + getToken(baseUrl: string) { + return { + token: this.apiKey || this.tokens.get(baseUrl), + isApiKey: !!this.apiKey, + }; + } + + async setToken(baseUrl: string, newToken: string | null) { + if (newToken) { + this.tokens.set(baseUrl, newToken); + } else { + this.tokens.delete(baseUrl); + } + + await this.saveTokenFile(this.tokens); + } + + useApiKey(key: string) { + this.apiKey = key; + } +} + +export const authStore = new AuthStore(); diff --git a/releases/cli-v1/stores/config.ts b/releases/cli-v1/stores/config.ts new file mode 100644 index 00000000..31ffb016 --- /dev/null +++ b/releases/cli-v1/stores/config.ts @@ -0,0 +1,196 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; + +import { Ajv, ValidateFunction } from "ajv"; +import { + assign as assignJSON, + parse as parseJSON, + stringify as stringifyJSON, +} from "comment-json"; +import equal from "fast-deep-equal"; +import { findUp } from "find-up"; + +import { + CONFIG_FILE_NAME, + DEFAULT_API_URL, + DEFAULT_BASE_URL, + DEFAULT_TYPES_OUTPUT, + MODULE_ROOT, + SCHEMA_URL, +} from "../utils/constants.js"; +import { ConfigValidationError, handleError } from "../utils/errors.js"; +import { stripTrailingSlash } from "../utils/urls.js"; +import { current as currentVersion } from "../utils/version.js"; + +export const typeFormats = ["react", "node"] as const; +export type TypeFormat = (typeof typeFormats)[number]; + +export type TypesOutput = { + path: string; + format: TypeFormat; +}; + +type Config = { + $schema: string; + baseUrl: string; + apiUrl: string; + appId: string | undefined; + orgId?: string; + typesOutput: TypesOutput[]; +}; + +const defaultConfig: Config = { + $schema: SCHEMA_URL, + baseUrl: DEFAULT_BASE_URL, + apiUrl: DEFAULT_API_URL, + appId: undefined, + typesOutput: [{ path: DEFAULT_TYPES_OUTPUT, format: "react" }], +}; + +// Helper to normalize typesOutput to array format +export function normalizeTypesOutput( + output?: string | TypesOutput[], +): TypesOutput[] | undefined { + if (!output) return undefined; + if (typeof output === "string") { + return [{ path: output, format: "react" }]; + } + return output; +} + +class ConfigStore { + protected config: Config = { ...defaultConfig }; + protected configPath: string | undefined; + protected projectPath: string | undefined; + protected clientVersion: string | undefined; + protected validateConfig: ValidateFunction | undefined; + + async initialize() { + await this.createValidator(); + await this.loadConfigFile(); + } + + protected async createValidator() { + try { + // Using current config store file, resolve the schema.json path + const schemaPath = join(MODULE_ROOT, "schema.json"); + const content = await readFile(schemaPath, "utf-8"); + const parsed = parseJSON(content) as unknown as Config; + + const ajv = new Ajv(); + this.validateConfig = ajv.compile(parsed); + } catch { + handleError(new Error("Failed to load the config schema"), "Config"); + } + } + + protected async loadConfigFile() { + if (!this.validateConfig) { + handleError(new Error("Failed to load the config schema"), "Config"); + } + + // Load the client version from the module's package.json metadata + try { + const { version } = await currentVersion(); + this.clientVersion = version; + } catch { + // Should not be the case, but ignore if no package.json is found + } + + try { + const projectMetadataPath = await findUp("package.json"); + this.configPath = await findUp(CONFIG_FILE_NAME); + this.projectPath = dirname( + this.configPath ?? projectMetadataPath ?? process.cwd(), + ); + + if (!this.configPath) return; + + const content = await readFile(this.configPath, "utf-8"); + const parsed = parseJSON(content) as unknown as Partial; + + // Normalize values + if (parsed.baseUrl) + parsed.baseUrl = stripTrailingSlash(parsed.baseUrl.trim()); + if (parsed.apiUrl) + parsed.apiUrl = stripTrailingSlash(parsed.apiUrl.trim()); + if (parsed.typesOutput?.length) + parsed.typesOutput = normalizeTypesOutput(parsed.typesOutput); + + if (!this.validateConfig!(parsed)) { + handleError( + new ConfigValidationError(this.validateConfig!.errors), + "Config", + ); + } + + this.config = assignJSON(this.config, parsed); + } catch { + // No config file found + } + } + + /** + * Create a new config file with initial values. + * @param overwrite If true, overwrites existing config file. Defaults to false + */ + async saveConfigFile(overwrite = false) { + const configWithoutDefaults: Partial = assignJSON({}, this.config); + + // Only include non-default values and $schema + for (const untypedKey in configWithoutDefaults) { + const key = untypedKey as keyof Config; + if ( + !["$schema"].includes(key) && + equal(configWithoutDefaults[key], defaultConfig[key]) + ) { + delete configWithoutDefaults[key]; + } + } + + const configJSON = stringifyJSON(configWithoutDefaults, null, 2); + + if (this.configPath && !overwrite) { + throw new Error("Config file already exists"); + } + + if (this.configPath) { + await writeFile(this.configPath, configJSON); + } else { + // Write to the project path + const packageJSONPath = await findUp("package.json"); + this.projectPath = dirname(packageJSONPath ?? process.cwd()); + this.configPath = join(this.projectPath, CONFIG_FILE_NAME); + await writeFile(this.configPath, configJSON); + } + } + + getConfig(): Config; + getConfig(key: K): Config[K]; + getConfig(key?: K) { + return key ? this.config?.[key] : this.config; + } + + getConfigPath() { + return this.configPath; + } + + getClientVersion() { + return this.clientVersion; + } + + getProjectPath() { + return this.projectPath ?? process.cwd(); + } + + setConfig(newConfig: Partial) { + // Update the config with new values skipping undefined values + for (const untypedKey in newConfig) { + const key = untypedKey as keyof Config; + if (newConfig[key] === undefined) continue; + (this.config as any)[key] = newConfig[key]; + } + } +} + +export const configStore = new ConfigStore(); diff --git a/releases/cli-v1/test/apps.test.ts b/releases/cli-v1/test/apps.test.ts new file mode 100644 index 00000000..bf6eb8a3 --- /dev/null +++ b/releases/cli-v1/test/apps.test.ts @@ -0,0 +1,202 @@ +import { input, select } from "@inquirer/prompts"; +import { beforeEach, expect, it, vi } from "vitest"; + +import { authStore } from "../stores/auth.js"; +import { configStore } from "../stores/config.js"; +import { authRequest } from "../utils/auth.js"; + +vi.mock("../utils/auth.js", () => ({ authRequest: vi.fn() })); +vi.mock("@inquirer/prompts", () => ({ input: vi.fn(), select: vi.fn() })); +vi.mock("../stores/auth.js", () => ({ authStore: { getToken: vi.fn() } })); +vi.mock("../stores/config.js", async (importOriginal) => ({ + ...(await importOriginal()), + configStore: { + getConfig: vi.fn(), + getConfigPath: vi.fn(), + setConfig: vi.fn(), + saveConfigFile: vi.fn(), + }, +})); + +const orgs = [ + { + id: "org-1", + name: "First", + featureKeyFormat: "kebabCaseLower", + apps: [app("app-1")], + }, + { + id: "org-2", + name: "Second", + featureKeyFormat: "camelCase", + apps: [app("app-2"), app("app-3")], + }, + { + id: "org-3", + name: "Third", + featureKeyFormat: "kebabCaseLower", + apps: [app("app-4")], + }, +]; + +function app(id: string) { + return { + id, + name: "App", + demo: false, + environments: [ + { id: `${id}-prod`, name: "Production", isProduction: true }, + ], + }; +} + +const request = vi.mocked(authRequest); +const choose = vi.mocked(select); +let orgId: string | undefined; + +beforeEach(() => { + vi.resetModules(); + vi.resetAllMocks(); + orgId = undefined; + vi.mocked(authStore.getToken).mockReturnValue({ + token: "token", + isApiKey: false, + }); + vi.mocked(configStore.getConfig).mockImplementation((key) => + key === "orgId" ? orgId : "https://example.com", + ); + request.mockResolvedValue({ data: orgs }); +}); + +it("discovers apps across memberships and resolves an existing app ID without an org pin", async () => { + const { getApp, listApps } = await import("../services/apps.js"); + + expect( + (await listApps()).map(({ name, id, org }) => [name, id, org.name]), + ).toEqual([ + ["App", "app-1", "First"], + ["App", "app-2", "Second"], + ["App", "app-3", "Second"], + ["App", "app-4", "Third"], + ]); + await expect(getApp("app-2")).resolves.toMatchObject({ + org: { id: "org-2", featureKeyFormat: "camelCase" }, + environments: [{ id: "app-2-prod" }], + }); + expect(request).toHaveBeenCalledExactlyOnceWith("/orgs"); +}); + +it("filters both app discovery and explicit app IDs to the selected org", async () => { + orgId = "org-2"; + const { getApp, listApps } = await import("../services/apps.js"); + + expect((await listApps()).map(({ id }) => id)).toEqual(["app-2", "app-3"]); + await expect(getApp("app-1")).rejects.toThrow("in organization 'org-2'"); +}); + +it("rejects an unknown or inaccessible org without falling back", async () => { + orgId = "unavailable-org"; + const { listApps } = await import("../services/apps.js"); + await expect(listApps()).rejects.toThrow( + "Organization 'unavailable-org' was not found or is not accessible", + ); + expect(request).toHaveBeenCalledExactlyOnceWith("/orgs"); +}); + +it("keeps API keys bound to their original app and organization", async () => { + vi.mocked(authStore.getToken).mockReturnValue({ + token: "token", + isApiKey: true, + }); + request.mockResolvedValue({ org: { ...orgs[1], apps: [orgs[1].apps[1]] } }); + const { getApp, listApps } = await import("../services/apps.js"); + + expect((await listApps()).map(({ id }) => id)).toEqual(["app-3"]); + await expect(getApp("app-2")).rejects.toThrow( + "App 'app-2' was not found or is not accessible", + ); + orgId = "org-1"; + await expect(listApps()).rejects.toThrow( + "Organization 'org-1' was not found or is not accessible", + ); + expect(request).toHaveBeenCalledExactlyOnceWith("/bootstrap"); +}); + +function mockConfigCreation() { + vi.mocked(configStore.saveConfigFile).mockImplementation(async () => { + vi.mocked(configStore.getConfigPath).mockReturnValue("reflag.config.json"); + }); + vi.mocked(input).mockResolvedValue("gen/flags.d.ts"); +} + +it("prompts for an org and then shows only its apps during init", async () => { + mockConfigCreation(); + choose + .mockResolvedValueOnce(orgs[1]) + .mockResolvedValueOnce("app-3") + .mockResolvedValueOnce("react"); + const { initAction } = await import("../commands/init.js"); + + await initAction(); + + expect(choose).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ + message: "Select an organization", + choices: orgs.map((org) => ({ + name: `${org.name} (${org.id})`, + value: org, + })), + }), + ); + expect(choose).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + message: "Select an app in Second", + choices: [ + { name: "App (app-2)", value: "app-2" }, + { name: "App (app-3)", value: "app-3" }, + ], + }), + ); + expect(configStore.setConfig).toHaveBeenCalledWith({ + appId: "app-3", + typesOutput: [{ path: "gen/flags.d.ts", format: "react" }], + }); +}); + +it.each([false, true])( + "skips the org prompt in a one-org scope (pinned: %s)", + async (pinned) => { + mockConfigCreation(); + if (pinned) orgId = "org-2"; + else request.mockResolvedValue({ data: [orgs[1]] }); + choose.mockResolvedValueOnce("app-2").mockResolvedValueOnce("react"); + const { initAction } = await import("../commands/init.js"); + + await initAction(); + + expect(choose).toHaveBeenCalledTimes(2); + expect(choose).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ message: "Select an app in Second" }), + ); + }, +); + +it("accepts an explicit app ID at init without either picker", async () => { + mockConfigCreation(); + choose.mockResolvedValueOnce("react"); + const { initAction } = await import("../commands/init.js"); + + await initAction({ appId: "app-4" }); + + expect(choose).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: "What is the output format?", + }), + ); + expect(configStore.setConfig).toHaveBeenCalledWith( + expect.objectContaining({ appId: "app-4" }), + ); +}); diff --git a/releases/cli-v1/test/gen.test.ts b/releases/cli-v1/test/gen.test.ts new file mode 100644 index 00000000..4518f51e --- /dev/null +++ b/releases/cli-v1/test/gen.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; + +import type { Flag } from "../services/flags.js"; +import { genTypes } from "../utils/gen.js"; +import type { JSONPrimitive } from "../utils/json.js"; + +function flag(key: string, name: string, payload: JSONPrimitive): Flag { + return { + id: key, + key, + name, + description: null, + stage: null, + remoteConfigs: [{ variants: [{ variant: { payload } }] }], + }; +} + +describe("SDK v1 generation", () => { + it("emits distinct payload aliases when flag names normalize the same way", () => { + const output = genTypes([ + flag("first", "My Flag", 123), + flag("second", "My-Flag", "text"), + flag("third", "My flag", false), + ]); + + expect(output).toContain( + "first: { config: { payload: MyFlagConfigPayload } };", + ); + expect(output).toContain( + "second: { config: { payload: MyFlagConfigPayload_2 } };", + ); + expect(output).toContain( + "third: { config: { payload: MyFlagConfigPayload_3 } };", + ); + expect(output).toContain("export type MyFlagConfigPayload = number"); + expect(output).toContain("export type MyFlagConfigPayload_2 = string"); + expect(output).toContain("export type MyFlagConfigPayload_3 = boolean"); + }); + + it("emits valid alias names for digit-leading names and preserves valid Unicode names", () => { + const output = genTypes([ + flag("numeric", "42", true), + flag("unicode", "Éclair", true), + ]); + + expect(output).toContain("payload: _42ConfigPayload"); + expect(output).toContain("export type _42ConfigPayload = boolean"); + expect(output).toContain("payload: ÉclairConfigPayload"); + expect(output).toContain("export type ÉclairConfigPayload = boolean"); + }); +}); diff --git a/releases/cli-v1/test/json.test.ts b/releases/cli-v1/test/json.test.ts new file mode 100644 index 00000000..11337431 --- /dev/null +++ b/releases/cli-v1/test/json.test.ts @@ -0,0 +1,483 @@ +import { describe, expect, it } from "vitest"; + +import { + JSONToType, + mergeTypeASTs, + quoteKey, + stringifyTypeAST, + toTypeAST, + TypeAST, +} from "../utils/json.js"; + +describe("JSON utilities", () => { + describe("toTypeAST", () => { + it("should handle primitive values", () => { + expect(toTypeAST("test")).toEqual({ kind: "primitive", type: "string" }); + expect(toTypeAST(42)).toEqual({ kind: "primitive", type: "number" }); + expect(toTypeAST(true)).toEqual({ kind: "primitive", type: "boolean" }); + expect(toTypeAST(null)).toEqual({ kind: "primitive", type: "null" }); + }); + + it("should handle arrays", () => { + expect(toTypeAST([1, 2, 3])).toEqual({ + kind: "array", + elementType: { kind: "primitive", type: "number" }, + }); + + expect(toTypeAST([])).toEqual({ + kind: "array", + elementType: { kind: "primitive", type: "any" }, + }); + }); + + it("should handle arrays with mixed element types", () => { + expect(toTypeAST([1, "test", true])).toEqual({ + kind: "array", + elementType: { + kind: "union", + types: [ + { kind: "primitive", type: "number" }, + { kind: "primitive", type: "string" }, + { kind: "primitive", type: "boolean" }, + ], + }, + }); + + expect(toTypeAST([{ name: "John" }, { age: 30 }])).toEqual({ + kind: "array", + elementType: { + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: true, + }, + { + key: "age", + type: { kind: "primitive", type: "number" }, + optional: true, + }, + ], + }, + }); + }); + + it("should handle objects", () => { + expect(toTypeAST({ name: "John", age: 30 })).toEqual({ + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "age", + type: { kind: "primitive", type: "number" }, + optional: false, + }, + ], + }); + }); + + it("should handle nested structures", () => { + const input = { + user: { + name: "John", + contacts: [{ email: "john@example.com" }], + }, + }; + + const expected: TypeAST = { + kind: "object", + properties: [ + { + key: "user", + type: { + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "contacts", + type: { + kind: "array", + elementType: { + kind: "object", + properties: [ + { + key: "email", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + ], + }, + }, + optional: false, + }, + ], + }, + optional: false, + }, + ], + }; + + expect(toTypeAST(input)).toEqual(expected); + }); + }); + + describe("mergeTypeASTs", () => { + it("should handle empty array", () => { + expect(mergeTypeASTs([])).toEqual({ kind: "primitive", type: "any" }); + }); + + it("should return the same AST for single item arrays", () => { + const ast: TypeAST = { kind: "primitive", type: "string" }; + expect(mergeTypeASTs([ast])).toEqual(ast); + }); + + it("should merge same primitive types", () => { + const types: TypeAST[] = [ + { kind: "primitive", type: "number" }, + { kind: "primitive", type: "number" }, + ]; + expect(mergeTypeASTs(types)).toEqual({ + kind: "primitive", + type: "number", + }); + }); + + it("should create union for different primitive types", () => { + const types: TypeAST[] = [ + { kind: "primitive", type: "string" }, + { kind: "primitive", type: "number" }, + ]; + expect(mergeTypeASTs(types)).toEqual({ + kind: "union", + types: [ + { kind: "primitive", type: "string" }, + { kind: "primitive", type: "number" }, + ], + }); + }); + + it("should merge array types", () => { + const types: TypeAST[] = [ + { kind: "array", elementType: { kind: "primitive", type: "number" } }, + { kind: "array", elementType: { kind: "primitive", type: "string" } }, + ]; + expect(mergeTypeASTs(types)).toEqual({ + kind: "array", + elementType: { + kind: "union", + types: [ + { kind: "primitive", type: "number" }, + { kind: "primitive", type: "string" }, + ], + }, + }); + }); + + it("should merge object types and mark missing properties as optional", () => { + const types: TypeAST[] = [ + { + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "age", + type: { kind: "primitive", type: "number" }, + optional: false, + }, + ], + }, + { + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "email", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + ], + }, + ]; + + expect(mergeTypeASTs(types)).toEqual({ + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "age", + type: { kind: "primitive", type: "number" }, + optional: true, + }, + { + key: "email", + type: { kind: "primitive", type: "string" }, + optional: true, + }, + ], + }); + }); + + it("should create union for mixed kinds", () => { + const types: TypeAST[] = [ + { kind: "primitive", type: "string" }, + { kind: "array", elementType: { kind: "primitive", type: "number" } }, + ]; + + expect(mergeTypeASTs(types)).toEqual({ + kind: "union", + types, + }); + }); + }); + + describe("stringifyTypeAST", () => { + it("should stringify primitive types", () => { + expect(stringifyTypeAST({ kind: "primitive", type: "string" })).toBe( + "string", + ); + expect(stringifyTypeAST({ kind: "primitive", type: "number" })).toBe( + "number", + ); + expect(stringifyTypeAST({ kind: "primitive", type: "boolean" })).toBe( + "boolean", + ); + expect(stringifyTypeAST({ kind: "primitive", type: "null" })).toBe( + "null", + ); + }); + + it("should stringify array types", () => { + expect( + stringifyTypeAST({ + kind: "array", + elementType: { kind: "primitive", type: "string" }, + }), + ).toBe("(string)[]"); + }); + + it("should stringify object types", () => { + const ast: TypeAST = { + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "age", + type: { kind: "primitive", type: "number" }, + optional: true, + }, + ], + }; + + const expected = `{\n name: string,\n age?: number\n}`; + expect(stringifyTypeAST(ast)).toBe(expected); + }); + + it("should stringify empty objects", () => { + expect(stringifyTypeAST({ kind: "object", properties: [] })).toBe("{}"); + }); + + it("should quote object keys with special characters", () => { + const ast: TypeAST = { + kind: "object", + properties: [ + { + key: "my-key", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "my key", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "my.key", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "123key", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + ], + }; + + const expected = `{\n "my-key": string,\n "my key": string,\n "my.key": string,\n "123key": string\n}`; + expect(stringifyTypeAST(ast)).toBe(expected); + }); + + it("should stringify union types", () => { + const ast: TypeAST = { + kind: "union", + types: [ + { kind: "primitive", type: "string" }, + { kind: "primitive", type: "number" }, + ], + }; + + expect(stringifyTypeAST(ast)).toBe("string | number"); + }); + + it("should handle complex nested types", () => { + const ast: TypeAST = { + kind: "object", + properties: [ + { + key: "user", + type: { + kind: "object", + properties: [ + { + key: "name", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + { + key: "contacts", + type: { + kind: "array", + elementType: { + kind: "object", + properties: [ + { + key: "email", + type: { kind: "primitive", type: "string" }, + optional: false, + }, + ], + }, + }, + optional: false, + }, + ], + }, + optional: false, + }, + ], + }; + + const expected = + `{\n user: {\n name: string,\n contacts: ({\n email: string\n })[]` + + `\n }\n}`; + expect(stringifyTypeAST(ast)).toBe(expected); + }); + }); + + describe("JSONToType", () => { + it("should handle empty arrays", () => { + expect(JSONToType([])).toBeNull(); + }); + + it("should generate type for array of primitives", () => { + expect(JSONToType([1, 2, 3])).toBe("number"); + expect(JSONToType(["a", "b", "c"])).toBe("string"); + expect(JSONToType([1, "a", true])).toBe("number | string | boolean"); + }); + + it("should handle arrays with simple mixed element types", () => { + const expected = "(number | string | boolean)[]"; + expect(JSONToType([["a", true], [1]])).toBe(expected); + }); + + it("should handle arrays with advanced mixed element types", () => { + const expected = + "(number | string | boolean | {\n id?: number,\n name?: string\n})[]"; + expect( + JSONToType([ + [1, "a", true], + [{ id: 1 }, { name: "test" }], + ]), + ).toBe(expected); + }); + + it("should preserve optional properties when merging nested arrays", () => { + expect(JSONToType([[[{ a: 1 }, {}], [{ a: 2 }]]])).toBe( + "(({\n a?: number\n})[])[]", + ); + }); + + it("should merge arrays with nested arrays of mixed element types", () => { + const expected = "((boolean | number | string | {\n id: number\n})[])[]"; + expect(JSONToType([[[1, "test"], [true]], [[{ id: 1 }]]])).toBe(expected); + }); + + it("should generate type for array of objects", () => { + const expected = `{\n name: string,\n age?: number,\n email?: string\n}`; + expect( + JSONToType([ + { name: "John", age: 30 }, + { name: "Jane", email: "jane@example.com" }, + ]), + ).toBe(expected); + }); + + it("should escape quoted keys and preserve empty keys in generated types", () => { + expect(JSONToType([{ 'a"b': 1, "a\\b": true, "": "empty" }])).toBe( + String.raw`{ + "a\"b": number, + "a\\b": boolean, + "": string +}`, + ); + }); + + it("should handle complex nested structures", () => { + const expected = + `{\n user: {\n name: string,\n settings: {\n theme?: string,` + + `\n notifications?: boolean\n }\n }\n}`; + + expect( + JSONToType([ + { + user: { + name: "John", + settings: { theme: "dark" }, + }, + }, + { + user: { + name: "Jane", + settings: { notifications: true }, + }, + }, + ]), + ).toBe(expected); + }); + }); + + describe("quoteKey", () => { + it("should quote keys with special characters", () => { + expect(quoteKey("my-key")).toBe('"my-key"'); + expect(quoteKey("my key")).toBe('"my key"'); + expect(quoteKey("my.key")).toBe('"my.key"'); + expect(quoteKey("123key")).toBe('"123key"'); + expect(quoteKey("key")).toBe("key"); + }); + }); +}); diff --git a/releases/cli-v1/test/schemas.test.ts b/releases/cli-v1/test/schemas.test.ts new file mode 100644 index 00000000..7a72d723 --- /dev/null +++ b/releases/cli-v1/test/schemas.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; + +import { FlagCreateSchema, FlagsQuerySchema } from "../services/flags.js"; +import { booleanish, PaginationQueryBaseSchema } from "../utils/schemas.js"; + +describe("CLI schemas", () => { + it.each([ + ["true", true], + ["1", true], + ["false", false], + ["0", false], + [true, true], + [false, false], + ])("parses boolean-like input %s as %s", (input, expected) => { + expect(booleanish.parse(input)).toBe(expected); + }); + + it("preserves flag query defaults", () => { + expect(FlagsQuerySchema.parse({ envId: "env_test" })).toEqual({ + envId: "env_test", + sortBy: "key", + sortOrder: "asc", + includeRemoteConfigs: false, + }); + }); + + it("rejects unknown query and flag fields", () => { + expect( + FlagsQuerySchema.safeParse({ envId: "env_test", unknown: true }).success, + ).toBe(false); + expect( + FlagCreateSchema.safeParse({ name: "Flag", key: "flag", unknown: true }) + .success, + ).toBe(false); + }); + + it("coerces pagination input and enforces page-size bounds", () => { + const schema = PaginationQueryBaseSchema(); + expect(schema.parse({ pageIndex: "2", pageSize: "10" })).toEqual({ + sortOrder: "asc", + pageIndex: 2, + pageSize: 10, + }); + expect(schema.safeParse({ pageSize: 0 }).success).toBe(false); + expect(schema.safeParse({ pageSize: 101 }).success).toBe(false); + }); +}); diff --git a/releases/cli-v1/tsconfig.json b/releases/cli-v1/tsconfig.json new file mode 100644 index 00000000..d69ba529 --- /dev/null +++ b/releases/cli-v1/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "@reflag/tsconfig/library", + "compilerOptions": { + "outDir": "./dist/", + "target": "ESNext", + "module": "NodeNext", + "moduleResolution": "NodeNext" + }, + "include": ["**/*.ts"], + "exclude": ["node_modules", "dist", "**/*.spec.ts"] +} diff --git a/releases/cli-v1/utils/auth.ts b/releases/cli-v1/utils/auth.ts new file mode 100644 index 00000000..4ae4c376 --- /dev/null +++ b/releases/cli-v1/utils/auth.ts @@ -0,0 +1,352 @@ +import crypto from "crypto"; +import http from "http"; + +import chalk from "chalk"; +import open from "open"; + +import { authStore } from "../stores/auth.js"; +import { configStore } from "../stores/config.js"; +import { + CLIENT_VERSION_HEADER_NAME, + CLIENT_VERSION_HEADER_VALUE, + DEFAULT_AUTH_TIMEOUT, +} from "./constants.js"; +import { ResponseError } from "./errors.js"; +import { ParamType } from "./types.js"; +import { errorUrl, successUrl } from "./urls.js"; + +const maxRetryCount = 1; + +interface waitForAccessToken { + accessToken: string; + expiresAt: Date; +} + +async function getOAuthServerUrls(apiUrl: string) { + const { protocol, host } = new URL(apiUrl); + const wellKnownUrl = `${protocol}//${host}/.well-known/oauth-authorization-server`; + + const response = await fetch(wellKnownUrl, { + signal: AbortSignal.timeout(5000), + }); + + if (response.ok) { + const data = (await response.json()) as { + authorization_endpoint: string; + token_endpoint: string; + registration_endpoint: string; + issuer: string; + }; + + return { + registrationEndpoint: + data.registration_endpoint ?? `${data.issuer}/oauth/register`, + authorizationEndpoint: data.authorization_endpoint, + tokenEndpoint: data.token_endpoint, + issuer: data.issuer, + }; + } + + throw new Error("Failed to fetch OAuth server metadata"); +} + +async function registerClient( + registrationEndpoint: string, + redirectUri: string, +) { + const registrationResponse = await fetch(registrationEndpoint, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + client_name: "Reflag CLI", + token_endpoint_auth_method: "none", + grant_types: ["authorization_code"], + redirect_uris: [redirectUri], + }), + signal: AbortSignal.timeout(5000), + }); + + if (!registrationResponse.ok) { + throw new Error(`Could not register client with OAuth server`); + } + + const registrationData = (await registrationResponse.json()) as { + client_id: string; + }; + + return registrationData.client_id; +} + +async function exchangeCodeForToken( + tokenEndpoint: string, + clientId: string, + code: string, + codeVerifier: string, + redirectUri: string, +) { + const response = await fetch(tokenEndpoint, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + body: new URLSearchParams({ + grant_type: "authorization_code", + client_id: clientId, + code, + code_verifier: codeVerifier, + redirect_uri: redirectUri, + }), + signal: AbortSignal.timeout(5000), + }); + + if (!response.ok) { + let errorDescription: string | undefined; + + try { + const errorResponse = await response.json(); + errorDescription = errorResponse.error_description || errorResponse.error; + } catch { + // ignore + } + + return { error: errorDescription ?? "unknown error" }; + } + + const successResponse = (await response.json()) as { + access_token: string; + expires_in: number; + }; + + return { + accessToken: successResponse.access_token, + expiresAt: new Date(Date.now() + successResponse.expires_in * 1000), + }; +} + +function createChallenge() { + // PKCE code verifier and challenge + const codeVerifier = crypto.randomBytes(32).toString("base64url"); + const codeChallenge = crypto + .createHash("sha256") + .update(codeVerifier) + .digest("base64") + .replace(/=/g, "") + .replace(/\+/g, "-") + .replace(/\//g, "_"); + + const state = crypto.randomUUID(); + + return { codeVerifier, codeChallenge, state }; +} + +export async function waitForAccessToken(baseUrl: string, apiUrl: string) { + const { authorizationEndpoint, tokenEndpoint, registrationEndpoint } = + await getOAuthServerUrls(apiUrl); + + let resolve: (args: waitForAccessToken) => void; + let reject: (arg0: Error) => void; + + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + + const { codeVerifier, codeChallenge, state } = createChallenge(); + + const timeout = setTimeout(() => { + cleanupAndReject( + `authentication timed out after ${DEFAULT_AUTH_TIMEOUT / 1000} seconds`, + ); + }, DEFAULT_AUTH_TIMEOUT); + + function cleanupAndReject(message: string) { + cleanup(); + reject(new Error(`Could not authenticate: ${message}`)); + } + + function cleanup() { + clearTimeout(timeout); + server.close(); + server.closeAllConnections(); + } + + const server = http.createServer(); + + server.listen(); + + const address = server.address(); + if (address == null || typeof address !== "object") { + throw new Error("Could not start server"); + } + + const callbackPath = "/oauth_callback"; + const redirectUri = `http://localhost:${address.port}${callbackPath}`; + + const clientId = await registerClient(registrationEndpoint, redirectUri); + + const params = { + response_type: "code", + client_id: clientId, + redirect_uri: redirectUri, + state, + code_challenge: codeChallenge, + code_challenge_method: "S256", + }; + + const browserUrl = `${authorizationEndpoint}?${new URLSearchParams(params).toString()}`; + + server.on("request", async (req, res) => { + if (!clientId || !redirectUri) { + res.writeHead(500).end("Something went wrong"); + + cleanupAndReject("something went wrong"); + return; + } + + const url = new URL(req.url ?? "/", "http://127.0.0.1"); + + if (url.pathname !== callbackPath) { + res.writeHead(404).end("Invalid path"); + + cleanupAndReject("invalid path"); + return; + } + + const error = url.searchParams.get("error"); + if (error) { + res.writeHead(400).end("Could not authenticate"); + + const errorDescription = url.searchParams.get("error_description"); + cleanupAndReject(`${errorDescription || error} `); + return; + } + + const code = url.searchParams.get("code"); + if (!code) { + res.writeHead(400).end("Could not authenticate"); + + cleanupAndReject("no code provided"); + return; + } + + const response = await exchangeCodeForToken( + tokenEndpoint, + clientId, + code, + codeVerifier, + redirectUri, + ); + + if ("error" in response) { + res + .writeHead(302, { + location: errorUrl( + baseUrl, + "Could not authenticate: unable to fetch access token", + ), + }) + .end("Could not authenticate"); + + cleanupAndReject(JSON.stringify(response.error)); + return; + } + + res + .writeHead(302, { + location: successUrl(baseUrl), + }) + .end("Authentication successful"); + + cleanup(); + resolve(response); + }); + + console.log( + `Opened web browser to facilitate login: ${chalk.cyan(browserUrl)}`, + ); + + void open(browserUrl); + + return promise; +} + +export async function authRequest>( + url: string, + options?: RequestInit & { + params?: Record; + }, + retryCount = 0, +): Promise { + const { baseUrl, apiUrl } = configStore.getConfig(); + const { token, isApiKey } = authStore.getToken(baseUrl); + + if (!token) { + const accessToken = await waitForAccessToken(baseUrl, apiUrl); + + await authStore.setToken(baseUrl, accessToken.accessToken); + return authRequest(url, options); + } + + if (url.startsWith("/")) { + url = url.slice(1); + } + + const resolvedUrl = new URL(`${apiUrl}/${url}`); + + if (options?.params) { + Object.entries(options.params).forEach(([key, value]) => { + if (value !== null && value !== undefined) { + if (Array.isArray(value)) { + value.forEach((v) => resolvedUrl.searchParams.append(key, String(v))); + } else { + resolvedUrl.searchParams.set(key, String(value)); + } + } + }); + } + + let response: Response | undefined; + + try { + response = await fetch(resolvedUrl, { + ...options, + headers: { + ...options?.headers, + Authorization: `Bearer ${token}`, + [CLIENT_VERSION_HEADER_NAME]: CLIENT_VERSION_HEADER_VALUE( + configStore.getClientVersion() ?? "unknown", + ), + }, + }); + } catch (error: unknown) { + const message = + error && typeof error == "object" && "message" in error + ? error.message + : "unknown"; + + throw new Error(`Failed to connect to "${resolvedUrl}". Error: ${message}`); + } + + if (!response.ok) { + if (response.status === 401) { + if (isApiKey) { + throw new Error( + `The provided API key is not valid for "${resolvedUrl}".`, + ); + } + + await authStore.setToken(baseUrl, null); + + if (retryCount < maxRetryCount) { + return authRequest(url, options, retryCount + 1); + } + } + + const data = await response.json(); + throw new ResponseError(data); + } + + return response.json(); +} diff --git a/releases/cli-v1/utils/constants.ts b/releases/cli-v1/utils/constants.ts new file mode 100644 index 00000000..a8fadc22 --- /dev/null +++ b/releases/cli-v1/utils/constants.ts @@ -0,0 +1,22 @@ +import os from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +export const CLIENT_VERSION_HEADER_NAME = "reflag-sdk-version"; +export const CLIENT_VERSION_HEADER_VALUE = (version: string) => + `cli/${version}`; + +export const CONFIG_FILE_NAME = "reflag.config.json"; +export const AUTH_FILE = join(os.homedir(), ".reflag-auth"); +export const SCHEMA_URL = `https://unpkg.com/@reflag/cli@latest/schema.json`; + +export const DEFAULT_BASE_URL = "https://app.reflag.com"; +export const DEFAULT_API_URL = `${DEFAULT_BASE_URL}/api`; +export const DEFAULT_TYPES_OUTPUT = join("gen", "flags.d.ts"); + +export const DEFAULT_AUTH_TIMEOUT = 60000; // 60 seconds + +export const MODULE_ROOT = fileURLToPath(import.meta.url).substring( + 0, + fileURLToPath(import.meta.url).lastIndexOf("cli") + 3, +); diff --git a/releases/cli-v1/utils/errors.ts b/releases/cli-v1/utils/errors.ts new file mode 100644 index 00000000..64b04290 --- /dev/null +++ b/releases/cli-v1/utils/errors.ts @@ -0,0 +1,88 @@ +import { ExitPromptError } from "@inquirer/core"; +import { ErrorObject } from "ajv"; +import chalk from "chalk"; + +export class MissingAppIdError extends Error { + constructor() { + super( + "App ID is required. Please provide it with --appId or in the config file. Use `reflag apps list` to see available apps.", + ); + this.name = "MissingAppIdError"; + } +} + +export class MissingEnvIdError extends Error { + constructor() { + super("Environment ID is required."); + this.name = "MissingEnvIdError"; + } +} + +export class ConfigValidationError extends Error { + constructor(errors?: ErrorObject[] | null) { + const messages = errors + ?.map((e) => { + const path = e.instancePath || "config"; + const value = e.params?.allowedValues + ? `: ${e.params.allowedValues.join(", ")}` + : ""; + return `${path}: ${e.message}${value}`; + }) + .join("\n"); + super(messages); + this.name = "ConfigValidationError"; + } +} + +type ResponseErrorData = { + error?: { + message?: string; + code?: string; + }; + validationErrors?: { path: string[]; message: string }[]; +}; + +export class ResponseError extends Error { + public readonly data: ResponseErrorData; + + constructor(response: ResponseErrorData) { + super(response.error?.message ?? response.error?.code); + this.data = response; + this.name = "ResponseError"; + } +} + +export function handleError(error: unknown, tag: string): never { + tag = chalk.bold(`\n[${tag}] error:`); + + if (error instanceof ExitPromptError) { + process.exit(0); + } else if (error instanceof ResponseError) { + console.error( + chalk.red(tag, error.data.error?.message ?? error.data.error?.code), + ); + + if (error.data.validationErrors) { + console.table( + error.data.validationErrors.map( + ({ path, message }: { path: string[]; message: string }) => ({ + path: path.join("."), + error: message, + }), + ), + ); + } + } else if (error instanceof Error) { + console.error(chalk.red(tag, error.message)); + + if (error.cause) { + console.error(error.cause); + } + } else if (typeof error === "string") { + console.error(chalk.red(tag, error)); + } else { + console.error(chalk.red(tag ?? "An unknown error occurred:", error)); + } + + process.exit(1); +} diff --git a/releases/cli-v1/utils/file.ts b/releases/cli-v1/utils/file.ts new file mode 100644 index 00000000..cef068c4 --- /dev/null +++ b/releases/cli-v1/utils/file.ts @@ -0,0 +1,31 @@ +import { access, constants } from "node:fs/promises"; +import os from "node:os"; +import { join } from "node:path"; +/** + * Checks if a file exists at the given path. + * @param path The path to the file. + * @returns True if the file exists, false otherwise. + */ +export async function fileExists(path: string): Promise { + try { + await access(path, constants.F_OK); + return true; + } catch { + return false; + } +} + +// Helper to resolve home directory +export const resolvePath = (p: string) => { + return join( + ...p.split("/").map((part) => { + if (part === "~") { + return os.homedir(); + } else if (part === "@") { + return process.env.APPDATA ?? ""; + } else { + return part; + } + }), + ); +}; diff --git a/releases/cli-v1/utils/gen.ts b/releases/cli-v1/utils/gen.ts new file mode 100644 index 00000000..2aa3f06b --- /dev/null +++ b/releases/cli-v1/utils/gen.ts @@ -0,0 +1,159 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { dirname, isAbsolute, join } from "node:path"; + +import { camelCase, kebabCase, pascalCase, snakeCase } from "change-case"; + +import { Flag, RemoteConfig } from "../services/flags.js"; +import { JSONToType, quoteKey } from "./json.js"; + +export type GenFormat = "react" | "node"; + +// Keep in sync with Reflag main repo +export const KeyFormats = [ + "custom", + "pascalCase", + "camelCase", + "snakeCaseUpper", + "snakeCaseLower", + "kebabCaseUpper", + "kebabCaseLower", +] as const; + +export type KeyFormat = (typeof KeyFormats)[number]; + +type KeyFormatPattern = { + transform: (key: string) => string; + regex: RegExp; + message: string; +}; + +export const KeyFormatPatterns: Record = { + custom: { + transform: (key) => key?.trim(), + regex: /^[\p{L}\p{N}\p{P}\p{S}\p{Z}]+$/u, + message: + "Key must contain only letters, numbers, punctuation, symbols, or spaces.", + }, + pascalCase: { + transform: (key) => pascalCase(key), + regex: /^[\p{Lu}][\p{L}\p{N}]*$/u, + message: + "Key must start with uppercase letter and contain only letters and numbers.", + }, + camelCase: { + transform: (key) => camelCase(key), + regex: /^[\p{Ll}][\p{L}\p{N}]*$/u, + message: + "Key must start with lowercase letter and contain only letters and numbers.", + }, + snakeCaseUpper: { + transform: (key) => snakeCase(key).toUpperCase(), + regex: /^[\p{Lu}][\p{Lu}\p{N}]*(?:_[\p{Lu}\p{N}]+)*$/u, + message: "Key must be uppercase with words separated by underscores.", + }, + snakeCaseLower: { + transform: (key) => snakeCase(key).toLowerCase(), + regex: /^[\p{Ll}][\p{Ll}\p{N}]*(?:_[\p{Ll}\p{N}]+)*$/u, + message: "Key must be lowercase with words separated by underscores.", + }, + kebabCaseUpper: { + transform: (key) => kebabCase(key).toUpperCase(), + regex: /^[\p{Lu}][\p{Lu}\p{N}]*(?:-[\p{Lu}\p{N}]+)*$/u, + message: "Key must be uppercase with words separated by hyphens.", + }, + kebabCaseLower: { + transform: (key) => kebabCase(key).toLowerCase(), + regex: /^[\p{Ll}][\p{Ll}\p{N}]*(?:-[\p{Ll}\p{N}]+)*$/u, + message: "Key must be lowercase with words separated by hyphens.", + }, +}; + +export function indentLines( + str: string, + indent = 2, + lineBreak = "\n", + trim = false, +): string { + const indentStr = " ".repeat(indent); + return str + .split(lineBreak) + .map((line) => `${indentStr}${trim ? line.trim() : line}`) + .join(lineBreak); +} + +export function genFlagKey(input: string, format: KeyFormat): string { + return KeyFormatPatterns[format].transform(input); +} + +export function genRemoteConfig(remoteConfigs?: RemoteConfig[]) { + const variants = remoteConfigs?.[0]?.variants; + if (!variants?.length) return; + return JSONToType( + remoteConfigs![0].variants?.map(({ variant: { payload } }) => payload), + ); +} + +export function genTypes(flags: Flag[], format: GenFormat = "react") { + const configDefs = new Map(); + const aliasCounts = new Map(); + flags.forEach(({ key, name, remoteConfigs }) => { + const definition = genRemoteConfig(remoteConfigs); + + if (!definition) { + return; + } + + const identifier = `${pascalCase(name)}ConfigPayload`.replace( + /[^\p{ID_Continue}$]/gu, + "_", + ); + const base = /^[$_\p{ID_Start}]/u.test(identifier) + ? identifier + : `_${identifier}`; + const count = (aliasCounts.get(base) ?? 0) + 1; + aliasCounts.set(base, count); + // A numbered suffix cannot collide with another base ending in ConfigPayload. + const configName = count === 1 ? base : `${base}_${count}`; + configDefs.set(key, { name: configName, definition }); + }); + + return /* ts */ ` +// DO NOT EDIT THIS FILE. IT IS GENERATED BY THE REFLAG CLI AND WILL BE OVERWRITTEN. +// eslint-disable +// prettier-ignore +import "@reflag/${format}-sdk"; + +declare module "@reflag/${format}-sdk" { + export interface Flags { +${flags + .map(({ key }) => { + const config = configDefs.get(key); + return indentLines( + `${quoteKey(key)}: ${config?.definition ? `{ config: { payload: ${config.name} } }` : "boolean"};`, + 4, + ); + }) + .join("\n")} + } + +${Array.from(configDefs.values()) + .map(({ name, definition }) => { + return indentLines(`export type ${name} = ${definition}`); + }) + .join("\n\n")} +} +`.trim(); +} + +export async function writeTypesToFile( + types: string, + outPath: string, + projectPath: string, +) { + const fullPath = isAbsolute(outPath) ? outPath : join(projectPath, outPath); + + await mkdir(dirname(fullPath), { recursive: true }); + await writeFile(fullPath, types); + + return fullPath; +} diff --git a/releases/cli-v1/utils/json.ts b/releases/cli-v1/utils/json.ts new file mode 100644 index 00000000..b58f206e --- /dev/null +++ b/releases/cli-v1/utils/json.ts @@ -0,0 +1,203 @@ +export type JSONPrimitive = + | number + | string + | boolean + | null + | JSONPrimitive[] + | { [key: string]: JSONPrimitive }; + +export type PrimitiveAST = { kind: "primitive"; type: string }; +export type ArrayAST = { kind: "array"; elementType: TypeAST }; +export type ObjectAST = { + kind: "object"; + properties: { key: string; type: TypeAST; optional: boolean }[]; +}; +export type UnionAST = { kind: "union"; types: TypeAST[] }; + +// Type AST to represent TypeScript types +export type TypeAST = PrimitiveAST | ArrayAST | ObjectAST | UnionAST; + +// Convert JSON value to TypeAST +export function toTypeAST(value: JSONPrimitive): TypeAST { + if (value === null) return { kind: "primitive", type: "null" }; + + if (Array.isArray(value)) { + if (value.length === 0) { + return { + kind: "array", + elementType: { kind: "primitive", type: "any" }, + }; + } + + return { + kind: "array", + elementType: mergeTypeASTs(value.map(toTypeAST)), + }; + } + + if (typeof value === "object") { + return { + kind: "object", + properties: Object.entries(value).map(([key, val]) => ({ + key, + type: toTypeAST(val), + optional: false, + })), + }; + } + + return { kind: "primitive", type: typeof value }; +} + +// Merge multiple TypeASTs into one +export function mergeTypeASTs(types: TypeAST[]): TypeAST { + if (types.length === 0) return { kind: "primitive", type: "any" }; + if (types.length === 1) return types[0]; + + // Group ASTs by kind + const byKind = { + union: types.filter((t) => t.kind === "union"), + primitive: types.filter((t) => t.kind === "primitive"), + array: types.filter((t) => t.kind === "array"), + object: types.filter((t) => t.kind === "object"), + }; + + // Create a union for mixed kinds + const hasMixedKinds = + byKind.union.length > 0 || // If we have any unions, treat it as mixed kinds + (byKind.primitive.length > 0 && + (byKind.array.length > 0 || byKind.object.length > 0)) || + (byKind.array.length > 0 && byKind.object.length > 0); + + if (hasMixedKinds) { + // If there are existing unions, flatten them into the current union + if (byKind.union.length > 0) { + // Flatten existing unions and collect types by category + const flattenedTypes: TypeAST[] = []; + const objectsToMerge: ObjectAST[] = [...byKind.object]; + const arraysToMerge: ArrayAST[] = [...byKind.array]; + + // Add primitives directly + flattenedTypes.push(...byKind.primitive); + + // Process union types + for (const unionType of byKind.union) { + for (const type of unionType.types) { + if (type.kind === "object") { + objectsToMerge.push(type); + } else if (type.kind === "array") { + arraysToMerge.push(type); + } else { + flattenedTypes.push(type); + } + } + } + + // Merge objects and arrays if they exist + if (objectsToMerge.length > 0) { + flattenedTypes.push(mergeTypeASTs(objectsToMerge)); + } + + if (arraysToMerge.length > 0) { + flattenedTypes.push(mergeTypeASTs(arraysToMerge)); + } + + return { kind: "union", types: flattenedTypes }; + } + + return { kind: "union", types }; + } + + // Handle primitives + if (byKind.primitive.length === types.length) { + const uniqueTypes = [...new Set(byKind.primitive.map((p) => p.type))]; + return uniqueTypes.length === 1 + ? { kind: "primitive", type: uniqueTypes[0] } + : { + kind: "union", + types: uniqueTypes.map((type) => ({ kind: "primitive", type })), + }; + } + + // Merge arrays + if (byKind.array.length === types.length) { + return { + kind: "array", + elementType: mergeTypeASTs(byKind.array.map((a) => a.elementType)), + }; + } + + // Merge objects + if (byKind.object.length === types.length) { + // Get all unique property keys + const allKeys = [ + ...new Set( + byKind.object.flatMap((obj) => obj.properties.map((p) => p.key)), + ), + ]; + + // Merge properties with same keys + const mergedProperties = allKeys.map((key) => { + const props = byKind.object + .map((obj) => obj.properties.find((p) => p.key === key)) + .filter((obj) => !!obj); + + return { + key, + type: mergeTypeASTs(props.map((p) => p.type)), + optional: + props.length < byKind.object.length || props.some((p) => p.optional), + }; + }); + + return { kind: "object", properties: mergedProperties }; + } + + // Fallback + return { kind: "primitive", type: "any" }; +} + +// Stringify TypeAST to TypeScript type declaration +export function stringifyTypeAST(ast: TypeAST, nestLevel = 0): string { + const indent = " ".repeat(nestLevel * 2); + const nextIndent = " ".repeat((nestLevel + 1) * 2); + + switch (ast.kind) { + case "primitive": + return ast.type; + + case "array": + return `(${stringifyTypeAST(ast.elementType, nestLevel)})[]`; + + case "object": + if (ast.properties.length === 0) return "{}"; + + return `{\n${ast.properties + .map(({ key, optional, type }) => { + return `${nextIndent}${quoteKey(key)}${optional ? "?" : ""}: ${stringifyTypeAST( + type, + nestLevel + 1, + )}`; + }) + .join(",\n")}\n${indent}}`; + + case "union": + if (ast.types.length === 0) return "any"; + if (ast.types.length === 1) + return stringifyTypeAST(ast.types[0], nestLevel); + return ast.types + .map((type) => stringifyTypeAST(type, nestLevel)) + .join(" | "); + } +} + +export function quoteKey(key: string): string { + return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key); +} + +// Convert JSON array to TypeScript type +export function JSONToType(json: JSONPrimitive[]): string | null { + if (!json.length) return null; + + return stringifyTypeAST(mergeTypeASTs(json.map(toTypeAST))); +} diff --git a/releases/cli-v1/utils/options.ts b/releases/cli-v1/utils/options.ts new file mode 100644 index 00000000..9de61560 --- /dev/null +++ b/releases/cli-v1/utils/options.ts @@ -0,0 +1,80 @@ +import { Argument, Option } from "commander"; + +import { CONFIG_FILE_NAME } from "./constants.js"; + +// Define supported editors directly here or import from a central place if needed elsewhere +const SUPPORTED_EDITORS = ["cursor", "vscode"] as const; // Add more later: "claude", "cline", "windsurf" + +export const debugOption = new Option("--debug", "Enable debug mode."); + +export const baseUrlOption = new Option( + "--base-url [url]", + `Reflag service URL (useful if behind a proxy). Falls back to baseUrl value in ${CONFIG_FILE_NAME}.`, +); + +export const apiUrlOption = new Option( + "--api-url [url]", + `Reflag API URL (useful if behind a proxy). Falls back to apiUrl value in ${CONFIG_FILE_NAME} or baseUrl with /api appended.`, +); + +export const apiKeyOption = new Option( + "--api-key [key]", + `Reflag API key. Can be used in CI/CD pipelines where logging in is not possible.`, +); + +export const appIdOption = new Option( + "-a, --appId [appId]", + `Reflag App ID. Falls back to appId value in ${CONFIG_FILE_NAME}.`, +); + +export const orgIdOption = new Option( + "--org-id ", + `Restrict CLI app discovery and flag commands to an organization. Overrides orgId in ${CONFIG_FILE_NAME}.`, +); + +export const overwriteOption = new Option( + "--overwrite", + "Force initialization and overwrite existing configuration.", +); + +export const typesOutOption = new Option( + "-o, --out [path]", + `Single output path for generated flag types. Falls back to typesOutput value in ${CONFIG_FILE_NAME}.`, +); + +export const typesFormatOption = new Option( + "-f, --format [format]", + "Single output format for generated flag types", +).choices(["react", "node"]); + +export const flagNameArgument = new Argument( + "[name]", + "Flag's name. If not provided, you'll be prompted to enter one.", +); + +export const flagKeyOption = new Option( + "-k, --key [flag key]", + "Flag key. If not provided, a key is generated from the flag's name.", +); + +export const editorOption = new Option( + "-e, --editor [editor]", + "Specify the editor to configure for MCP.", +).choices(SUPPORTED_EDITORS); + +export const configScopeOption = new Option( + "-s, --scope [scope]", + "Specify whether to use local or global configuration.", +).choices(["local", "global"]); + +export const rulesFormatOption = new Option( + "-f, --format [format]", + "Format to copy rules in", +) + .choices(["cursor", "copilot"]) + .default("cursor"); + +export const yesOption = new Option( + "-y, --yes", + "Skip confirmation prompts and overwrite existing files without asking.", +); diff --git a/releases/cli-v1/utils/schemas.ts b/releases/cli-v1/utils/schemas.ts new file mode 100644 index 00000000..804d6e05 --- /dev/null +++ b/releases/cli-v1/utils/schemas.ts @@ -0,0 +1,65 @@ +import { z } from "zod"; + +export const sortTypeSchema = z + .enum(["flat", "hierarchical"]) + .describe("Type of sorting to apply"); + +export const booleanish = z.preprocess((value) => { + if (typeof value === "string") { + return value === "true" || value === "1"; + } + return Boolean(value); +}, z.boolean().describe("Boolean value that can be parsed from strings like 'true' or '1'")) as z.ZodType< + boolean, + boolean +>; + +export const PaginationQueryBaseSchema = ( + { + sortOrder = "asc", + pageIndex = 0, + pageSize = 20, + }: { + sortOrder?: "asc" | "desc"; + pageIndex?: number; + pageSize?: number; + } = { + sortOrder: "asc", + pageIndex: 0, + pageSize: 20, + }, +) => + z.object({ + sortOrder: z + .enum(["asc", "desc"]) + .default(sortOrder) + .describe("Sort direction (ascending or descending)"), + pageIndex: z.coerce + .number() + .int() + .nonnegative() + .default(pageIndex) + .describe("Zero-based page index"), + pageSize: z.coerce + .number() + .int() + .nonnegative() + .min(1) + .max(100) + .default(pageSize) + .describe("Number of items per page (1-100)"), + }); + +export const EnvironmentQuerySchema = z + .object({ + envId: z.string().min(1).describe("Environment identifier"), + }) + .strict(); + +export type EnvironmentQuery = z.infer; + +export const ExternalIdSchema = z + .string() + .nonempty() + .max(256) + .describe("External identifier, non-empty string up to 256 characters"); diff --git a/releases/cli-v1/utils/types.ts b/releases/cli-v1/utils/types.ts new file mode 100644 index 00000000..001050f7 --- /dev/null +++ b/releases/cli-v1/utils/types.ts @@ -0,0 +1,25 @@ +export const FunnelStepList = [ + "company", + "segment", + "tried", + "adopted", + "retained", +] as const; + +export type FunnelStep = (typeof FunnelStepList)[number]; + +export type FeedbackSource = "api" | "manual" | "prompt" | "sdk" | "widget"; + +export type SatisfactionScore = 0 | 1 | 2 | 3 | 4 | 5; + +export type ParamType = string | number | boolean | Date; + +export type PaginatedResponse = { + data: T[]; + metadata: Record; + totalCount: number; + pageIndex: number; + pageSize: number; + sortBy: string; + sortOrder: string; +}; diff --git a/releases/cli-v1/utils/urls.ts b/releases/cli-v1/utils/urls.ts new file mode 100644 index 00000000..5b85944e --- /dev/null +++ b/releases/cli-v1/utils/urls.ts @@ -0,0 +1,34 @@ +import chalk from "chalk"; +import slugMod from "slug"; + +import { DEFAULT_BASE_URL } from "./constants.js"; + +export type UrlArgs = { id: string; name: string }; + +export function slug({ id, name }: UrlArgs) { + return `${slugMod(name).substring(0, 15)}-${id}`; +} + +export function stripTrailingSlash(str: T): T { + return str?.endsWith("/") ? (str.slice(0, -1) as T) : str; +} + +export const successUrl = (baseUrl: string) => `${baseUrl}/cli-login/success`; +export const errorUrl = (baseUrl: string, error: string) => + `${baseUrl}/cli-login/error?error=${error}`; + +export const baseUrlSuffix = (baseUrl: string) => { + return baseUrl !== DEFAULT_BASE_URL ? ` at ${chalk.cyan(baseUrl)}` : ""; +}; + +export function environmentUrl(baseUrl: string, environment: UrlArgs): string { + return `${baseUrl}/envs/${slug(environment)}`; +} + +export function featureUrl( + baseUrl: string, + env: UrlArgs, + feature: UrlArgs, +): string { + return `${environmentUrl(baseUrl, env)}/features/${slug(feature)}`; +} diff --git a/releases/cli-v1/utils/version.ts b/releases/cli-v1/utils/version.ts new file mode 100644 index 00000000..0e9805d0 --- /dev/null +++ b/releases/cli-v1/utils/version.ts @@ -0,0 +1,64 @@ +import { readFile } from "fs/promises"; +import { join } from "path"; + +import { gt } from "semver"; + +import { MODULE_ROOT } from "./constants.js"; + +export async function current() { + try { + const packageJsonPath = join(MODULE_ROOT, "package.json"); + const packageJsonContent = await readFile(packageJsonPath, "utf-8"); + const packageInfo: { + version: string; + name: string; + } = JSON.parse(packageJsonContent); + + return { + version: packageInfo.version, + name: packageInfo.name, + }; + } catch (error) { + throw new Error( + `Failed to read current version: ${error instanceof Error ? error.message : "Unknown error"}`, + ); + } +} + +async function getLatestVersionFromNpm(packageName: string): Promise { + try { + const response = await fetch(`https://registry.npmjs.org/${packageName}`, { + signal: AbortSignal.timeout(5000), + }); + + if (!response.ok) { + throw new Error( + `Failed to fetch package info: ${response.status} ${response.statusText}`, + ); + } + + const data: { + "dist-tags": { + latest: string; + }; + } = await response.json(); + + return data["dist-tags"].latest; + } catch (error) { + throw new Error( + `Failed to fetch latest version from npm: ${error instanceof Error ? error.message : "Unknown error"}`, + ); + } +} + +export async function checkLatest() { + const { version: currentVersion, name: packageName } = await current(); + + const latestVersion = await getLatestVersionFromNpm(packageName); + const isNewerAvailable = gt(latestVersion, currentVersion); + return { + currentVersion, + latestVersion, + isNewerAvailable, + }; +} diff --git a/releases/cli-v1/vite.config.js b/releases/cli-v1/vite.config.js new file mode 100644 index 00000000..7b433523 --- /dev/null +++ b/releases/cli-v1/vite.config.js @@ -0,0 +1,14 @@ +import { defineConfig } from "vite"; + +export default defineConfig({ + test: { + environment: "node", + exclude: [ + "**/node_modules/**", + "**/dist/**", + "**/.{idea,git,cache,output,temp}/**", + "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*", + "**/example/**", + ], + }, +}); diff --git a/scripts/cli-v1-release.mjs b/scripts/cli-v1-release.mjs new file mode 100644 index 00000000..e361acec --- /dev/null +++ b/scripts/cli-v1-release.mjs @@ -0,0 +1,52 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const packageName = "@reflag/cli"; +const stableV1 = /^1\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +export function assertCliV1Release(manifest, requestedVersion, latest) { + if (manifest.name !== packageName || manifest.private) { + throw new Error(`Expected the public ${packageName} package`); + } + if ( + !stableV1.test(requestedVersion) || + manifest.version !== requestedVersion + ) { + throw new Error( + "The requested stable CLI v1 version must match the packaged version", + ); + } + + const current = typeof latest === "string" && stableV1.exec(latest); + if (!current) { + throw new Error( + `Refusing to update npm latest: '${latest}' is not a stable CLI v1 version`, + ); + } + const expected = `1.${current[1]}.${BigInt(current[2]) + 1n}`; + if (requestedVersion !== expected) { + throw new Error( + `Expected the next CLI v1 patch (${expected}), not ${requestedVersion}`, + ); + } +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + const manifest = JSON.parse(readFileSync(0, "utf8")); + const response = await fetch( + `https://registry.npmjs.org/-/package/${encodeURIComponent(packageName)}/dist-tags`, + { signal: AbortSignal.timeout(10_000) }, + ); + if (!response.ok) { + throw new Error(`Could not read npm dist-tags (HTTP ${response.status})`); + } + const { latest } = await response.json(); + assertCliV1Release(manifest, process.env.CLI_VERSION, latest); + console.log( + `Verified ${packageName} can move npm latest from ${latest} to ${manifest.version}`, + ); +} diff --git a/scripts/cli-v1-release.test.mjs b/scripts/cli-v1-release.test.mjs new file mode 100644 index 00000000..726913b9 --- /dev/null +++ b/scripts/cli-v1-release.test.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { assertCliV1Release } from "./cli-v1-release.mjs"; + +const cli = { name: "@reflag/cli", version: "1.0.5" }; + +test("accepts the next stable CLI v1 patch", () => { + assert.doesNotThrow(() => assertCliV1Release(cli, "1.0.5", "1.0.4")); +}); + +test("does not let a maintenance release move latest if it no longer points at a stable v1", () => { + for (const latest of [undefined, "0.9.9", "1.0.4-next.1", "2.0.0"]) { + assert.throws( + () => assertCliV1Release(cli, "1.0.5", latest), + /not a stable CLI v1/, + ); + } +}); + +test("rejects skipped patches, already released versions, and downgrades", () => { + for (const latest of ["1.0.3", "1.0.5", "1.0.6", "1.1.1"]) { + assert.throws( + () => assertCliV1Release(cli, "1.0.5", latest), + /Expected the next CLI v1 patch/, + ); + } +}); + +test("rejects unconfirmed, prerelease, and different package versions", () => { + for (const version of [undefined, "1.0.6", "1.0.5-next.0", "2.0.0"]) { + assert.throws( + () => assertCliV1Release(cli, version, "1.0.4"), + /must match the packaged version/, + ); + } +}); + +test("rejects building a different or private package", () => { + for (const manifest of [ + { ...cli, name: "@reflag/node-sdk" }, + { ...cli, private: true }, + ]) { + assert.throws( + () => assertCliV1Release(manifest, "1.0.5", "1.0.4"), + /Expected the public @reflag\/cli package/, + ); + } +}); diff --git a/scripts/release-channel.test.mjs b/scripts/release-channel.test.mjs index d517df24..4db3f496 100644 --- a/scripts/release-channel.test.mjs +++ b/scripts/release-channel.test.mjs @@ -53,16 +53,36 @@ test("the channel command produces only the GitHub Actions output", () => { assert.equal(output, `prerelease=${releaseChannel(state) === "next"}\n`); }); -test("all stable-doc publication steps require a stable release channel", () => { +test("CLI v1 releases use main and require an explicit publish request", () => { const workflow = read(".github/workflows/publish.yml"); + assert.doesNotMatch(workflow, /workflow_dispatch:/); + assert.match(workflow, /repository_dispatch:\s+types: \[release-cli-v1\]/); + assert.match( + workflow, + /release:\s+if: github\.event_name == 'push' && github\.ref == 'refs\/heads\/main'/, + ); + assert.match( + workflow, + /build-cli-v1:\s+if: github\.event_name == 'repository_dispatch' && github\.ref == 'refs\/heads\/main'/, + ); + assert.match( + workflow, + /publish-cli-v1:\s+needs: build-cli-v1\s+if: \$\{\{ toJSON\(github\.event\.client_payload\.publish\) == 'true' \}\}/, + ); +}); + +test("all stable-doc publication steps require a stable release channel", () => { + const workflow = read(".github/workflows/publish.yml").split( + "\n build-cli-v1:", + )[0]; assert.match( workflow, /id: release-channel\s+run: node scripts\/release-channel\.mjs >> "\$GITHUB_OUTPUT"/, ); const conditions = workflow .split("\n") - .map((line) => line.trim()) - .filter((line) => line.startsWith("if: ")); + .filter((line) => line.startsWith(" if: ")) + .map((line) => line.trim()); assert.equal(conditions.length, 7); for (const condition of conditions) { assert.ok(