Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(cli): split theme add/list into api/theme leaf shape (#4471)

Joey601520f4e737
diff --git a/.changeset/cli-theme-add-list-leaves.md b/.changeset/cli-theme-add-list-leaves.md
new file mode 100644
index 0000000000..2cf1c937d7
--- /dev/null
+++ b/.changeset/cli-theme-add-list-leaves.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[refactor] CLI: `theme add`/`list` are reorganized into the fractal `api/theme/` leaf shape — a shared `_adapter.mjs` (bundled-theme manifest reader + slug resolver) with thin `add/` (copy → `theme.add` receipt) and `list/` (`theme.list`) leaves over it, plus a `theme.mjs` barrel, mirroring the `theme build` extraction (#4462). `themeList()` is now exported from `@astryxdesign/cli/api` alongside `themeAdd`. Pure reorg: `theme list`/`add` `--json` envelopes and human output are byte-identical, with new direct-API tests for both leaves.
+@josephfarina
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index a3f52bb422..e3230cb24e 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -24,8 +24,7 @@ export {docs} from './docs/docs.mjs';
export {blog} from './blog/blog.mjs';
export {discover} from './discover/discover.mjs';
export {template} from './template/template.mjs';
-export {themeAdd, listThemes} from './theme/theme-add.mjs';
-export {themeBuild} from './theme/build/build.mjs';
+export {themeBuild, themeAdd, themeList, listThemes} from './theme/theme.mjs';
export {hook} from './hook/hook.mjs';
export {search} from './search/search.mjs';
export {build} from './build/build.mjs';
diff --git a/packages/cli/api/theme/_adapter.mjs b/packages/cli/api/theme/_adapter.mjs
new file mode 100644
index 0000000000..5a0974bc8c
--- /dev/null
+++ b/packages/cli/api/theme/_adapter.mjs
@@ -0,0 +1,63 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Shared data layer for the `theme` command's `add`/`list` leaves — reads
+ * the bundled-theme manifest (`templates/themes/manifest.json`, generated by
+ * scripts/generate-cli-themes.mjs) and resolves a theme by slug. Both leaves
+ * sit on this; neither reads the manifest itself.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {CLI_ROOT} from '../../utils/paths.mjs';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
+
+/** Directory holding the generated theme bundle. */
+export const THEMES_DIR = path.join(CLI_ROOT, 'templates', 'themes');
+/** The bundle manifest that lists every theme (+ its files). */
+export const MANIFEST_PATH = path.join(THEMES_DIR, 'manifest.json');
+
+/**
+ * A single bundled theme entry from `templates/themes/manifest.json`.
+ * @typedef {object} BundledTheme
+ * @property {string} slug
+ * @property {string} displayName
+ * @property {string} description
+ * @property {boolean} maintained
+ * @property {string} entry
+ * @property {string} exportName
+ * @property {string[]} files
+ */
+
+/**
+ * Parsed `themes` array from the bundle manifest (empty if not generated).
+ * @returns {BundledTheme[]}
+ */
+export function listThemes() {
+ if (!fs.existsSync(MANIFEST_PATH)) return [];
+ /** @type {{themes?: BundledTheme[]}} */
+ let manifest;
+ try {
+ manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf-8'));
+ } catch (err) {
+ throw new AstryxError(
+ `Theme bundle manifest is unreadable (${MANIFEST_PATH}): ${/** @type {any} */ (err).message}`,
+ undefined,
+ ERROR_CODES.ERR_NO_SOURCE,
+ );
+ }
+ return Array.isArray(manifest.themes) ? manifest.themes : [];
+}
+
+/**
+ * Resolve a bundled theme by slug (case-insensitive). `undefined` when the slug
+ * is empty or unknown.
+ * @param {string} [slug]
+ * @returns {BundledTheme | undefined}
+ */
+export function findTheme(slug) {
+ if (!slug) return undefined;
+ const lc = String(slug).toLowerCase();
+ return listThemes().find(t => t.slug.toLowerCase() === lc);
+}
diff --git a/packages/cli/api/theme/theme-add.mjs b/packages/cli/api/theme/add/add.mjs
similarity index 58%
rename from packages/cli/api/theme/theme-add.mjs
rename to packages/cli/api/theme/add/add.mjs
index 6cf833696a..e9ab0e690c 100644
--- a/packages/cli/api/theme/theme-add.mjs
+++ b/packages/cli/api/theme/add/add.mjs
@@ -1,38 +1,24 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Programmatic API for `astryx theme add` — copies a bundled theme's
- * source (`templates/themes/`, see scripts/generate-cli-themes.mjs) into the
- * consumer's project so they own it, without needing the theme package.
+ * @file `astryx theme add` leaf — copies a bundled theme's source
+ * (`templates/themes/<slug>/`) into the consumer's project so they own it,
+ * without needing the theme package. Which theme is resolved by ../_adapter.mjs;
+ * this leaf owns the copy I/O + path-safety and returns a `theme.add` receipt.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {CLI_ROOT} from '../../utils/paths.mjs';
-import {assertWithin, PathSafetyError} from '../../utils/path-safety.mjs';
-import {AstryxError} from '../error.mjs';
-import {ERROR_CODES} from '../../lib/error-codes.mjs';
-
-const THEMES_DIR = path.join(CLI_ROOT, 'templates', 'themes');
-const MANIFEST_PATH = path.join(THEMES_DIR, 'manifest.json');
+import {assertWithin, PathSafetyError} from '../../../utils/path-safety.mjs';
+import {AstryxError} from '../../error.mjs';
+import {ERROR_CODES} from '../../../lib/error-codes.mjs';
+import {THEMES_DIR, listThemes, findTheme} from '../_adapter.mjs';
// Stripped from scaffolded files so the consumer's copy doesn't carry our
// repo boilerplate (mirrors the docsite). Preserves a leading BOM/shebang.
const META_COPYRIGHT_HEADER_RE =
/^(\uFEFF?(?:#![^\r\n]*(?:\r?\n))?)\/\/ Copyright \(c\) Meta Platforms, Inc\. and affiliates\.\r?\n(?:\r?\n)*/;
-/**
- * A single bundled theme entry from `templates/themes/manifest.json`.
- * @typedef {object} BundledTheme
- * @property {string} slug
- * @property {string} displayName
- * @property {string} description
- * @property {boolean} maintained
- * @property {string} entry
- * @property {string} exportName
- * @property {string[]} files
- */
-
/**
* @param {string} source
* @returns {string}
@@ -41,36 +27,6 @@ function stripCopyrightHeader(source) {
return source.replace(META_COPYRIGHT_HEADER_RE, '$1');
}
-/**
- * Parsed `themes` array from the bundle manifest (empty if not generated).
- * @returns {BundledTheme[]}
- */
-export function listThemes() {
- if (!fs.existsSync(MANIFEST_PATH)) return [];
- /** @type {{themes?: BundledTheme[]}} */
- let manifest;
- try {
- manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf-8'));
- } catch (err) {
- throw new AstryxError(
- `Theme bundle manifest is unreadable (${MANIFEST_PATH}): ${/** @type {any} */ (err).message}`,
- undefined,
- ERROR_CODES.ERR_NO_SOURCE,
- );
- }
- return Array.isArray(manifest.themes) ? manifest.themes : [];
-}
-
-/**
- * @param {string} [slug]
- * @returns {BundledTheme | undefined}
- */
-function findTheme(slug) {
- if (!slug) return undefined;
- const lc = String(slug).toLowerCase();
- return listThemes().find(t => t.slug.toLowerCase() === lc);
-}
-
/**
* @param {string} slug
* @returns {string}
@@ -80,36 +36,24 @@ function defaultTargetDir(slug) {
}
/**
- * Resolve the scaffold plan for `theme add`. Returns the theme list when no
- * slug (or `list`); otherwise copies the theme's files into the destination
- * (defaults to `src/themes/<slug>/`).
+ * Copy a bundled theme's files into the consumer's project (defaults to
+ * `src/themes/<slug>/`). Writes are staged to temp files then renamed, rolling
+ * back partials on failure so a failed write never leaves a half-written theme.
+ * Throws AstryxError for an unknown slug, a target that escapes cwd, an existing
+ * file (without `overwrite`), a missing bundled file, or a write failure.
*
- * @param {string} [slug]
- * @param {{list?: boolean, targetPath?: string, overwrite?: boolean, cwd?: string}} [options]
- * @returns {Promise<{type: string, data: unknown}>}
+ * @param {string} slug
+ * @param {{targetPath?: string, overwrite?: boolean, cwd?: string}} [options]
+ * @returns {Promise<import('../../../types/theme').ThemeAddResponse>}
*/
export async function themeAdd(slug, options = {}) {
- const {list = false, targetPath, overwrite = false, cwd = process.cwd()} =
- options;
- const themes = listThemes();
-
- if (list || !slug) {
- return {
- type: 'theme.list',
- data: themes.map(t => ({
- slug: t.slug,
- displayName: t.displayName,
- description: t.description,
- maintained: t.maintained,
- })),
- };
- }
+ const {targetPath, overwrite = false, cwd = process.cwd()} = options;
const match = findTheme(slug);
if (!match) {
throw new AstryxError(
`Unknown theme "${slug}"`,
- themes.map(t => ({
+ listThemes().map(t => ({
name: t.slug,
reason: t.maintained ? 'maintained theme' : 'example theme',
})),
diff --git a/packages/cli/api/theme/add/add.test.mjs b/packages/cli/api/theme/add/add.test.mjs
new file mode 100644
index 0000000000..f35f731a62
--- /dev/null
+++ b/packages/cli/api/theme/add/add.test.mjs
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Direct-API tests for the `theme add` leaf. Copies real bundled themes
+ * into a tmp cwd and asserts the receipt + on-disk effects, plus the guard rails
+ * (unknown slug, no-overwrite, path traversal). Uses the maintained `neutral`
+ * theme so the fixture stays stable.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {themeAdd} from './add.mjs';
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('themeAdd (api/theme/add)', () => {
+ it('copies a theme into src/themes/<slug> and returns a theme.add receipt', async () => {
+ const result = await themeAdd('neutral', {cwd: tmpDir});
+ expect(result.type).toBe('theme.add');
+ expect(result.data.slug).toBe('neutral');
+ expect(result.data.outputDir).toBe(path.join('src', 'themes', 'neutral'));
+ expect(result.data.files.length).toBeGreaterThan(0);
+ for (const f of result.data.files) {
+ expect(
+ fs.existsSync(path.join(tmpDir, 'src', 'themes', 'neutral', f)),
+ ).toBe(true);
+ }
+ });
+
+ it('strips the Meta copyright header from copied files', async () => {
+ const result = await themeAdd('neutral', {cwd: tmpDir});
+ const first = path.join(tmpDir, result.data.outputDir, result.data.files[0]);
+ expect(fs.readFileSync(first, 'utf-8')).not.toMatch(
+ /Copyright \(c\) Meta Platforms/,
+ );
+ });
+
+ it('resolves the slug case-insensitively', async () => {
+ const result = await themeAdd('Neutral', {cwd: tmpDir});
+ expect(result.data.slug).toBe('neutral');
+ });
+
+ it('honors an explicit target path (within cwd)', async () => {
+ const result = await themeAdd('neutral', {
+ cwd: tmpDir,
+ targetPath: 'themes/mine',
+ });
+ expect(result.data.outputDir).toBe(path.join('themes', 'mine'));
+ expect(
+ fs.existsSync(path.join(tmpDir, 'themes', 'mine', result.data.files[0])),
+ ).toBe(true);
+ });
+
+ it('throws ERR_UNKNOWN_THEME for an unknown slug (with suggestions)', async () => {
+ await expect(themeAdd('does-not-exist', {cwd: tmpDir})).rejects.toMatchObject(
+ {code: 'ERR_UNKNOWN_THEME'},
+ );
+ });
+
+ it('refuses to overwrite existing files without overwrite', async () => {
+ await themeAdd('neutral', {cwd: tmpDir});
+ await expect(themeAdd('neutral', {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_FILE_EXISTS',
+ });
+ });
+
+ it('replaces files when overwrite is set', async () => {
+ await themeAdd('neutral', {cwd: tmpDir});
+ const result = await themeAdd('neutral', {cwd: tmpDir, overwrite: true});
+ expect(result.type).toBe('theme.add');
+ });
+
+ it('rejects a target path that escapes cwd', async () => {
+ await expect(
+ themeAdd('neutral', {cwd: tmpDir, targetPath: '../escape'}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ });
+});
diff --git a/packages/cli/api/theme/list/list.mjs b/packages/cli/api/theme/list/list.mjs
new file mode 100644
index 0000000000..9c7fa77a9a
--- /dev/null
+++ b/packages/cli/api/theme/list/list.mjs
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx theme list` leaf — projects the bundled-theme manifest into the
+ * `theme.list` envelope. Data source: ../_adapter.mjs (listThemes).
+ */
+
+import {listThemes} from '../_adapter.mjs';
+
+/**
+ * List the themes bundled with this CLI build (the ones `theme add` can
+ * scaffold). Pure projection of the manifest; no I/O beyond the adapter read.
+ * @returns {import('../../../types/theme').ThemeListResponse}
+ */
+export function themeList() {
+ return {
+ type: 'theme.list',
+ data: listThemes().map(t => ({
+ slug: t.slug,
+ displayName: t.displayName,
+ description: t.description,
+ maintained: t.maintained,
+ })),
+ };
+}
diff --git a/packages/cli/api/theme/list/list.test.mjs b/packages/cli/api/theme/list/list.test.mjs
new file mode 100644
index 0000000000..a108eefa2d
--- /dev/null
+++ b/packages/cli/api/theme/list/list.test.mjs
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Direct-API tests for the `theme list` leaf. Runs against the real
+ * bundled-theme manifest (committed under templates/themes/), so it doubles as a
+ * guard that the bundle stays readable and shaped as `theme.list` expects.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {themeList} from './list.mjs';
+
+describe('themeList (api/theme/list)', () => {
+ it('returns a theme.list envelope of the bundled themes', () => {
+ const result = themeList();
+ expect(result.type).toBe('theme.list');
+ expect(Array.isArray(result.data)).toBe(true);
+ expect(result.data.length).toBeGreaterThan(0);
+ for (const t of result.data) {
+ expect(typeof t.slug).toBe('string');
+ expect(typeof t.displayName).toBe('string');
+ expect(typeof t.description).toBe('string');
+ expect(typeof t.maintained).toBe('boolean');
+ }
+ });
+
+ it('surfaces the maintained neutral theme', () => {
+ const neutral = themeList().data.find(t => t.slug === 'neutral');
+ expect(neutral).toBeTruthy();
+ expect(neutral?.maintained).toBe(true);
+ });
+
+ it('projects only the list fields (no entry/exportName/files leak)', () => {
+ const [first] = themeList().data;
+ expect(first).toBeTruthy();
+ expect(Object.keys(first ?? {}).sort()).toEqual([
+ 'description',
+ 'displayName',
+ 'maintained',
+ 'slug',
+ ]);
+ });
+});
diff --git a/packages/cli/api/theme/theme.mjs b/packages/cli/api/theme/theme.mjs
new file mode 100644
index 0000000000..fde7301971
--- /dev/null
+++ b/packages/cli/api/theme/theme.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `theme` command barrel — re-exports the build/add/list leaves so the CLI
+ * (cli/commands/build-theme.mjs) and scripted callers import from one place.
+ * Each leaf is also importable directly (e.g. api/theme/add/add.mjs). `theme`
+ * has real subcommands, so there is no flag-dispatch here — the CLI calls the
+ * leaf it wants.
+ */
+
+export {themeBuild, importSpecifier} from './build/build.mjs';
+export {themeAdd} from './add/add.mjs';
+export {themeList} from './list/list.mjs';
+export {listThemes} from './_adapter.mjs';
diff --git a/packages/cli/cli/commands/build-theme.mjs b/packages/cli/cli/commands/build-theme.mjs
index b0901c4487..098b62172c 100644
--- a/packages/cli/cli/commands/build-theme.mjs
+++ b/packages/cli/cli/commands/build-theme.mjs
@@ -4,11 +4,11 @@
* @file theme command — Commander wiring for `astryx theme` (build/list/add).
*
* Thin CLI wrapper. The `build` compiler lives in the programmatic API
- * (../../api/theme/build/build.mjs); `list`/`add` delegate to
- * ../../api/theme/theme-add.mjs. This file only parses options, injects a
- * logger, renders human output, and maps AstryxError → cliError. Watch mode
- * (a human-interactive, long-running loop) stays here because it re-invokes
- * `theme build` as a child process.
+ * (../../api/theme/build/build.mjs); `list`/`add` delegate to the
+ * ../../api/theme/list/list.mjs and ../../api/theme/add/add.mjs leaves. This
+ * file only parses options, injects a logger, renders human output, and maps
+ * AstryxError → cliError. Watch mode (a human-interactive, long-running loop)
+ * stays here because it re-invokes `theme build` as a child process.
*
* Usage:
* astryx theme build ./src/themes/ocean.ts
@@ -23,7 +23,8 @@ import {getCliInvocation} from '../../utils/package-manager.mjs';
import {jsonOut, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
-import {themeAdd} from '../../api/theme/theme-add.mjs';
+import {themeAdd} from '../../api/theme/add/add.mjs';
+import {themeList} from '../../api/theme/list/list.mjs';
import {themeBuild, importSpecifier} from '../../api/theme/build/build.mjs';
/**
@@ -212,9 +213,7 @@ export function registerTheme(program) {
/** @type {import('../../types/theme').ThemeListResponse} */
let result;
try {
- result = /** @type {import('../../types/theme').ThemeListResponse} */ (
- await themeAdd(undefined, {list: true, cwd: process.cwd()})
- );
+ result = themeList();
} catch (e) {
const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
@@ -248,18 +247,19 @@ export function registerTheme(program) {
// The CLI is non-interactive: never prompt to confirm an overwrite.
// Existing files require an explicit --overwrite; otherwise themeAdd's
- // ERR_FILE_EXISTS guard rejects the write.
+ // ERR_FILE_EXISTS guard rejects the write. `--list` (or a bare `theme add`
+ // with no slug) is the list affordance — route it to the list leaf.
/** @type {import('../../types/theme').ThemeListResponse | import('../../types/theme').ThemeAddResponse} */
let result;
try {
- result = /** @type {import('../../types/theme').ThemeListResponse | import('../../types/theme').ThemeAddResponse} */ (
- await themeAdd(slug, {
- list: options.list,
- targetPath,
- overwrite: options.overwrite,
- cwd: process.cwd(),
- })
- );
+ result =
+ options.list || !slug
+ ? themeList()
+ : await themeAdd(slug, {
+ targetPath,
+ overwrite: options.overwrite,
+ cwd: process.cwd(),
+ });
} catch (e) {
const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
cliError(err.message, {suggestions: err.suggestions || [], code: err.code});