Skip to content

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

TypeScript

feat(cli): `astryx theme targets` — the themeable surface, enumerable in one command (#5115)

Cindy Zhang789ef5745cfd
diff --git a/.changeset/cli-theme-targets.md b/.changeset/cli-theme-targets.md
new file mode 100644
index 0000000000..e92d003b84
--- /dev/null
+++ b/.changeset/cli-theme-targets.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] CLI: `astryx theme targets` lists every component theming target — the `defineTheme` key, the class it paints, and the props and states it accepts — for one component or the whole system, with `--json` for lint and audit scripts. `astryx theme --help` now points at component overrides instead of reading as a build-tool menu. The listing and `theme build`'s override validation share one enumeration of the component docs, so neither can drift from the components.
+@cixzhang
diff --git a/packages/cli/README.md b/packages/cli/README.md
index fdde4d4583..7288d85ad6 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -419,6 +419,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |
| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |
| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not — `exists` when a file was already there, which is a success. |
+| `theme.targets` | The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index 9bf93e6dc2..cf01082983 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -25,7 +25,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 {themeBuild, themeAdd, themeList, listThemes} from './theme/theme.mjs';
+export {themeBuild, themeAdd, themeList, themeTargets, 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/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 1933163f95..a5070c4329 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -43,6 +43,10 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {AstryxError} from '../../error.mjs';
import {logger} from '../../logger.mjs';
import {loadComponentDoc} from '../../../foundation/discovery/component-loader.mjs';
+import {
+ collectThemingTargets,
+ targetsByKey,
+} from '../../../foundation/discovery/theming-targets.mjs';
import {
collectUnloadedFonts,
formatFontLoadingHelp,
@@ -882,6 +886,9 @@ ${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedThem
* Returns null when docs are unavailable so validation can skip unknown-key
* warnings rather than guessing from a second registry.
*
+ * Shares its enumeration with `theme targets`, so what a theme author can list
+ * is exactly what this validator accepts.
+ *
* @returns {Promise<Record<string, string[]> | null>}
*/
async function loadKnownComponents() {
@@ -889,44 +896,7 @@ async function loadKnownComponents() {
const coreSrc = coreRoot ? path.join(coreRoot, 'src') : null;
if (!coreSrc || !fs.existsSync(coreSrc)) return null;
- /** @type {Record<string, string[]>} */
- const targets = {};
-
- /** @param {string} dir */
- async function scan(dir) {
- const entries = fs.readdirSync(dir, {withFileTypes: true});
- for (const entry of entries) {
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
- await scan(full);
- continue;
- }
- if (!entry.name.endsWith('.doc.mjs')) continue;
-
- /** @type {any} */
- let doc;
- try {
- doc = await loadComponentDoc(full);
- } catch {
- continue;
- }
-
- for (const target of doc?.theming?.targets || []) {
- const className = target?.className;
- if (typeof className !== 'string') continue;
- const key = className.replace(/^astryx-/, '');
- if (!key) continue;
- const props = [target.visualProps, target.states]
- .filter(list => Array.isArray(list))
- .flat()
- .filter((/** @type {unknown} */ p) => typeof p === 'string');
- targets[key] = [...new Set([...(targets[key] || []), ...props])];
- }
- }
- }
-
- await scan(coreSrc);
+ const targets = targetsByKey(await collectThemingTargets(coreSrc));
return Object.keys(targets).length > 0 ? targets : null;
}
diff --git a/packages/cli/api/theme/targets/targets.mjs b/packages/cli/api/theme/targets/targets.mjs
new file mode 100644
index 0000000000..51bb1aaaec
--- /dev/null
+++ b/packages/cli/api/theme/targets/targets.mjs
@@ -0,0 +1,87 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx theme targets` leaf — the whole themeable surface, enumerated.
+ *
+ * @input a cwd (to resolve the project's `@astryxdesign/core`) and an optional
+ * component/key filter
+ * @output the `theme.targets` envelope: one row per theming target
+ * @position api/theme/targets — projection over
+ * foundation/discovery/theming-targets.mjs, the same component docs
+ * `astryx component <Name>` prints its Theming table from.
+ */
+
+import * as path from 'node:path';
+import {findCoreDir} from '../../../foundation/fs/paths.mjs';
+import {collectThemingTargets} from '../../../foundation/discovery/theming-targets.mjs';
+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
+import {AstryxError} from '../../error.mjs';
+
+/**
+ * Whether a target matches the caller's filter loosely: any target whose key,
+ * class, or component contains it — so `theme targets thumb` finds the switch
+ * thumb without knowing which component owns it.
+ * @param {import('../../../foundation/discovery/theming-targets.mjs').ThemingTarget} target
+ * @param {string} filter - already lowercased
+ * @returns {boolean}
+ */
+function matchesLoosely(target, filter) {
+ return (
+ target.key.toLowerCase().includes(filter) ||
+ target.className.toLowerCase().includes(filter) ||
+ target.component.toLowerCase().includes(filter)
+ );
+}
+
+/**
+ * List every component theming target — the `defineTheme` `components` keys,
+ * with the props and states each one accepts.
+ *
+ * A filter naming a component exactly wins over a substring search, so
+ * `theme targets Button` is Button's own set (what `astryx component Button`
+ * prints) rather than every key that happens to contain "button".
+ *
+ * @param {string} [filter] - component name, or a substring of a target key
+ * @param {{cwd?: string}} [ctx]
+ * @returns {Promise<import('../theme.type.mjs').ThemeTargetsResponse>}
+ */
+export async function themeTargets(filter, {cwd = process.cwd()} = {}) {
+ const coreDir = findCoreDir(cwd);
+ if (!coreDir) {
+ throw new AstryxError(
+ 'Could not find @astryxdesign/core package',
+ undefined,
+ ERROR_CODES.ERR_CORE_NOT_FOUND,
+ );
+ }
+
+ const all = await collectThemingTargets(path.join(coreDir, 'src'));
+ const needle = filter ? String(filter).toLowerCase() : null;
+ let targets = all;
+ if (needle) {
+ const named = all.filter(t => t.component.toLowerCase() === needle);
+ targets = named.length > 0 ? named : all.filter(t => matchesLoosely(t, needle));
+ }
+
+ if (needle && targets.length === 0) {
+ const near = [...new Set(all.map(t => t.component))]
+ .filter(name => name.toLowerCase().startsWith(needle.slice(0, 3)))
+ .sort()
+ .slice(0, 5)
+ .map(name => ({name, reason: 'has theming targets'}));
+ throw new AstryxError(
+ `No theming target matches "${filter}". Run \`theme targets\` with no filter for the whole list.`,
+ near.length > 0 ? near : undefined,
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+
+ return {
+ type: 'theme.targets',
+ data: {
+ filter: filter ?? null,
+ componentCount: new Set(targets.map(t => t.component)).size,
+ targets,
+ },
+ };
+}
diff --git a/packages/cli/api/theme/targets/targets.test.mjs b/packages/cli/api/theme/targets/targets.test.mjs
new file mode 100644
index 0000000000..8ba56fa434
--- /dev/null
+++ b/packages/cli/api/theme/targets/targets.test.mjs
@@ -0,0 +1,65 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Direct-API tests for the `theme targets` leaf. Runs against the real
+ * core docs, so it doubles as a guard that the themeable surface stays
+ * readable and shaped as `theme.targets` promises.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {themeTargets} from './targets.mjs';
+
+describe('themeTargets (api/theme/targets)', () => {
+ it('returns a theme.targets envelope covering the whole surface', async () => {
+ const result = await themeTargets();
+ expect(result.type).toBe('theme.targets');
+ expect(result.data.filter).toBeNull();
+ expect(result.data.targets.length).toBeGreaterThan(100);
+ expect(result.data.componentCount).toBeGreaterThan(50);
+ for (const t of result.data.targets) {
+ expect(Object.keys(t).sort()).toEqual([
+ 'className',
+ 'component',
+ 'key',
+ 'props',
+ 'states',
+ ]);
+ }
+ }, 60_000);
+
+ it('scopes to one component by name', async () => {
+ const {data} = await themeTargets('Switch');
+ expect(data.filter).toBe('Switch');
+ expect(data.componentCount).toBe(1);
+ expect(data.targets.map(t => t.key)).toEqual([
+ 'switch',
+ 'switch-field',
+ 'switch-thumb',
+ ]);
+ }, 60_000);
+
+ // Half the system's keys contain "button" (chat-send-button, toggle-button,
+ // …). A component name has to mean the component, or `theme targets Button`
+ // answers a different question than `component Button` and the two views
+ // look like they disagree.
+ it('prefers an exact component name over a substring match', async () => {
+ const {data} = await themeTargets('Button');
+ expect(data.targets.map(t => t.key)).toEqual(['button']);
+ }, 60_000);
+
+ // This command answers "which theme slot paints the switch thumb?" — a
+ // question you can only ask by the part, not the component, until you
+ // already know which component owns it.
+ it('searches keys by substring, across components', async () => {
+ const {data} = await themeTargets('thumb');
+ expect(data.componentCount).toBeGreaterThan(1);
+ expect(data.targets.map(t => t.key)).toContain('switch-thumb');
+ for (const t of data.targets) expect(t.key).toContain('thumb');
+ }, 60_000);
+
+ it('rejects a filter that matches nothing, with components to try', async () => {
+ await expect(themeTargets('nosuchthing')).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_COMPONENT',
+ });
+ }, 60_000);
+});
diff --git a/packages/cli/api/theme/theme.mjs b/packages/cli/api/theme/theme.mjs
index 5fad0627a2..88c5fa0d35 100644
--- a/packages/cli/api/theme/theme.mjs
+++ b/packages/cli/api/theme/theme.mjs
@@ -1,7 +1,8 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file `theme` command barrel — re-exports the build/add/list leaves so the CLI
+ * @file `theme` command barrel — re-exports the build/add/list/template/targets
+ * 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
@@ -11,5 +12,6 @@
export {themeBuild, importSpecifier} from './build/build.mjs';
export {themeAdd} from './add/add.mjs';
export {themeTemplate} from './template/template.mjs';
+export {themeTargets} from './targets/targets.mjs';
export {themeList} from './list/list.mjs';
export {listThemes} from './_adapter.mjs';
diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjs
index 438e0c3b95..258412cbd3 100644
--- a/packages/cli/api/theme/theme.type.mjs
+++ b/packages/cli/api/theme/theme.type.mjs
@@ -14,9 +14,10 @@
* xds --json theme list -> theme.list
* xds --json theme add <slug> -> theme.add
* xds --json theme template -> theme.template
+ * xds --json theme targets [filter] -> theme.targets
* (file not found / parse error) -> CLIError
*
- * @position api — colocated typedefs for api/theme/{theme,build,add,list,template,_adapter}
+ * @position api — colocated typedefs for api/theme/{theme,build,add,list,template,targets,_adapter}
*/
/**
@@ -78,6 +79,25 @@
* @property {{path: string, written: boolean, reason: 'exists' | null}} data
*/
+/**
+ * One themeable target: the `defineTheme` `components` key, the class it
+ * renders as, the component whose doc declares it, and the props and states
+ * that are legal override keys under it.
+ * @typedef {object} ThemeTargetEntry
+ * @property {string} key
+ * @property {string} className
+ * @property {string} component
+ * @property {string[]} props
+ * @property {string[]} states
+ */
+
+/**
+ * xds --json theme targets [filter]
+ * @typedef {object} ThemeTargetsResponse
+ * @property {'theme.targets'} type
+ * @property {{filter: string | null, componentCount: number, targets: ThemeTargetEntry[]}} data
+ */
+
// Make this a module so the @typedefs above are importable as types via
// `import('./theme.type.mjs').ThemeBuildResponse` (and re-exportable from a .d.ts).
export {};
diff --git a/packages/cli/api/theme/themeTargets.doc.mjs b/packages/cli/api/theme/themeTargets.doc.mjs
new file mode 100644
index 0000000000..e7485d489a
--- /dev/null
+++ b/packages/cli/api/theme/themeTargets.doc.mjs
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `themeTargets()` / `astryx theme targets`. Colocated
+ * with the API function it documents; the response-shape source of truth stays
+ * in `theme.type.mjs`.
+ * @position packages/cli/api/theme — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'themeTargets',
+ displayName: 'themeTargets()',
+ summary: 'List every component theming target a theme can override.',
+ description:
+ 'Enumerates the whole themeable surface: each `defineTheme` components key, the stable ' +
+ 'class it paints, the component that declares it, and the props and states that are legal ' +
+ 'override keys under it. Same source as the Theming table `astryx component <Name>` prints ' +
+ '— the component docs — so the list cannot drift from the components, and `theme build` ' +
+ 'validates overrides against this exact set. A filter naming a component gives that ' +
+ 'component\u2019s set; anything else is a substring search over the keys.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'themeTargets(filter?: string, ctx?: {cwd?: string}): Promise<ThemeTargetsResponse>',
+ keywords: ['theme', 'targets', 'defineTheme', 'components', 'override', 'class', 'states', 'audit'],
+ params: [
+ {
+ name: 'filter',
+ type: 'string',
+ description:
+ 'A component name (exact, case-insensitive) or a substring of a target key. Omit for the whole surface.',
+ },
+ {
+ name: 'ctx.cwd',
+ type: 'string',
+ description: 'Directory the project’s @astryxdesign/core is resolved from.',
+ },
+ ],
+ returns: [
+ {
+ type: 'theme.targets',
+ description:
+ 'The echoed filter, how many components are represented, and the targets: each {key, className, component, props, states}.',
+ },
+ ],
+ throws: [
+ {code: 'ERR_CORE_NOT_FOUND', when: '@astryxdesign/core cannot be resolved from cwd'},
+ {code: 'ERR_UNKNOWN_COMPONENT', when: 'a filter matches no target'},
+ ],
+ examples: [
+ {label: 'The whole themeable surface', code: 'await themeTargets();'},
+ {label: "One component's targets", code: "await themeTargets('Switch');"},
+ ],
+ command: 'theme targets',
+ related: ['themeBuild', 'themeTemplate', 'component'],
+};
diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjs
index 91367e3b6f..7a2f83a0c1 100644
--- a/packages/cli/assets/docs/theme.doc.dense.mjs
+++ b/packages/cli/assets/docs/theme.doc.dense.mjs
@@ -10,7 +10,7 @@ export const docsDense = {
{ section: 'Theme Props', title: 'Props', content: [null] },
{ section: 'Creating a Custom Theme', title: 'Custom Theme', content: [{ type: 'prose', text: '`theme list` + `theme add <slug>` to start from a shipped theme, or defineTheme from scratch. only override tokens that differ.' }, null, { type: 'prose', text: '`astryx theme template` writes theme.template.ts: every defineTheme field + token families + override syntax, annotated, with the CLI command that prints each reference.' }] },
{ section: 'defineTheme', title: 'defineTheme', content: [{ type: 'prose', text: 'scale configs (color, typography, radius, motion) + explicit token overrides + component overrides. color derives full palette from accent via HCT; accent = hex or [light, dark] tuple (per-scheme palettes). tokens overrides win token-by-token; --color-on-accent stays baked from color.accent, so prefer a tuple accent over overriding --color-accent.' }, null, null] },
- { section: 'Component Style Overrides', title: 'Component Overrides', content: [{ type: 'prose', text: 'components field uses semantic component keys + style keys (base, variant:value, stateName), not raw selectors. for external CSS, prefer data-* selectors from `astryx docs styling`. write standard CSS (borderRadius, padding) — pipeline expands to internal vars. public vars (--button-focus-offset etc) set directly. private vars (--_*) cannot be set — use CSS properties. run `astryx component <Name>` for details.' }, null, null, null, null] },
+ { section: 'Component Style Overrides', title: 'Component Overrides', content: [{ type: 'prose', text: 'components field uses semantic component keys + style keys (base, variant:value, stateName), not raw selectors. for external CSS, prefer data-* selectors from `astryx docs styling`. write standard CSS (borderRadius, padding) — pipeline expands to internal vars. public vars (--button-focus-offset etc) set directly. private vars (--_*) cannot be set — use CSS properties. run `astryx theme targets [Name]` to enumerate every themeable key (--json for lint), `astryx component <Name>` for one component.' }, null, null, null, null] },
{ section: 'Custom Variants', title: 'Custom Variants', content: [{ type: 'prose', text: 'any unknown prop:value in components becomes a new variant. astryx theme build generates TS augmentations. works on any extensible prop axis (variant, status, etc).' }, null, null, null, null] },
{ section: 'Building Themes for Production', title: 'Build for Production', content: [{ type: 'prose', text: 'astryx theme build compiles defineTheme to static CSS. outputs .css + .js (__built:true) + .d.ts.' }, null, null, null, null] },
{ section: 'Runtime vs Built Themes', title: 'Runtime vs Built', content: [{ type: 'prose', text: 'runtime: useInsertionEffect injects styles client-side. built: static CSS on first paint. USE /built + theme.css FOR SSR.' }, null, null, null] },
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index b4d8c0bf36..ccf8a368e2 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -300,7 +300,7 @@ const brandTheme = defineTheme({
},
{
type: 'prose',
- text: 'Run `astryx component <Name>` to see a component\'s theming targets, public CSS variables, and which standard CSS properties are supported.',
+ text: 'Run `astryx theme targets` for every themeable key in the system (`astryx theme targets <Name>` to scope it, `--json` to lint a theme against it), and `astryx component <Name>` for one component\'s theming targets, public CSS variables, and which standard CSS properties are supported.',
},
{
type: 'list',
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index 5f48247991..9ab69dc068 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -38,6 +38,7 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {themeAdd} from '../../../api/theme/add/add.mjs';
import {themeTemplate} from '../../../api/theme/template/template.mjs';
import {themeList} from '../../../api/theme/list/list.mjs';
+import {themeTargets} from '../../../api/theme/targets/targets.mjs';
import {themeBuild, importSpecifier} from '../../../api/theme/build/build.mjs';
import {defineCommand} from '../lib/define-command.mjs';
import {doc as themeGroup} from './theme.doc.mjs';
@@ -45,10 +46,12 @@ import {doc as themeBuildCommand} from './theme-build.doc.mjs';
import {doc as themeListCommand} from './theme-list.doc.mjs';
import {doc as themeAddCommand} from './theme-add.doc.mjs';
import {doc as themeTemplateCommand} from './theme-template.doc.mjs';
+import {doc as themeTargetsCommand} from './theme-targets.doc.mjs';
import {doc as themeBuildFn} from '../../../api/theme/themeBuild.doc.mjs';
import {doc as themeListFn} from '../../../api/theme/themeList.doc.mjs';
import {doc as themeAddFn} from '../../../api/theme/themeAdd.doc.mjs';
import {doc as themeTemplateFn} from '../../../api/theme/themeTemplate.doc.mjs';
+import {doc as themeTargetsFn} from '../../../api/theme/themeTargets.doc.mjs';
/**
* Path to this CLI's real entry (clients/cli/bin/astryx.mjs), resolved from
@@ -194,6 +197,36 @@ function printThemeList(themes) {
);
}
+/**
+ * Render the targets as one greppable line each, under an aligned header. A
+ * `records()` block would be five lines per target — over a thousand for the
+ * full surface, which is the view this command exists to make readable.
+ * @param {import('../../../api/theme/theme.type.mjs').ThemeTargetEntry[]} targets
+ * @returns {string}
+ */
+function formatTargetsTable(targets) {
+ const rows = targets.map(t => ({
+ key: t.key,
+ component: t.component,
+ props: t.props.join(', ') || '-',
+ states: t.states.join(', ') || '-',
+ }));
+ const head = {key: 'key', component: 'component', props: 'props', states: 'states'};
+ const width = (/** @type {'key'|'component'|'props'} */ field) =>
+ [head, ...rows].reduce((max, r) => Math.max(max, r[field].length), 0);
+ const w = {key: width('key'), component: width('component'), props: width('props')};
+ const line = (/** @type {typeof head} */ r) =>
+ [
+ r.key.padEnd(w.key),
+ r.component.padEnd(w.component),
+ r.props.padEnd(w.props),
+ r.states,
+ ]
+ .join(' ')
+ .trimEnd();
+ return [line(head), ...rows.map(line)].join('\n');
+}
+
/**
* @param {import('commander').Command} program
*/
@@ -225,6 +258,18 @@ export function registerTheme(program) {
},
});
+ // Theming questions are asked at `theme`, but per-component overrides live
+ // under `component`. Without this pointer the group reads as a build-tool
+ // menu, and the component targets are unreachable from the noun the user
+ // started at.
+ theme.addHelpText(
+ 'after',
+ `\nComponent style overrides:\n` +
+ ` ${getCliInvocation()} theme targets Every themeable class, with its props and states\n` +
+ ` ${getCliInvocation()} component <Name> One component's theming table\n` +
+ ` ${getCliInvocation()} docs theme How component overrides work\n`,
+ );
+
defineCommand(theme, themeBuildCommand, {
fn: themeBuildFn,
action: async (
@@ -502,4 +547,44 @@ export function registerTheme(program) {
);
},
});
+
+ defineCommand(theme, themeTargetsCommand, {
+ fn: themeTargetsFn,
+ action: async (/** @type {string | undefined} */ filter) => {
+ const json = program.opts().json || false;
+
+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeTargetsResponse} */
+ let result;
+ try {
+ result = await themeTargets(filter, {cwd: process.cwd()});
+ } catch (e) {
+ const err =
+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
+ cliError(err.message, {
+ suggestions: err.suggestions || [],
+ code: err.code,
+ });
+ return;
+ }
+
+ if (json) return jsonOut(result);
+
+ const run = getCliInvocation();
+ const {targets, componentCount} = result.data;
+ emit(
+ section(
+ 'Theming targets',
+ `${targets.length} across ${componentCount} component${componentCount === 1 ? '' : 's'}`,
+ ),
+ text(formatTargetsTable(targets)),
+ text(
+ [
+ `Each key goes under \`components\` in defineTheme; it paints \`.astryx-<key>\`.`,
+ `Props take a value (\`variant:secondary\`); states are written bare (\`checked\`).`,
+ `One component in full: ${run} component <Name>`,
+ ].join('\n'),
+ ),
+ );
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/theme-targets.behavior.test.mjs b/packages/cli/clients/cli/commands/theme-targets.behavior.test.mjs
new file mode 100644
index 0000000000..810994839c
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-targets.behavior.test.mjs
@@ -0,0 +1,64 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CLI behavior for `astryx theme targets`.
+ *
+ * The API leaf is covered by api/theme/targets/targets.test.mjs; what is only
+ * reachable here is the terminal binding — the table a human reads, the JSON
+ * envelope a lint script reads, and the route into component overrides from
+ * `theme --help`, which is where the question gets asked.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+describe('astryx theme targets', () => {
+ it('prints one greppable line per target, with props and states', async () => {
+ const {status, stdout} = await runCli(['theme', 'targets', 'Switch']);
+
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^switch\s+Switch\s+size\s+checked, disabled$/m);
+ expect(stdout).toMatch(/^switch-thumb\s+Switch\s+size\s+checked$/m);
+ expect(stdout).toMatch(/3 across 1 component/);
+ });
+
+ it('lists the whole surface when unfiltered', async () => {
+ const {status, stdout} = await runCli(['theme', 'targets']);
+
+ expect(status).toBe(0);
+ const rows = stdout.split('\n').filter(l => /^[a-z][a-z0-9-]*\s{2,}/.test(l));
+ expect(rows.length).toBeGreaterThan(100);
+ expect(stdout).toMatch(/^button\s/m);
+ expect(stdout).toMatch(/^switch-thumb\s/m);
+ }, 30_000);
+
+ it('returns a theme.targets envelope under --json', async () => {
+ const {status, stdout} = await runCli(['--json', 'theme', 'targets', 'Switch']);
+
+ expect(status).toBe(0);
+ const payload = JSON.parse(stdout);
+ expect(payload.type).toBe('theme.targets');
+ expect(payload.data.targets).toContainEqual({
+ key: 'switch-thumb',
+ className: 'astryx-switch-thumb',
+ component: 'Switch',
+ props: ['size'],
+ states: ['checked'],
+ });
+ });
+
+ it('fails a filter that matches nothing', async () => {
+ const {status, stderr} = await runCli(['theme', 'targets', 'nosuchthing']);
+
+ expect(status).toBe(1);
+ expect(stderr).toMatch(/No theming target matches "nosuchthing"/);
+ });
+
+ it('routes a theming question from `theme --help` to component overrides', async () => {
+ const {stdout} = await runCli(['theme', '--help']);
+
+ expect(stdout).toMatch(/Component style overrides:/);
+ expect(stdout).toMatch(/theme targets/);
+ expect(stdout).toMatch(/component <Name>/);
+ });
+});
diff --git a/packages/cli/clients/cli/commands/theme-targets.doc.mjs b/packages/cli/clients/cli/commands/theme-targets.doc.mjs
new file mode 100644
index 0000000000..8b25e7c313
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-targets.doc.mjs
@@ -0,0 +1,38 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx theme targets`. The terminal binding of the
+ * `themeTargets()` function (referenced via `fn`); its args map to that
+ * function's params so a converter can build Commander config + --help from one
+ * source of truth.
+ * @position packages/cli/clients/cli/commands — command documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const doc = {
+ type: 'command',
+ name: 'theme targets',
+ displayName: 'astryx theme targets',
+ namespace: 'cli',
+ summary: 'List the component theming targets a theme can override',
+ description:
+ 'Prints every `defineTheme` components key across the system: the stable class it paints, ' +
+ 'the component that declares it, and the props and states that are legal override keys ' +
+ 'under it. This is the whole themeable surface in one command — what auditing a theme, or ' +
+ 'answering "which key paints this pixel?", used to need one `astryx component <Name>` per ' +
+ 'component to assemble. Pass a component name to scope it; pass any substring to search ' +
+ 'keys. `--json` for a list a repo can lint its own theme against.',
+ fn: 'themeTargets',
+ args: [{name: 'filter', param: 'filter', required: false}],
+ examples: [
+ {label: 'The whole themeable surface', cli: 'astryx theme targets'},
+ {label: "One component's targets", cli: 'astryx theme targets Switch'},
+ {label: 'Search keys', cli: 'astryx theme targets thumb'},
+ {label: 'For a lint or an audit script', cli: 'astryx --json theme targets'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {code: 1, when: 'a filter matches no target, or core cannot be resolved'},
+ ],
+ related: ['component', 'theme build', 'theme template'],
+};
diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjs
index a92a933fc2..e72c1c4561 100644
--- a/packages/cli/clients/cli/commands/theme.doc.mjs
+++ b/packages/cli/clients/cli/commands/theme.doc.mjs
@@ -17,11 +17,13 @@ export const doc = {
description:
'The theme command group. Running astryx theme with no subcommand prints the ' +
'subcommand list; the work happens in the subcommands: compile a theme (build), ' +
- 'scaffold one into your project (add), start a custom one from the annotated template (template), or list the bundled themes (list).',
- subcommands: ['build', 'add', 'list', 'template'],
+ 'scaffold one into your project (add), start a custom one from the annotated template (template), ' +
+ 'list the bundled themes (list), or list the component theming targets a theme can override (targets).',
+ subcommands: ['build', 'add', 'list', 'template', 'targets'],
examples: [
{label: 'List bundled themes', cli: 'astryx theme list'},
{label: 'Scaffold a theme', cli: 'astryx theme add matcha'},
+ {label: 'See what a theme can override', cli: 'astryx theme targets'},
],
exitCodes: [
{code: 0, when: 'success (help shown, or a subcommand succeeded)'},
diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjs
index bb054bb0a4..fa00fe3b87 100644
--- a/packages/cli/clients/cli/index.mjs
+++ b/packages/cli/clients/cli/index.mjs
@@ -70,6 +70,7 @@ export const JSON_SUPPORTED = new Set([
'theme list',
'theme add',
'theme template',
+ 'theme targets',
'upgrade',
'manifest',
'doctor',
diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjs
index 3962d7ed79..25a247fe62 100644
--- a/packages/cli/clients/cli/lib/manifest.mjs
+++ b/packages/cli/clients/cli/lib/manifest.mjs
@@ -77,6 +77,7 @@ export const RESPONSE_TYPES = {
'theme list': ['theme.list'],
'theme add': ['theme.list', 'theme.add'],
'theme template': ['theme.template'],
+ 'theme targets': ['theme.targets'],
upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],
manifest: ['manifest'],
doctor: ['doctor'],
@@ -116,6 +117,7 @@ const EXAMPLES = {
'astryx theme add matcha ./src/themes/matcha',
],
'theme template': ['astryx theme template', 'astryx theme template --json'],
+ 'theme targets': ['astryx theme targets Switch', 'astryx --json theme targets'],
upgrade: ['astryx upgrade --json'],
manifest: ['astryx manifest --json', 'astryx --json'],
doctor: ['astryx doctor', 'astryx doctor --json'],
diff --git a/packages/cli/foundation/discovery/theming-targets.mjs b/packages/cli/foundation/discovery/theming-targets.mjs
new file mode 100644
index 0000000000..3434e4d76c
--- /dev/null
+++ b/packages/cli/foundation/discovery/theming-targets.mjs
@@ -0,0 +1,135 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The one enumeration of component theming targets.
+ *
+ * @input a core `src` directory
+ * @output every `theming.targets` entry authored in a component `.doc.mjs`,
+ * flattened into the `defineTheme` component key a theme author writes
+ * @position packages/cli/foundation/discovery — shared by `theme targets` (the
+ * listing) and `theme build` (override validation). Both read the
+ * component docs, which are the source of truth `astryx component
+ * <Name>` prints; nothing here is a second registry, so the list a
+ * theme author can enumerate and the set the compiler accepts cannot
+ * drift from the components or from each other.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {loadComponentDoc} from './component-loader.mjs';
+
+const SKIP_DIRS = new Set(['node_modules', '__tests__']);
+
+/**
+ * One theming target, as a theme author has to write it.
+ * @typedef {object} ThemingTarget
+ * @property {string} key - the `defineTheme` `components` key (class minus the `astryx-` prefix)
+ * @property {string} className - the stable class the component renders
+ * @property {string} component - the component whose doc declares it
+ * @property {string[]} props - visual props the target reflects (`variant:value` keys)
+ * @property {string[]} states - runtime states the target reflects (bare-name keys)
+ */
+
+/**
+ * Strip the namespace prefix to get the `defineTheme` key for a class name.
+ *
+ * Keep the `astryx-` literal in sync with packages/core/src/naming.ts
+ * (NAMESPACE / classPrefix), the same way component-format.mjs does.
+ * <!-- SYNC: packages/core/src/naming.ts (namespace prefix source of truth) -->
+ * @param {string} className
+ * @returns {string}
+ */
+function targetKey(className) {
+ return className.replace(/^astryx-/, '');
+}
+
+/**
+ * Every theming target declared under a core `src` directory, sorted by key
+ * then component. A key can appear more than once: a shared sub-element (the
+ * radio indicator, say) is documented by every component that renders it.
+ *
+ * Unreadable docs are skipped rather than fatal — a single malformed doc must
+ * not take out theme validation or the listing.
+ *
+ * @param {string} coreSrc - absolute path to `<core>/src`
+ * @returns {Promise<ThemingTarget[]>}
+ */
+export async function collectThemingTargets(coreSrc) {
+ if (!coreSrc || !fs.existsSync(coreSrc)) return [];
+
+ /** @type {ThemingTarget[]} */
+ const targets = [];
+
+ /** @param {string} dir */
+ async function scan(dir) {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (SKIP_DIRS.has(entry.name)) continue;
+ await scan(full);
+ continue;
+ }
+ if (!entry.name.endsWith('.doc.mjs')) continue;
+
+ /** @type {any} */
+ let doc;
+ try {
+ doc = await loadComponentDoc(full);
+ } catch {
+ continue;
+ }
+
+ const component =
+ typeof doc?.name === 'string' && doc.name
+ ? doc.name
+ : path.basename(path.dirname(full));
+
+ for (const target of doc?.theming?.targets || []) {
+ const className = target?.className;
+ if (typeof className !== 'string') continue;
+ const key = targetKey(className);
+ if (!key) continue;
+ targets.push({
+ key,
+ className,
+ component,
+ props: stringList(target.visualProps),
+ states: stringList(target.states),
+ });
+ }
+ }
+ }
+
+ await scan(coreSrc);
+
+ targets.sort(
+ (a, b) => a.key.localeCompare(b.key) || a.component.localeCompare(b.component),
+ );
+ return targets;
+}
+
+/**
+ * Collapse the enumeration into the `{key: [props and states]}` map theme
+ * validation checks override keys against — both are legal override keys, so
+ * they share one list.
+ * @param {ThemingTarget[]} targets
+ * @returns {Record<string, string[]>}
+ */
+export function targetsByKey(targets) {
+ /** @type {Record<string, string[]>} */
+ const byKey = {};
+ for (const t of targets) {
+ byKey[t.key] = [...new Set([...(byKey[t.key] || []), ...t.props, ...t.states])];
+ }
+ return byKey;
+}
+
+/**
+ * @param {unknown} value
+ * @returns {string[]}
+ */
+function stringList(value) {
+ return Array.isArray(value)
+ ? value.filter((/** @type {unknown} */ v) => typeof v === 'string')
+ : [];
+}
diff --git a/packages/cli/foundation/discovery/theming-targets.test.mjs b/packages/cli/foundation/discovery/theming-targets.test.mjs
new file mode 100644
index 0000000000..f61e812b9d
--- /dev/null
+++ b/packages/cli/foundation/discovery/theming-targets.test.mjs
@@ -0,0 +1,127 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The enumerability guard for component theming targets.
+ *
+ * A theming target is only useful if a theme author can find it. These tests
+ * run against the REAL core docs and fail if any component's targets stop
+ * being enumerable — a doc that moves out of the scanned tree, a target shape
+ * that stops being read, or a component whose Theming table says one thing
+ * while `theme targets` says another. That divergence is the failure the
+ * listing exists to prevent: a target list that can drift from the components
+ * is worse than no list.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as path from 'node:path';
+import {findCoreDir} from '../fs/paths.mjs';
+import {
+ discoverComponents,
+ findComponentReadme,
+} from './component-discovery.mjs';
+import {loadComponentDoc} from './component-loader.mjs';
+import {collectThemingTargets, targetsByKey} from './theming-targets.mjs';
+
+const coreDir = /** @type {string} */ (findCoreDir(process.cwd()));
+const coreSrc = path.join(coreDir, 'src');
+
+/** @type {Promise<import('./theming-targets.mjs').ThemingTarget[]>} */
+const enumerated = collectThemingTargets(coreSrc);
+
+describe('collectThemingTargets', () => {
+ it('enumerates the whole surface, not a handful', async () => {
+ const targets = await enumerated;
+ expect(targets.length).toBeGreaterThan(100);
+ expect(new Set(targets.map(t => t.component)).size).toBeGreaterThan(50);
+ });
+
+ it('drops the namespace prefix so each key is what defineTheme takes', async () => {
+ for (const t of await enumerated) {
+ expect(t.className).toBe(`astryx-${t.key}`);
+ expect(t.component).toBeTruthy();
+ }
+ });
+
+ it('carries the props and states a target reflects', async () => {
+ const targets = await enumerated;
+ expect(targets.find(t => t.key === 'switch-thumb')).toEqual({
+ key: 'switch-thumb',
+ className: 'astryx-switch-thumb',
+ component: 'Switch',
+ props: ['size'],
+ states: ['checked'],
+ });
+ });
+
+ it('is sorted by key, so a diff of two runs is readable', async () => {
+ const keys = (await enumerated).map(t => t.key);
+ expect(keys).toEqual([...keys].sort((a, b) => a.localeCompare(b)));
+ });
+
+ // The listing and `theme build`'s override validation read this one
+ // enumeration. `targetsByKey` is the shape validation wants: props and
+ // states merged, because both are legal override keys.
+ it('collapses to the override keys, merging the components that share one', async () => {
+ const byKey = targetsByKey(await enumerated);
+ expect(byKey['switch']).toEqual(['size', 'checked', 'disabled']);
+ // `radio` is documented by both Indicator and RadioList.
+ const radio = (await enumerated).filter(t => t.key === 'radio');
+ expect(radio.length).toBeGreaterThan(1);
+ for (const t of radio) {
+ for (const name of [...t.props, ...t.states]) {
+ expect(byKey['radio']).toContain(name);
+ }
+ }
+ });
+
+ it('every component doc that declares targets has them enumerated', async () => {
+ const targets = await enumerated;
+ /** @type {Map<string, Set<string>>} key -> props+states */
+ const byKey = new Map(
+ Object.entries(targetsByKey(targets)).map(([k, v]) => [k, new Set(v)]),
+ );
+
+ const names = Object.values(discoverComponents(coreDir)).flat();
+ /** @type {string[]} */
+ const missing = [];
+ /** @type {Set<string>} */
+ const seenDocs = new Set();
+ let checked = 0;
+
+ for (const name of names) {
+ const docPath = findComponentReadme(coreDir, name);
+ if (!docPath || seenDocs.has(docPath)) continue;
+ seenDocs.add(docPath);
+
+ /** @type {any} */
+ let doc;
+ try {
+ doc = await loadComponentDoc(docPath);
+ } catch {
+ continue;
+ }
+
+ for (const target of doc?.theming?.targets || []) {
+ if (typeof target?.className !== 'string') continue;
+ checked++;
+ const key = target.className.replace(/^astryx-/, '');
+ const known = byKey.get(key);
+ if (!known) {
+ missing.push(`${name}: ${target.className} is not enumerable`);
+ continue;
+ }
+ for (const prop of [
+ ...(target.visualProps || []),
+ ...(target.states || []),
+ ]) {
+ if (!known.has(prop)) {
+ missing.push(`${name}: ${target.className} lost "${prop}"`);
+ }
+ }
+ }
+ }
+
+ expect(checked).toBeGreaterThan(100);
+ expect(missing).toEqual([]);
+ }, 60_000);
+});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 06b19c3998..9d9825e9b2 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -199,6 +199,11 @@ export const doc = {
description:
'A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not — `exists` when a file was already there, which is a success.',
},
+ {
+ value: 'theme.targets',
+ description:
+ 'The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys.',
+ },
// upgrade
{