Skip to content

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

TypeScript

refactor(cli): extract theme build compiler into api/theme/build (#4462)

Joey6e17c7405b97
diff --git a/.changeset/cli-thin-api-theme-build.md b/.changeset/cli-thin-api-theme-build.md
new file mode 100644
index 0000000000..cc0ff70ac8
--- /dev/null
+++ b/.changeset/cli-thin-api-theme-build.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] CLI: `theme build` is now fully scriptable through the `./api` barrel — the ~1,000-line theme compiler (defineTheme extraction, CSS generation via `@astryxdesign/core/theme`, variant/type-declaration + icon-module generation, override validation) lives in `api/theme/build` and returns a typed `theme.build` receipt, with the CLI reduced to a thin parse → API call → render wrapper. Human progress is emitted through an injectable logger, so a scripted `themeBuild()` stays silent while the generated CSS/JS/.d.ts, the `--json` envelope, and human output stay byte-identical for existing usage. Watch mode remains a thin CLI loop.
+@josephfarina
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index 9ba9aeff5d..a3f52bb422 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -25,6 +25,7 @@ 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 {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
new file mode 100644
index 0000000000..340f5f3a81
--- /dev/null
+++ b/packages/cli/api/theme/build/build.mjs
@@ -0,0 +1,1053 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file theme build API — compile a defineTheme file to CSS + JS + .d.ts.
+ *
+ * `themeBuild(file, options, ctx)` is the programmatic surface behind
+ * `astryx theme build`. It reads a theme file that uses defineTheme() and, via
+ * @astryxdesign/core's shared generator (the SINGLE source of truth so the
+ * build emits the exact CSS the `<Theme>` runtime does), writes:
+ * - A CSS file with token overrides and component styles
+ * - A JS module that re-exports the built theme (+ icon registry)
+ * - A .d.ts (plus an optional .variants.d.ts for custom prop values)
+ *
+ * It performs the writes and returns a `theme.build` receipt, or `null` when
+ * the theme produced no CSS (nothing to build). Errors throw AstryxError (with
+ * a stable code). Human progress is emitted through the injected `logger`
+ * (silent by default), so the CLI keeps its exact output while a programmatic
+ * caller stays quiet.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL, fileURLToPath} from 'node:url';
+import {createJiti} from 'jiti';
+import {getCliInvocation} from '../../../utils/package-manager.mjs';
+import {
+ sanitizeName,
+ PathSafetyError,
+} from '../../../utils/path-safety.mjs';
+import {ERROR_CODES} from '../../../lib/error-codes.mjs';
+import {AstryxError} from '../../error.mjs';
+
+// Import shared theme processing from core. `astryx theme build` MUST produce the
+// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
+// path: core's generator. There is no in-CLI fallback implementation — if this
+// import fails, the build fails (see the ERR_CORE_NOT_FOUND guard in the theme
+// action). A built, resolvable `@astryxdesign/core` is a hard requirement.
+// A built, resolvable `@astryxdesign/core` is a hard requirement. These are
+// populated from a dynamic import (a runtime boundary), so `any` is intentional.
+/** @type {any} */ let _defineTheme = null;
+/** @type {any} */ let _generateThemeRulesSplit = null;
+/** @type {any} */ let _generateOnMediaCSS = null;
+/** @type {any} */ let _coreImportError = null;
+try {
+ const coreTheme = await import('@astryxdesign/core/theme');
+ _defineTheme = coreTheme.defineTheme;
+ _generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
+ _generateOnMediaCSS = coreTheme.generateOnMediaCSS;
+} catch (e) {
+ // Capture the reason so the theme action can surface a precise, actionable
+ // error. We don't throw here: this module is imported eagerly by the CLI
+ // entrypoint for every command, and a throw at load time would break
+ // unrelated commands (the entry wraps loads in try/catch and degrades the
+ // command to a stub). The hard failure happens when `theme build` runs.
+ _coreImportError = e;
+}
+
+/**
+ * Build a @generated attribution header for generated files.
+ * @param {string} sourceFile - Relative path to the source theme file
+ * @param {'css'|'js'|'ts'} lang - File language (determines comment syntax)
+ * @param {string} [command] - The full CLI command used to generate this file
+ */
+function generatedHeader(sourceFile, lang = 'js', command) {
+ const timestamp = new Date().toISOString();
+ const body = [
+ `@generated by \`astryx theme build\` — do not edit manually.`,
+ `Source: ${sourceFile}`,
+ ];
+ if (command) {
+ body.push(`Command: ${command}`);
+ }
+ body.push(`Generated: ${timestamp}`);
+ if (lang === 'css') {
+ return `/*\n * ${body.join('\n * ')}\n */\n\n`;
+ }
+ return `/**\n * ${body.join('\n * ')}\n */\n\n`;
+}
+
+/**
+ * Convert a theme name to a valid JS identifier.
+ * e.g. 'default-minimal' → 'defaultMinimal', 'ocean' → 'ocean'
+ * @param {string} name
+ * @returns {string}
+ */
+function toIdentifier(name) {
+ return name.replace(/-([a-z])/g, (/** @type {string} */ _, /** @type {string} */ c) => c.toUpperCase());
+}
+
+/**
+ * Import specifier for install/scaffold instructions. Drops a leading `src/`
+ * from the cwd-relative dir (most consumers import from a file under src/) but
+ * keeps the rest of the path (e.g. `themes/gothic`). Callers note the path is
+ * relative to the consumer's file.
+ * Exported (not just used by `themeBuild`'s install instructions) because the
+ * thin CLI's `theme add` action reuses it for its own scaffold instructions.
+ * @param {string} relDir
+ * @param {string} base
+ * @returns {string}
+ */
+export function importSpecifier(relDir, base) {
+ const normalized = relDir === '.' ? '' : relDir;
+ const withinSrc = normalized.replace(/^src\/?/, '').replace(/\/+$/, '');
+ return withinSrc ? `./${withinSrc}/${base}` : `./${base}`;
+}
+
+/**
+ * Convert a kebab-case component name to PascalCase.
+ * e.g. 'button' → 'Button', 'progress-bar' → 'ProgressBar', 'avatar-status-dot' → 'AvatarStatusDot'
+ * @param {string} name
+ * @returns {string}
+ */
+function toPascalCase(name) {
+ return name
+ .split('-')
+ .map((/** @type {string} */ part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join('');
+}
+
+/**
+ * Load known built-in values for a component's visual props from its .doc.mjs file.
+ * Parses the type string (e.g. "'info' | 'warning' | 'error' | 'success'") to extract values.
+ * Returns a map of { propName: string[] } for props that are visual (listed in theming targets).
+ * @param {string} componentName
+ * @returns {Promise<Record<string, string[]>>}
+ */
+async function loadKnownValues(componentName) {
+ // Resolve core src relative to the CLI package, not cwd (which may be a theme package)
+ const cliDir = path.dirname(fileURLToPath(import.meta.url));
+ const coreSrc = path.resolve(cliDir, '../../../../core/src');
+ if (!fs.existsSync(coreSrc)) return {};
+ // Map component name to directory (e.g. 'banner' → 'Banner', 'dropdownmenu' → 'DropdownMenu')
+ const dirs = fs.readdirSync(coreSrc, { withFileTypes: true })
+ .filter(d => d.isDirectory())
+ .map(d => d.name);
+ const dir = dirs.find(d => d.toLowerCase() === componentName.toLowerCase()
+ || d.toLowerCase().replace(/[^a-z]/g, '') === componentName.toLowerCase());
+ if (!dir) return {};
+
+ const docPath = path.join(coreSrc, dir, `${dir}.doc.mjs`);
+ if (!fs.existsSync(docPath)) return {};
+
+ try {
+ const docModule = await import(pathToFileURL(docPath).href);
+ const doc = docModule.docs;
+ if (!doc?.theming?.targets) return {};
+
+ // Collect all props — from doc.props or doc.components[].props
+ const allProps = [];
+ if (doc.props) allProps.push(...doc.props);
+ if (doc.components) {
+ for (const comp of doc.components) {
+ if (comp.props) allProps.push(...comp.props);
+ }
+ }
+ if (allProps.length === 0) return {};
+
+ // Collect visual prop names from theming targets
+ /** @type {Set<string>} */
+ const visualProps = new Set();
+ for (const target of doc.theming.targets) {
+ if (target.visualProps) {
+ for (const vp of target.visualProps) visualProps.add(vp);
+ }
+ }
+
+ // Extract values from prop type strings
+ /** @type {Record<string, string[]>} */
+ const result = {};
+ for (const prop of allProps) {
+ if (!visualProps.has(prop.name)) continue;
+ if (!prop.type || typeof prop.type !== 'string') continue;
+
+ // Parse union type: "'info' | 'warning' | 'error' | 'success'" → ['info', 'warning', 'error', 'success']
+ const matches = prop.type.match(/'([^']+)'/g);
+ if (matches) {
+ result[prop.name] = matches.map((/** @type {string} */ m) => m.replace(/'/g, ''));
+ }
+ }
+ return result;
+ } catch {
+ return {};
+ }
+}
+
+// Cache for loaded known values
+/** @type {Map<string, Record<string, string[]>>} */
+const _knownValuesCache = new Map();
+/**
+ * @param {string} componentName
+ * @returns {Promise<Record<string, string[]>>}
+ */
+async function getKnownValues(componentName) {
+ if (!_knownValuesCache.has(componentName)) {
+ _knownValuesCache.set(componentName, await loadKnownValues(componentName));
+ }
+ return _knownValuesCache.get(componentName) ?? {};
+}
+
+/**
+ * Resolve `@astryxdesign/core`'s package root relative to the CLI package. Core
+ * and the CLI ship as siblings (`@astryxdesign/core`, `@astryxdesign/cli`), so
+ * `../../../../core` from `api/theme/build/` reaches core whether installed from
+ * npm or run inside the monorepo. Returns null if it can't be found.
+ */
+function resolveCoreRoot() {
+ const cliDir = path.dirname(fileURLToPath(import.meta.url));
+ const coreRoot = path.resolve(cliDir, '../../../../core');
+ return fs.existsSync(coreRoot) ? coreRoot : null;
+}
+
+/**
+ * Read the type declarations `@astryxdesign/core/<Component>` exposes so we can
+ * check whether a given augmentation-target interface actually exists before
+ * generating a module augmentation against it.
+ *
+ * Reads the shipped `dist/<Component>/index.d.ts` (what a consumer's TypeScript
+ * actually sees), falling back to the `src/<Component>/index.ts` in the
+ * monorepo. Returns the file contents, or '' if nothing is found.
+ */
+/** @type {Map<string, string>} */
+const _componentDeclCache = new Map();
+/**
+ * @param {string} pascalName
+ * @returns {string}
+ */
+function readComponentDeclarations(pascalName) {
+ if (_componentDeclCache.has(pascalName)) {
+ return _componentDeclCache.get(pascalName) ?? '';
+ }
+ let contents = '';
+ const coreRoot = resolveCoreRoot();
+ if (coreRoot) {
+ const candidates = [
+ path.join(coreRoot, 'dist', pascalName, 'index.d.ts'),
+ path.join(coreRoot, 'src', pascalName, 'index.ts'),
+ ];
+ for (const file of candidates) {
+ try {
+ if (fs.existsSync(file)) {
+ contents = fs.readFileSync(file, 'utf-8');
+ break;
+ }
+ } catch {
+ // ignore and try the next candidate
+ }
+ }
+ }
+ _componentDeclCache.set(pascalName, contents);
+ return contents;
+}
+
+/**
+ * Determine whether `@astryxdesign/core/<Component>` exports an interface named
+ * `interfaceName` that can be augmented via module augmentation.
+ *
+ * Only interfaces are extension points — closed literal-union types (e.g.
+ * `HeadingType`, `ButtonSize`) are NOT augmentable, so a generated augmentation
+ * against them is dead code. We check that the name is exported (directly or
+ * re-exported) as a type/interface.
+ * @param {string} pascalName
+ * @param {string} interfaceName
+ * @returns {boolean}
+ */
+function componentHasAugmentableInterface(pascalName, interfaceName) {
+ const decl = readComponentDeclarations(pascalName);
+ if (!decl) return false;
+ // Word-boundary match so `ButtonVariantMap` doesn't match `XButtonVariantMap`.
+ const re = new RegExp(`\\b${interfaceName}\\b`);
+ return re.test(decl);
+}
+
+/**
+ * Generate TypeScript declaration content with module augmentation for custom
+ * component prop values found in the theme's `components` keys. Reads known
+ * values from doc files to filter out base prop values.
+ *
+ * Interface naming convention: PascalCase(component) + PascalCase(prop) + Map
+ * banner + status → BannerStatusMap
+ * button + variant → ButtonVariantMap
+ *
+ * An augmentation is only emitted when `@astryxdesign/core/<Component>` actually
+ * exports a matching interface. Props backed by closed literal-union types
+ * (e.g. Button `size`, Heading `type`/`level`) have no augmentation point, so
+ * generating a `declare module` block for them would be dead code — those are
+ * skipped.
+ *
+ * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef - Theme definition (resolved by defineTheme)
+ * @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed
+ */
+async function generateVariantDeclarationsAsync(themeDef) {
+ if (!themeDef.components || Object.keys(themeDef.components).length === 0) {
+ return null;
+ }
+
+ // Collect custom values: { component: { prop: [value, ...] } }
+ /** @type {Record<string, Record<string, Set<string>>>} */
+ const customValues = {};
+
+ for (const [component, rules] of Object.entries(themeDef.components)) {
+ const knownForComponent = await getKnownValues(component);
+
+ for (const key of Object.keys(rules)) {
+ if (key === 'base') continue;
+
+ const pairs = key.split('+');
+ for (const pair of pairs) {
+ const colonIdx = pair.indexOf(':');
+ if (colonIdx === -1) continue;
+ const prop = pair.slice(0, colonIdx);
+ const value = pair.slice(colonIdx + 1);
+
+ // Skip known built-in values
+ const knownForProp = knownForComponent[prop];
+ if (knownForProp && knownForProp.includes(value)) continue;
+
+ if (!customValues[component]) customValues[component] = {};
+ if (!customValues[component][prop]) customValues[component][prop] = new Set();
+ customValues[component][prop].add(value);
+ }
+ }
+ }
+
+ // Check if we found any custom values
+ const hasCustom = Object.values(customValues).some(
+ props => Object.values(props).some(values => values.size > 0)
+ );
+ if (!hasCustom) return null;
+
+ const sections = ['// Generated by astryx theme build', 'export {};', ''];
+
+ for (const [component, props] of Object.entries(customValues)) {
+ for (const [prop, values] of Object.entries(props)) {
+ if (values.size === 0) continue;
+
+ const pascal = toPascalCase(component);
+ const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
+ const modulePath = `@astryxdesign/core/${pascal}`;
+ const interfaceName = `${pascal}${propPascal}Map`;
+
+ // Only augment interfaces that actually exist as an extension point in
+ // core. Props backed by closed literal-union types (e.g. Button `size`,
+ // Heading `type`/`level`) have no `*Map` interface — a `declare module`
+ // block against a non-existent interface just creates a new, unused
+ // interface and never extends the component's prop union, so skip it.
+ if (!componentHasAugmentableInterface(pascal, interfaceName)) continue;
+
+ sections.push(`declare module '${modulePath}' {`);
+ sections.push(` interface ${interfaceName} {`);
+ for (const v of values) {
+ sections.push(` '${v}': true;`);
+ }
+ sections.push(' }');
+ sections.push('}');
+ sections.push('');
+ }
+ }
+
+ // If every custom value targeted a non-augmentable prop, there's nothing to
+ // emit beyond the header — return null so no `.variants.d.ts` is written.
+ const hasEmittedAugmentation = sections.some(line =>
+ line.startsWith('declare module'),
+ );
+ if (!hasEmittedAugmentation) return null;
+
+ return sections.join('\n');
+}
+
+/**
+ * Resolve a token value — [light, dark] tuple becomes light-dark()
+ * @param {unknown} value
+ * @returns {unknown}
+ */
+function resolveTokenValue(value) {
+ if (Array.isArray(value)) {
+ return `light-dark(${value[0]}, ${value[1]})`;
+ }
+ return value;
+}
+
+// Theme @scope selector helpers. Keep the `astryx` literal in sync with
+// packages/core/src/naming.ts (NAMESPACE) and generateThemeRules.ts.
+// Theme scopes to data-astryx-theme; the static build path must match.
+const themeScopeStart = (/** @type {string} */ name) => `[data-astryx-theme="${name}"]`;
+const THEME_SCOPE_TO = `[data-astryx-theme]`;
+
+/**
+ * Import a theme module using jiti and find the defineTheme() result.
+ * Returns the resolved DefinedTheme object.
+ * @param {string} filePath
+ * @returns {Promise<any>}
+ */
+async function importThemeModule(filePath) {
+ const jiti = createJiti(import.meta.url, {
+ moduleCache: false,
+ jsx: true,
+ });
+
+ const mod = await jiti.import(filePath, {default: true});
+
+ if (isThemeObject(mod)) return mod;
+
+ if (mod && typeof mod === 'object') {
+ for (const value of Object.values(mod)) {
+ if (isThemeObject(value)) return value;
+ }
+ }
+
+ throw new Error(
+ `Could not find a defineTheme() result in ${filePath}.\n` +
+ `Expected an export like: export const myTheme = defineTheme({ name: '...', tokens: {...} })`,
+ );
+}
+
+/**
+ * @param {any} value
+ * @returns {boolean}
+ */
+function isThemeObject(value) {
+ return (
+ value &&
+ typeof value === 'object' &&
+ typeof value.name === 'string' &&
+ value.tokens &&
+ typeof value.tokens === 'object'
+ );
+}
+
+/**
+ * Extract the theme definition from a JS/TS file.
+ * Tries jiti first (full TS support), falls back to regex+eval.
+ * @param {string} filePath
+ * @returns {Promise<any>}
+ */
+async function extractThemeDefinition(filePath) {
+ try {
+ return await importThemeModule(filePath);
+ } catch (jitiError) {
+ try {
+ return extractThemeDefinitionLegacy(filePath);
+ } catch {
+ const je = /** @type {Error} */ (jitiError);
+ throw new Error(
+ `Failed to load theme from ${filePath}: ${je.message}\n` +
+ `Make sure all imports in the theme file are resolvable.`,
+ );
+ }
+ }
+}
+
+/**
+ * Fallback extraction via regex + eval.
+ * Only works for plain object literals — can't follow imports or variables.
+ * @param {string} filePath
+ * @returns {any}
+ */
+function extractThemeDefinitionLegacy(filePath) {
+ const content = fs.readFileSync(filePath, 'utf8');
+
+ const defineMatch = content.match(/defineTheme\s*\(\s*({[\s\S]*?})\s*\)/);
+ if (!defineMatch) {
+ const defaultMatch = content.match(/export\s+default\s+({[\s\S]*?});/);
+ if (!defaultMatch) {
+ throw new Error(
+ `Could not find defineTheme() call or default export in ${filePath}.\n` +
+ `Expected: defineTheme({ name: '...', tokens: {...} })`,
+ );
+ }
+
+ return eval(`(${defaultMatch[1]})`);
+ }
+
+ let objStr = defineMatch[1];
+ objStr = objStr.replace(/\s+as\s+const/g, '');
+ objStr = objStr.replace(/icons:\s*[a-zA-Z_][a-zA-Z0-9_]*/g, 'icons: undefined');
+
+ try {
+
+ return eval(`(${objStr})`);
+ } catch (e) {
+ const err = /** @type {Error} */ (e);
+ throw new Error(
+ `Failed to parse theme definition in ${filePath}: ${err.message}\n` +
+ `Make sure the defineTheme() argument is a plain object literal.`,
+ {cause: e},
+ );
+ }
+}
+
+/**
+ * Extract icon import info from a theme source file.
+ * Returns { importPath, exportName } or null if no icons.
+ *
+ * Looks for patterns like:
+ * import { defaultIconRegistry } from './icons';
+ * icons: defaultIconRegistry,
+ * @param {string} filePath
+ * @returns {{exportName: string, importPath: string} | null}
+ */
+function extractIconInfo(filePath) {
+ const content = fs.readFileSync(filePath, 'utf8');
+
+ // Find the icons field in defineTheme
+ const iconsMatch = content.match(/icons:\s*([a-zA-Z_][a-zA-Z0-9_]*)/);
+ if (!iconsMatch) return null;
+
+ const varName = /** @type {string} */ (iconsMatch[1]);
+
+ // Find the import for that variable
+ const importRegex = new RegExp(
+ `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,
+ );
+ const importMatch = content.match(importRegex);
+ if (!importMatch) return null;
+
+ return {
+ exportName: varName,
+ importPath: /** @type {string} */ (importMatch[1]),
+ };
+}
+
+/**
+ * Generate a minimal JS module for a built theme.
+ * Includes the theme name, marker, and re-exports the icon registry.
+ * All styling is in the CSS file.
+ * @param {any} themeDef
+ * @param {{exportName: string, importPath: string} | null} iconInfo
+ * @returns {string}
+ */
+function generateBuiltModule(themeDef, iconInfo) {
+ const iconImport = iconInfo
+ ? `import { ${iconInfo.exportName} } from '${iconInfo.importPath}';\n`
+ : '';
+ const iconsField = iconInfo ? ` icons: ${iconInfo.exportName},` : '';
+ const iconReExport = iconInfo
+ ? `\nexport { ${iconInfo.exportName} };\n`
+ : '';
+
+ // Resolve token values — tuples become light-dark() strings
+ /** @type {Record<string, unknown>} */
+ const resolvedTokens = {};
+ if (themeDef.tokens) {
+ for (const [key, value] of Object.entries(themeDef.tokens)) {
+ resolvedTokens[key] = resolveTokenValue(value);
+ }
+ }
+
+ const tokensStr = JSON.stringify(resolvedTokens, null, 2)
+ .split('\n')
+ .map((line, i) => (i === 0 ? line : ' ' + line))
+ .join('\n');
+
+ return `${iconImport}/**
+ * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
+ * Import the CSS file alongside this module:
+ *
+ * import { ${toIdentifier(themeDef.name)}Theme } from './${themeDef.name}';
+ * import './${themeDef.name}.css';
+ */
+export const ${toIdentifier(themeDef.name)}Theme = {
+ name: '${themeDef.name}',
+ __built: true,
+ tokens: ${tokensStr},
+${iconsField}
+};
+${iconReExport}`;
+}
+
+/**
+ * Generate TypeScript declarations for a built theme module.
+ * @param {any} themeDef
+ * @param {{exportName: string, importPath: string} | null} iconInfo
+ * @param {string | null} variantsFileName
+ * @returns {string}
+ */
+function generateBuiltTypes(themeDef, iconInfo, variantsFileName) {
+ const iconType = iconInfo
+ ? `import type { IconRegistry } from '@astryxdesign/core/Icon';
+export declare const ${iconInfo.exportName}: IconRegistry;
+`
+ : '';
+ // Pull in the generated custom-variant augmentations so that importing the
+ // theme's types also loads the module augmentations (otherwise the
+ // `.variants.d.ts` is emitted but never referenced, and the custom variants
+ // never widen the component prop unions for consumers).
+ const variantsRef = variantsFileName
+ ? `/// <reference path="./${variantsFileName}" />
+`
+ : '';
+ return `${variantsRef}import type { DefinedTheme } from '@astryxdesign/core/theme';
+${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedTheme;
+`;
+}
+
+// =============================================================================
+// Component validation
+// =============================================================================
+
+/**
+ * Known Astryx component names and their visual props.
+ * Used to warn on typos in defineTheme component overrides.
+ * @type {Record<string, string[]>}
+ */
+const KNOWN_COMPONENTS = {
+ appshell: ['position'],
+ aspectratio: [],
+ avatar: ['size'],
+ badge: ['variant', 'color'],
+ banner: ['container', 'status'],
+ breadcrumbs: ['variant'],
+ button: ['variant', 'size'],
+ calendar: [],
+ card: ['variant'],
+ center: [],
+ checkboxinput: [],
+ collapsible: [],
+ dateinput: [],
+ dialog: ['variant', 'position'],
+ divider: ['variant', 'orientation'],
+ dropdownmenu: [],
+ 'empty-state': [],
+ field: [],
+ formlayout: [],
+ grid: ['align'],
+ heading: ['level'],
+ icon: ['size', 'color'],
+ kbd: [],
+ layer: [],
+ layout: [],
+ link: ['color'],
+ list: ['type', 'density'],
+ mobilenav: [],
+ moremenu: [],
+ navicon: [],
+ numberinput: [],
+ pagination: ['variant'],
+ progressbar: ['variant', 'size'],
+ radiolist: ['orientation'],
+ section: ['variant'],
+ selector: ['type', 'size', 'color'],
+ sidenav: [],
+ skeleton: [],
+ slider: ['orientation'],
+ spinner: ['size'],
+ stack: [],
+ statusdot: ['variant', 'size'],
+ switch: [],
+ table: [],
+ tablist: ['type'],
+ text: ['type', 'color'],
+ textarea: [],
+ textinput: [],
+ timeinput: [],
+ token: ['color'],
+ tokenizer: [],
+ topnav: [],
+ typeahead: ['type', 'size', 'color'],
+};
+
+/**
+ * Validate component overrides in a theme definition.
+ * Warns on unknown component names and unknown prop names.
+ * Returns array of warning strings.
+ * @param {{components?: Record<string, Record<string, unknown>>}} themeDef
+ * @returns {string[]}
+ */
+function validateComponentOverrides(themeDef) {
+ /** @type {string[]} */
+ const warnings = [];
+ if (!themeDef.components) return warnings;
+
+ for (const [component, rules] of Object.entries(themeDef.components)) {
+ // Check component name
+ if (!(component in KNOWN_COMPONENTS)) {
+ const similar = Object.keys(KNOWN_COMPONENTS)
+ .filter((k) => {
+ if (k.includes(component) || component.includes(k)) return true;
+ // Levenshtein distance 1-2 for short names
+ if (Math.abs(k.length - component.length) <= 2) {
+ let diff = 0;
+ const longer = k.length >= component.length ? k : component;
+ const shorter = k.length < component.length ? k : component;
+ let j = 0;
+ for (let i = 0; i < longer.length && diff <= 2; i++) {
+ if (longer[i] !== shorter[j]) diff++;
+ else j++;
+ }
+ diff += shorter.length - j;
+ return diff <= 2;
+ }
+ return false;
+ })
+ .slice(0, 3);
+ const hint = similar.length > 0 ? ` Did you mean: ${similar.join(', ')}?` : '';
+ warnings.push(`Unknown component "${component}".${hint}`);
+ continue;
+ }
+
+ // Check prop names in prop:value keys
+ const knownProps = KNOWN_COMPONENTS[component];
+ for (const key of Object.keys(rules)) {
+ if (key === 'base') continue;
+
+ // Parse prop:value pairs (e.g. 'variant:secondary' or 'variant:destructive+size:sm')
+ const pairs = key.split('+');
+ for (const pair of pairs) {
+ const [prop] = pair.split(':');
+ if (prop && !knownProps.includes(prop)) {
+ const hint =
+ knownProps.length > 0
+ ? ` Known props: ${knownProps.join(', ')}`
+ : ' This component has no variant props.';
+ warnings.push(
+ `Unknown prop "${prop}" on component "${component}".${hint}`,
+ );
+ }
+ }
+ }
+ }
+
+ return warnings;
+}
+
+/**
+ * Validate that themes don't set private (--_*) CSS custom properties directly.
+ * Private vars are internal implementation details managed by the derived var
+ * expansion pipeline. Theme authors should write standard CSS properties
+ * (e.g. borderRadius, padding) instead.
+ *
+ * Returns array of error strings.
+ * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef
+ * @returns {string[]}
+ */
+function validatePrivateVars(themeDef) {
+ /** @type {string[]} */
+ const errors = [];
+ if (!themeDef.components) return errors;
+
+ for (const [component, rules] of Object.entries(themeDef.components)) {
+ for (const [key, styles] of Object.entries(rules)) {
+ for (const prop of Object.keys(styles)) {
+ if (typeof prop === 'string' && prop.startsWith('--_')) {
+ errors.push(
+ `Component "${component}" (${key}) sets private var "${prop}". ` +
+ `Private vars (--_*) are internal — use standard CSS properties ` +
+ `(e.g. borderRadius, padding) instead. The pipeline expands them automatically.`,
+ );
+ }
+ }
+ }
+ }
+
+ return errors;
+}
+
+/**
+ * @typedef {object} ThemeBuildLogger
+ * @property {(m?: string) => void} log - stdout (install/receipt lines)
+ * @property {(m?: string) => void} warn - stderr (component-override warnings)
+ * @property {(m?: string) => void} error - stderr (private-var errors)
+ */
+
+/**
+ * No-op logger — the default so a programmatic caller stays silent. The CLI
+ * injects a real logger (humanLog / console.warn / console.error) in human
+ * mode, and this same no-op shape in --json mode so human chatter never
+ * corrupts the single JSON envelope.
+ * @type {ThemeBuildLogger}
+ */
+const noopLogger = {log() {}, warn() {}, error() {}};
+
+/**
+ * Compile a defineTheme file to CSS + JS + .d.ts (and an optional
+ * `.variants.d.ts`). Performs the writes and returns a `theme.build` receipt,
+ * or `null` when the theme produced no CSS (nothing to build). Throws
+ * AstryxError (stable code) on failure. Progress is emitted through `logger`
+ * (silent by default).
+ *
+ * @param {string} file - Theme file path, resolved against `cwd`.
+ * @param {{out?: string}} [options] - `out` overrides the output CSS path.
+ * @param {{cwd?: string, logger?: ThemeBuildLogger}} [ctx]
+ * @returns {Promise<import('../../../types/theme').ThemeBuildResponse | null>}
+ */
+export async function themeBuild(file, options = {}, {cwd = process.cwd(), logger = noopLogger} = {}) {
+ const filePath = path.resolve(cwd, file);
+
+ if (!fs.existsSync(filePath)) {
+ throw new AstryxError(`File not found: ${filePath}`, undefined, ERROR_CODES.ERR_FILE_NOT_FOUND);
+ }
+
+ logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);
+
+ // Extract theme definition
+ let themeDef;
+ try {
+ themeDef = await extractThemeDefinition(filePath);
+ } catch (e) {
+ const err = /** @type {Error} */ (e);
+ throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_THEME_LOAD);
+ }
+
+ if (!themeDef.name) {
+ throw new AstryxError('Theme must have a name property.', undefined, ERROR_CODES.ERR_THEME_INVALID);
+ }
+
+ // Path-safety: the theme name is used to derive output filenames
+ // (e.g. `${name}.css`, `${name}.js`). Reject names containing path
+ // separators or traversal markers — `../../escaped` would otherwise
+ // write JS modules outside the input directory.
+ try {
+ sanitizeName(themeDef.name, {label: 'theme name'});
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
+ }
+ throw err;
+ }
+
+ // Validate component overrides
+ const warnings = validateComponentOverrides(themeDef);
+ const warningMessages = [];
+ for (const w of warnings) {
+ warningMessages.push(w);
+ logger.warn(` ⚠ ${w}`);
+ }
+
+ // Validate no private vars are set directly
+ const privateVarErrors = validatePrivateVars(themeDef);
+ for (const e of privateVarErrors) {
+ warningMessages.push(e);
+ logger.error(` ✗ ${e}`);
+ }
+ if (privateVarErrors.length > 0) {
+ logger.error(`\n ${privateVarErrors.length} private var error(s). Use standard CSS properties instead.`);
+ }
+
+ // Generate CSS via core's shared generator — the SINGLE source of truth.
+ // `astryx theme build` and the `<Theme>` runtime MUST emit identical CSS, so
+ // there is exactly one generation path: @astryxdesign/core/theme. If core could not
+ // be imported, fail hard rather than silently producing divergent output.
+ if (!_defineTheme || !_generateThemeRulesSplit) {
+ throw new AstryxError(
+ 'Could not load @astryxdesign/core/theme — `astryx theme build` requires a ' +
+ 'built, resolvable @astryxdesign/core so it emits the same CSS as the ' +
+ 'runtime <Theme>. Build @astryxdesign/core first (e.g. `pnpm -F @astryxdesign/core ' +
+ 'build`)' +
+ (_coreImportError ? `.\n Import error: ${_coreImportError.message}` : '.'),
+ undefined,
+ ERROR_CODES.ERR_CORE_NOT_FOUND,
+ );
+ }
+
+ let css;
+ let resolvedTheme;
+ {
+ // jiti returns an already-resolved theme; legacy eval returns raw input.
+ const isAlreadyResolved =
+ !themeDef.typography && !themeDef.motion && !themeDef.radius;
+ if (isAlreadyResolved) {
+ resolvedTheme = themeDef;
+ } else {
+ resolvedTheme = _defineTheme({
+ name: themeDef.name,
+ typography: themeDef.typography,
+ motion: themeDef.motion,
+ radius: themeDef.radius,
+ tokens: themeDef.tokens,
+ components: themeDef.components,
+ });
+ }
+ const scopeSelector = themeScopeStart(themeDef.name);
+ const scopeTo = THEME_SCOPE_TO;
+
+ const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
+ const cssParts = [];
+ // Prose element defaults always ship — the `<Theme>` runtime
+ // (generateThemeCSS) always emits them, so the build must too, or the
+ // CLI output would diverge from runtime. They go in @layer reset
+ // (zero-specificity :where()) so component/Markdown StyleX always wins.
+ if (prose.length > 0) {
+ const proseInner = prose.join('\n\n');
+ cssParts.push(
+ `@layer reset {\n@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}\n}`,
+ );
+ }
+ if (component.length > 0) {
+ const componentInner = component.join('\n\n');
+ const componentScope = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
+ // #3658: also emit attribute-specific rules so <Theme mode> can override color-scheme
+ const colorSchemeDecl = componentScope.includes('light-dark(')
+ ? ' :root { color-scheme: light dark; }\n html[data-theme="light"] { color-scheme: light; }\n html[data-theme="dark"] { color-scheme: dark; }\n\n'
+ : '';
+ cssParts.push(
+ `@layer astryx-theme {\n${colorSchemeDecl}${componentScope}\n}`,
+ );
+ }
+ // On-media rules (MediaTheme dark/light surface overrides)
+ if (_generateOnMediaCSS) {
+ const onMediaCss = _generateOnMediaCSS(resolvedTheme);
+ if (onMediaCss) {
+ cssParts.push(`@layer astryx-theme {\n${onMediaCss}\n}`);
+ }
+ }
+ if (cssParts.length === 0) {
+ logger.log('No overrides found — nothing to build.');
+ return null;
+ }
+ css = cssParts.join('\n\n') + '\n';
+ }
+
+ // Source path relative to cwd — used in @generated headers
+ const sourceRelative = path.relative(cwd, filePath);
+ const buildCommand = `astryx theme build ${sourceRelative}${options.out ? ' --out ' + path.relative(cwd, path.resolve(cwd, options.out)) : ''}`;
+
+ // Derive the default CSS name from the theme name so .css/.js/.d.ts
+ // share one scheme; an explicit --out still wins.
+ const baseName = themeDef.name;
+ const outPath = options.out
+ ? path.resolve(cwd, options.out)
+ : path.join(path.dirname(filePath), `${baseName}.css`);
+
+ const displayTheme = resolvedTheme || themeDef;
+ const tokenCount = displayTheme.tokens ? Object.keys(displayTheme.tokens).length : 0;
+ const componentCount = displayTheme.components ? Object.keys(displayTheme.components).length : 0;
+ const size = (Buffer.byteLength(css) / 1024).toFixed(1);
+
+ // Compute all output paths up front so we can validate them as a
+ // group BEFORE writing anything. Previously the CSS would be written
+ // first; if the JS write failed (e.g. ENOENT, permission), the CSS
+ // was left as orphaned half-built output. Stage-then-commit avoids
+ // that.
+ const outDir = path.dirname(outPath);
+ const jsPath = path.join(outDir, `${baseName}.js`);
+ const dtsPath = path.join(outDir, `${baseName}.d.ts`);
+
+ const iconInfo = extractIconInfo(filePath);
+
+ // Type augmentation .d.ts if theme has custom prop values. Computed
+ // before the main .d.ts so the latter can reference it (see below).
+ const augmentationSource = resolvedTheme || themeDef;
+ const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);
+ const variantsFileName = variantDecl ? `${baseName}.variants.d.ts` : null;
+ const variantDtsPath =
+ variantDecl && variantsFileName
+ ? path.join(outDir, variantsFileName)
+ : null;
+ const variantContent = variantDecl
+ ? generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl
+ : null;
+
+ // Generate all file contents in memory first. The main .d.ts references
+ // the variants file (when present) via a triple-slash directive so
+ // importing the theme also loads the custom-variant augmentations.
+ const cssContent = generatedHeader(sourceRelative, 'css', buildCommand) + css;
+ const jsContent = generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo);
+ const dtsContent = generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo, variantsFileName);
+
+ // Atomic-ish write: stage every file as `<dest>.tmp`, then rename
+ // each into place. If any stage step fails we clean up partials and
+ // exit; if a rename fails mid-way we still have the originals (or
+ // nothing) — never a half-built output set.
+ const writes = [
+ {dest: outPath, content: cssContent},
+ {dest: jsPath, content: jsContent},
+ {dest: dtsPath, content: dtsContent},
+ ];
+ if (variantDtsPath && variantContent) {
+ writes.push({dest: variantDtsPath, content: variantContent});
+ }
+
+ fs.mkdirSync(outDir, {recursive: true});
+ /** @type {Array<{tmp: string, dest: string}>} */
+ const staged = [];
+ try {
+ for (const w of writes) {
+ const tmp = `${w.dest}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, w.content);
+ staged.push({tmp, dest: w.dest});
+ }
+ for (const s of staged) {
+ fs.renameSync(s.tmp, s.dest);
+ }
+ } catch (err) {
+ // Roll back any temp files we managed to create.
+ for (const s of staged) {
+ try { fs.rmSync(s.tmp, {force: true}); } catch { /* best-effort */ }
+ }
+ const msg = `Failed to write theme outputs: ${/** @type {Error} */ (err).message}`;
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_WRITE_FAILED);
+ }
+
+ logger.log(`\n✓ ${path.relative(cwd, outPath)}`);
+ logger.log(` ${tokenCount} token overrides, ${componentCount} component overrides`);
+ logger.log(` ${size} KB`);
+ logger.log(`✓ ${path.relative(cwd, jsPath)}`);
+ logger.log(`✓ ${path.relative(cwd, dtsPath)}`);
+ if (variantDtsPath && variantDecl) {
+ const augCount = (variantDecl.match(/': true;/g) || []).length;
+ logger.log(`✓ ${path.relative(cwd, variantDtsPath)} (${augCount} type augmentations)`);
+ }
+
+ const relOutDir = path.relative(cwd, outDir) || '.';
+ const cssBase = path.basename(outPath, '.css');
+ const jsImport = importSpecifier(relOutDir, baseName);
+ const cssImport = importSpecifier(relOutDir, cssBase) + '.css';
+ const exportName = `${toIdentifier(baseName)}Theme`;
+ logger.log(`
+Install in your app (paths are relative to a file in src/ — adjust if yours lives elsewhere):
+
+ import { ${exportName} } from '${jsImport}';
+ import '${cssImport}';
+
+ <Theme theme={${exportName}}>
+ <App />
+ </Theme>
+
+Or with a <link> tag:
+
+ import { ${exportName} } from '${jsImport}';
+
+ <link rel="stylesheet" href="${cssImport}" />
+ <Theme theme={${exportName}}>
+ <App />
+ </Theme>
+`);
+
+ // Print font declaration warnings (derived from typography roles)
+ if (resolvedTheme && resolvedTheme.fonts && resolvedTheme.fonts.length > 0) {
+ logger.log(`\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`);
+ for (const font of resolvedTheme.fonts) {
+ logger.log(` ${font.family} — add to your document <head>:`);
+ logger.log(` <link rel="stylesheet" href="${font.url}" />`);
+ }
+ logger.log('');
+ }
+
+ return {
+ type: 'theme.build',
+ data: {
+ name: themeDef.name,
+ tokenCount,
+ componentCount,
+ sizeKB: parseFloat(size),
+ outputs: {
+ css: path.relative(cwd, outPath),
+ js: path.relative(cwd, jsPath),
+ dts: path.relative(cwd, dtsPath),
+ ...(variantDecl && variantDtsPath ? {variantsDts: path.relative(cwd, variantDtsPath)} : {}),
+ },
+ warnings: warningMessages,
+ },
+ };
+}
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
new file mode 100644
index 0000000000..e1795a0a01
--- /dev/null
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -0,0 +1,136 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Direct API tests for `themeBuild()` — the programmatic surface behind
+ * `astryx theme build` (`@astryxdesign/cli/api`).
+ *
+ * The CLI suites (cli/commands/build-theme.*.test.mjs) drive `registerTheme`
+ * end-to-end; these assert the API contract you get calling `themeBuild()` in
+ * code: the typed `theme.build` receipt (with files actually written to disk),
+ * that it honors the `cwd` option, stays SILENT under the default noopLogger,
+ * and returns `null` when there is nothing to build.
+ *
+ * `themeBuild` compiles via @astryxdesign/core's generator, so it needs a built
+ * core — the `node` project's globalSetup (vitest.global-setup.node.mjs) builds
+ * it once before workers fork.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {
+ generateThemeRulesSplit as mockGenerateThemeRulesSplit,
+ generateOnMediaCSS as mockGenerateOnMediaCSS,
+} from '@astryxdesign/core/theme';
+import {themeBuild} from './build.mjs';
+
+// `themeBuild` captures core's generator once at module load. Wrap the two
+// CSS-emitting exports in vi.fn (call-through by default) so the receipt tests
+// exercise the REAL generator, while the "nothing to build" test can force an
+// empty result for a single call — the only way to reach that branch, since
+// core's prose element defaults otherwise always ship a non-empty CSS block.
+vi.mock('@astryxdesign/core/theme', async importActual => {
+ const actual = /** @type {Record<string, unknown>} */ (await importActual());
+ return {
+ ...actual,
+ generateThemeRulesSplit: vi.fn(actual.generateThemeRulesSplit),
+ generateOnMediaCSS: vi.fn(actual.generateOnMediaCSS),
+ };
+});
+
+vi.setConfig({testTimeout: 30000});
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-build-api-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ // Clear call history only — do NOT restore, which would drop the vi.fn
+ // call-through implementations set up in the factory above.
+ vi.clearAllMocks();
+});
+
+describe('themeBuild() — receipt', () => {
+ it('compiles a minimal theme and returns a theme.build receipt with files on disk', async () => {
+ const themeFile = path.join(tmpDir, 'apitheme.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default { name: 'apitheme', tokens: { '--color-bg': '#0a0a0a' } };\n`,
+ );
+
+ // Resolve `file` against the cwd option (not process.cwd()).
+ const result = await themeBuild('apitheme.mjs', {}, {cwd: tmpDir});
+
+ expect(result).not.toBeNull();
+ expect(result?.type).toBe('theme.build');
+ expect(result?.data.name).toBe('apitheme');
+ expect(result?.data.sizeKB).toBeGreaterThan(0);
+
+ // Output paths are cwd-relative and derive from the theme name…
+ expect(result?.data.outputs.css).toBe('apitheme.css');
+ expect(result?.data.outputs.js).toBe('apitheme.js');
+ expect(result?.data.outputs.dts).toBe('apitheme.d.ts');
+ // …and every declared output actually exists on disk.
+ for (const rel of [
+ result?.data.outputs.css,
+ result?.data.outputs.js,
+ result?.data.outputs.dts,
+ ]) {
+ expect(fs.existsSync(path.join(tmpDir, /** @type {string} */ (rel)))).toBe(
+ true,
+ );
+ }
+ });
+
+ it('is silent by default (noopLogger) — no console output for a scripted caller', async () => {
+ const themeFile = path.join(tmpDir, 'quiet.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default { name: 'quiet', tokens: { '--color-bg': '#fff' } };\n`,
+ );
+
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const outSpy = vi
+ .spyOn(process.stdout, 'write')
+ .mockImplementation(() => true);
+
+ try {
+ const result = await themeBuild('quiet.mjs', {}, {cwd: tmpDir});
+ expect(result?.type).toBe('theme.build');
+ expect(logSpy).not.toHaveBeenCalled();
+ expect(warnSpy).not.toHaveBeenCalled();
+ expect(errSpy).not.toHaveBeenCalled();
+ expect(outSpy).not.toHaveBeenCalled();
+ } finally {
+ logSpy.mockRestore();
+ warnSpy.mockRestore();
+ errSpy.mockRestore();
+ outSpy.mockRestore();
+ }
+ });
+});
+
+describe('themeBuild() — nothing to build', () => {
+ it('returns null and writes nothing when the generator yields no CSS', async () => {
+ const themeFile = path.join(tmpDir, 'empty.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default { name: 'empty', tokens: {} };\n`,
+ );
+
+ // Force the generator to emit nothing for this one build (prose defaults
+ // otherwise always ship, so this branch is unreachable with real output).
+ mockGenerateThemeRulesSplit.mockReturnValueOnce({component: [], prose: []});
+ mockGenerateOnMediaCSS.mockReturnValueOnce('');
+
+ const result = await themeBuild('empty.mjs', {}, {cwd: tmpDir});
+
+ expect(result).toBeNull();
+ // Nothing written — the tmp dir still holds only the source fixture.
+ expect(fs.readdirSync(tmpDir)).toEqual(['empty.mjs']);
+ });
+});
diff --git a/packages/cli/cli/commands/build-theme.mjs b/packages/cli/cli/commands/build-theme.mjs
index 0a6673493d..f6581562c3 100644
--- a/packages/cli/cli/commands/build-theme.mjs
+++ b/packages/cli/cli/commands/build-theme.mjs
@@ -1,11 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file theme build command — Compile a defineTheme file to CSS
+ * @file theme command — Commander wiring for `astryx theme` (build/list/add).
*
- * Takes a theme file that uses defineTheme() and outputs:
- * - A CSS file with token overrides and component styles
- * - An updated JS module that references the built className
+ * 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.
*
* Usage:
* astryx theme build ./src/themes/ocean.ts
@@ -14,739 +17,14 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {pathToFileURL, fileURLToPath} from 'node:url';
+import {fileURLToPath} from 'node:url';
import {spawn} from 'node:child_process';
-import {createJiti} from 'jiti';
import {getCliInvocation} from '../../utils/package-manager.mjs';
-import {
- sanitizeName,
- PathSafetyError,
-} from '../../utils/path-safety.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 shared theme processing from core. `astryx theme build` MUST produce the
-// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
-// path: core's generator. There is no in-CLI fallback implementation — if this
-// import fails, the build fails (see the ERR_CORE_NOT_FOUND guard in the theme
-// action). A built, resolvable `@astryxdesign/core` is a hard requirement.
-// A built, resolvable `@astryxdesign/core` is a hard requirement. These are
-// populated from a dynamic import (a runtime boundary), so `any` is intentional.
-/** @type {any} */ let _defineTheme = null;
-/** @type {any} */ let _generateThemeRulesSplit = null;
-/** @type {any} */ let _generateOnMediaCSS = null;
-/** @type {any} */ let _coreImportError = null;
-try {
- const coreTheme = await import('@astryxdesign/core/theme');
- _defineTheme = coreTheme.defineTheme;
- _generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
- _generateOnMediaCSS = coreTheme.generateOnMediaCSS;
-} catch (e) {
- // Capture the reason so the theme action can surface a precise, actionable
- // error. We don't throw here: this module is imported eagerly by the CLI
- // entrypoint for every command, and a throw at load time would break
- // unrelated commands (the entry wraps loads in try/catch and degrades the
- // command to a stub). The hard failure happens when `theme build` runs.
- _coreImportError = e;
-}
-
-/**
- * Build a @generated attribution header for generated files.
- * @param {string} sourceFile - Relative path to the source theme file
- * @param {'css'|'js'|'ts'} lang - File language (determines comment syntax)
- * @param {string} [command] - The full CLI command used to generate this file
- */
-function generatedHeader(sourceFile, lang = 'js', command) {
- const timestamp = new Date().toISOString();
- const body = [
- `@generated by \`astryx theme build\` — do not edit manually.`,
- `Source: ${sourceFile}`,
- ];
- if (command) {
- body.push(`Command: ${command}`);
- }
- body.push(`Generated: ${timestamp}`);
- if (lang === 'css') {
- return `/*\n * ${body.join('\n * ')}\n */\n\n`;
- }
- return `/**\n * ${body.join('\n * ')}\n */\n\n`;
-}
-
-/**
- * Convert a theme name to a valid JS identifier.
- * e.g. 'default-minimal' → 'defaultMinimal', 'ocean' → 'ocean'
- * @param {string} name
- * @returns {string}
- */
-function toIdentifier(name) {
- return name.replace(/-([a-z])/g, (/** @type {string} */ _, /** @type {string} */ c) => c.toUpperCase());
-}
-
-/**
- * Import specifier for install/scaffold instructions. Drops a leading `src/`
- * from the cwd-relative dir (most consumers import from a file under src/) but
- * keeps the rest of the path (e.g. `themes/gothic`). Callers note the path is
- * relative to the consumer's file.
- * @param {string} relDir
- * @param {string} base
- * @returns {string}
- */
-function importSpecifier(relDir, base) {
- const normalized = relDir === '.' ? '' : relDir;
- const withinSrc = normalized.replace(/^src\/?/, '').replace(/\/+$/, '');
- return withinSrc ? `./${withinSrc}/${base}` : `./${base}`;
-}
-
-/**
- * Convert a kebab-case component name to PascalCase.
- * e.g. 'button' → 'Button', 'progress-bar' → 'ProgressBar', 'avatar-status-dot' → 'AvatarStatusDot'
- * @param {string} name
- * @returns {string}
- */
-function toPascalCase(name) {
- return name
- .split('-')
- .map((/** @type {string} */ part) => part.charAt(0).toUpperCase() + part.slice(1))
- .join('');
-}
-
-/**
- * Load known built-in values for a component's visual props from its .doc.mjs file.
- * Parses the type string (e.g. "'info' | 'warning' | 'error' | 'success'") to extract values.
- * Returns a map of { propName: string[] } for props that are visual (listed in theming targets).
- * @param {string} componentName
- * @returns {Promise<Record<string, string[]>>}
- */
-async function loadKnownValues(componentName) {
- // Resolve core src relative to the CLI package, not cwd (which may be a theme package)
- const cliDir = path.dirname(fileURLToPath(import.meta.url));
- const coreSrc = path.resolve(cliDir, '../../../core/src');
- if (!fs.existsSync(coreSrc)) return {};
- // Map component name to directory (e.g. 'banner' → 'Banner', 'dropdownmenu' → 'DropdownMenu')
- const dirs = fs.readdirSync(coreSrc, { withFileTypes: true })
- .filter(d => d.isDirectory())
- .map(d => d.name);
- const dir = dirs.find(d => d.toLowerCase() === componentName.toLowerCase()
- || d.toLowerCase().replace(/[^a-z]/g, '') === componentName.toLowerCase());
- if (!dir) return {};
-
- const docPath = path.join(coreSrc, dir, `${dir}.doc.mjs`);
- if (!fs.existsSync(docPath)) return {};
-
- try {
- const docModule = await import(pathToFileURL(docPath).href);
- const doc = docModule.docs;
- if (!doc?.theming?.targets) return {};
-
- // Collect all props — from doc.props or doc.components[].props
- const allProps = [];
- if (doc.props) allProps.push(...doc.props);
- if (doc.components) {
- for (const comp of doc.components) {
- if (comp.props) allProps.push(...comp.props);
- }
- }
- if (allProps.length === 0) return {};
-
- // Collect visual prop names from theming targets
- /** @type {Set<string>} */
- const visualProps = new Set();
- for (const target of doc.theming.targets) {
- if (target.visualProps) {
- for (const vp of target.visualProps) visualProps.add(vp);
- }
- }
-
- // Extract values from prop type strings
- /** @type {Record<string, string[]>} */
- const result = {};
- for (const prop of allProps) {
- if (!visualProps.has(prop.name)) continue;
- if (!prop.type || typeof prop.type !== 'string') continue;
-
- // Parse union type: "'info' | 'warning' | 'error' | 'success'" → ['info', 'warning', 'error', 'success']
- const matches = prop.type.match(/'([^']+)'/g);
- if (matches) {
- result[prop.name] = matches.map((/** @type {string} */ m) => m.replace(/'/g, ''));
- }
- }
- return result;
- } catch {
- return {};
- }
-}
-
-// Cache for loaded known values
-/** @type {Map<string, Record<string, string[]>>} */
-const _knownValuesCache = new Map();
-/**
- * @param {string} componentName
- * @returns {Promise<Record<string, string[]>>}
- */
-async function getKnownValues(componentName) {
- if (!_knownValuesCache.has(componentName)) {
- _knownValuesCache.set(componentName, await loadKnownValues(componentName));
- }
- return _knownValuesCache.get(componentName) ?? {};
-}
-
-/**
- * Resolve `@astryxdesign/core`'s package root relative to the CLI package. Core
- * and the CLI ship as siblings (`@astryxdesign/core`, `@astryxdesign/cli`), so
- * `../../../core` from `src/commands/` reaches core whether installed from npm
- * or run inside the monorepo. Returns null if it can't be found.
- */
-function resolveCoreRoot() {
- const cliDir = path.dirname(fileURLToPath(import.meta.url));
- const coreRoot = path.resolve(cliDir, '../../../core');
- return fs.existsSync(coreRoot) ? coreRoot : null;
-}
-
-/**
- * Read the type declarations `@astryxdesign/core/<Component>` exposes so we can
- * check whether a given augmentation-target interface actually exists before
- * generating a module augmentation against it.
- *
- * Reads the shipped `dist/<Component>/index.d.ts` (what a consumer's TypeScript
- * actually sees), falling back to the `src/<Component>/index.ts` in the
- * monorepo. Returns the file contents, or '' if nothing is found.
- */
-/** @type {Map<string, string>} */
-const _componentDeclCache = new Map();
-/**
- * @param {string} pascalName
- * @returns {string}
- */
-function readComponentDeclarations(pascalName) {
- if (_componentDeclCache.has(pascalName)) {
- return _componentDeclCache.get(pascalName) ?? '';
- }
- let contents = '';
- const coreRoot = resolveCoreRoot();
- if (coreRoot) {
- const candidates = [
- path.join(coreRoot, 'dist', pascalName, 'index.d.ts'),
- path.join(coreRoot, 'src', pascalName, 'index.ts'),
- ];
- for (const file of candidates) {
- try {
- if (fs.existsSync(file)) {
- contents = fs.readFileSync(file, 'utf-8');
- break;
- }
- } catch {
- // ignore and try the next candidate
- }
- }
- }
- _componentDeclCache.set(pascalName, contents);
- return contents;
-}
-
-/**
- * Determine whether `@astryxdesign/core/<Component>` exports an interface named
- * `interfaceName` that can be augmented via module augmentation.
- *
- * Only interfaces are extension points — closed literal-union types (e.g.
- * `HeadingType`, `ButtonSize`) are NOT augmentable, so a generated augmentation
- * against them is dead code. We check that the name is exported (directly or
- * re-exported) as a type/interface.
- * @param {string} pascalName
- * @param {string} interfaceName
- * @returns {boolean}
- */
-function componentHasAugmentableInterface(pascalName, interfaceName) {
- const decl = readComponentDeclarations(pascalName);
- if (!decl) return false;
- // Word-boundary match so `ButtonVariantMap` doesn't match `XButtonVariantMap`.
- const re = new RegExp(`\\b${interfaceName}\\b`);
- return re.test(decl);
-}
-
-/**
- * Generate TypeScript declaration content with module augmentation for custom
- * component prop values found in the theme's `components` keys. Reads known
- * values from doc files to filter out base prop values.
- *
- * Interface naming convention: PascalCase(component) + PascalCase(prop) + Map
- * banner + status → BannerStatusMap
- * button + variant → ButtonVariantMap
- *
- * An augmentation is only emitted when `@astryxdesign/core/<Component>` actually
- * exports a matching interface. Props backed by closed literal-union types
- * (e.g. Button `size`, Heading `type`/`level`) have no augmentation point, so
- * generating a `declare module` block for them would be dead code — those are
- * skipped.
- *
- * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef - Theme definition (resolved by defineTheme)
- * @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed
- */
-async function generateVariantDeclarationsAsync(themeDef) {
- if (!themeDef.components || Object.keys(themeDef.components).length === 0) {
- return null;
- }
-
- // Collect custom values: { component: { prop: [value, ...] } }
- /** @type {Record<string, Record<string, Set<string>>>} */
- const customValues = {};
-
- for (const [component, rules] of Object.entries(themeDef.components)) {
- const knownForComponent = await getKnownValues(component);
-
- for (const key of Object.keys(rules)) {
- if (key === 'base') continue;
-
- const pairs = key.split('+');
- for (const pair of pairs) {
- const colonIdx = pair.indexOf(':');
- if (colonIdx === -1) continue;
- const prop = pair.slice(0, colonIdx);
- const value = pair.slice(colonIdx + 1);
-
- // Skip known built-in values
- const knownForProp = knownForComponent[prop];
- if (knownForProp && knownForProp.includes(value)) continue;
-
- if (!customValues[component]) customValues[component] = {};
- if (!customValues[component][prop]) customValues[component][prop] = new Set();
- customValues[component][prop].add(value);
- }
- }
- }
-
- // Check if we found any custom values
- const hasCustom = Object.values(customValues).some(
- props => Object.values(props).some(values => values.size > 0)
- );
- if (!hasCustom) return null;
-
- const sections = ['// Generated by astryx theme build', 'export {};', ''];
-
- for (const [component, props] of Object.entries(customValues)) {
- for (const [prop, values] of Object.entries(props)) {
- if (values.size === 0) continue;
-
- const pascal = toPascalCase(component);
- const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
- const modulePath = `@astryxdesign/core/${pascal}`;
- const interfaceName = `${pascal}${propPascal}Map`;
-
- // Only augment interfaces that actually exist as an extension point in
- // core. Props backed by closed literal-union types (e.g. Button `size`,
- // Heading `type`/`level`) have no `*Map` interface — a `declare module`
- // block against a non-existent interface just creates a new, unused
- // interface and never extends the component's prop union, so skip it.
- if (!componentHasAugmentableInterface(pascal, interfaceName)) continue;
-
- sections.push(`declare module '${modulePath}' {`);
- sections.push(` interface ${interfaceName} {`);
- for (const v of values) {
- sections.push(` '${v}': true;`);
- }
- sections.push(' }');
- sections.push('}');
- sections.push('');
- }
- }
-
- // If every custom value targeted a non-augmentable prop, there's nothing to
- // emit beyond the header — return null so no `.variants.d.ts` is written.
- const hasEmittedAugmentation = sections.some(line =>
- line.startsWith('declare module'),
- );
- if (!hasEmittedAugmentation) return null;
-
- return sections.join('\n');
-}
-
-/**
- * Resolve a token value — [light, dark] tuple becomes light-dark()
- * @param {unknown} value
- * @returns {unknown}
- */
-function resolveTokenValue(value) {
- if (Array.isArray(value)) {
- return `light-dark(${value[0]}, ${value[1]})`;
- }
- return value;
-}
-
-// Theme @scope selector helpers. Keep the `astryx` literal in sync with
-// packages/core/src/naming.ts (NAMESPACE) and generateThemeRules.ts.
-// Theme scopes to data-astryx-theme; the static build path must match.
-const themeScopeStart = (/** @type {string} */ name) => `[data-astryx-theme="${name}"]`;
-const THEME_SCOPE_TO = `[data-astryx-theme]`;
-
-/**
- * Import a theme module using jiti and find the defineTheme() result.
- * Returns the resolved DefinedTheme object.
- * @param {string} filePath
- * @returns {Promise<any>}
- */
-async function importThemeModule(filePath) {
- const jiti = createJiti(import.meta.url, {
- moduleCache: false,
- jsx: true,
- });
-
- const mod = await jiti.import(filePath, {default: true});
-
- if (isThemeObject(mod)) return mod;
-
- if (mod && typeof mod === 'object') {
- for (const value of Object.values(mod)) {
- if (isThemeObject(value)) return value;
- }
- }
-
- throw new Error(
- `Could not find a defineTheme() result in ${filePath}.\n` +
- `Expected an export like: export const myTheme = defineTheme({ name: '...', tokens: {...} })`,
- );
-}
-
-/**
- * @param {any} value
- * @returns {boolean}
- */
-function isThemeObject(value) {
- return (
- value &&
- typeof value === 'object' &&
- typeof value.name === 'string' &&
- value.tokens &&
- typeof value.tokens === 'object'
- );
-}
-
-/**
- * Extract the theme definition from a JS/TS file.
- * Tries jiti first (full TS support), falls back to regex+eval.
- * @param {string} filePath
- * @returns {Promise<any>}
- */
-async function extractThemeDefinition(filePath) {
- try {
- return await importThemeModule(filePath);
- } catch (jitiError) {
- try {
- return extractThemeDefinitionLegacy(filePath);
- } catch {
- const je = /** @type {Error} */ (jitiError);
- throw new Error(
- `Failed to load theme from ${filePath}: ${je.message}\n` +
- `Make sure all imports in the theme file are resolvable.`,
- );
- }
- }
-}
-
-/**
- * Fallback extraction via regex + eval.
- * Only works for plain object literals — can't follow imports or variables.
- * @param {string} filePath
- * @returns {any}
- */
-function extractThemeDefinitionLegacy(filePath) {
- const content = fs.readFileSync(filePath, 'utf8');
-
- const defineMatch = content.match(/defineTheme\s*\(\s*({[\s\S]*?})\s*\)/);
- if (!defineMatch) {
- const defaultMatch = content.match(/export\s+default\s+({[\s\S]*?});/);
- if (!defaultMatch) {
- throw new Error(
- `Could not find defineTheme() call or default export in ${filePath}.\n` +
- `Expected: defineTheme({ name: '...', tokens: {...} })`,
- );
- }
-
- return eval(`(${defaultMatch[1]})`);
- }
-
- let objStr = defineMatch[1];
- objStr = objStr.replace(/\s+as\s+const/g, '');
- objStr = objStr.replace(/icons:\s*[a-zA-Z_][a-zA-Z0-9_]*/g, 'icons: undefined');
-
- try {
-
- return eval(`(${objStr})`);
- } catch (e) {
- const err = /** @type {Error} */ (e);
- throw new Error(
- `Failed to parse theme definition in ${filePath}: ${err.message}\n` +
- `Make sure the defineTheme() argument is a plain object literal.`,
- {cause: e},
- );
- }
-}
-
-/**
- * Extract icon import info from a theme source file.
- * Returns { importPath, exportName } or null if no icons.
- *
- * Looks for patterns like:
- * import { defaultIconRegistry } from './icons';
- * icons: defaultIconRegistry,
- * @param {string} filePath
- * @returns {{exportName: string, importPath: string} | null}
- */
-function extractIconInfo(filePath) {
- const content = fs.readFileSync(filePath, 'utf8');
-
- // Find the icons field in defineTheme
- const iconsMatch = content.match(/icons:\s*([a-zA-Z_][a-zA-Z0-9_]*)/);
- if (!iconsMatch) return null;
-
- const varName = /** @type {string} */ (iconsMatch[1]);
-
- // Find the import for that variable
- const importRegex = new RegExp(
- `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,
- );
- const importMatch = content.match(importRegex);
- if (!importMatch) return null;
-
- return {
- exportName: varName,
- importPath: /** @type {string} */ (importMatch[1]),
- };
-}
-
-/**
- * Generate a minimal JS module for a built theme.
- * Includes the theme name, marker, and re-exports the icon registry.
- * All styling is in the CSS file.
- * @param {any} themeDef
- * @param {{exportName: string, importPath: string} | null} iconInfo
- * @returns {string}
- */
-function generateBuiltModule(themeDef, iconInfo) {
- const iconImport = iconInfo
- ? `import { ${iconInfo.exportName} } from '${iconInfo.importPath}';\n`
- : '';
- const iconsField = iconInfo ? ` icons: ${iconInfo.exportName},` : '';
- const iconReExport = iconInfo
- ? `\nexport { ${iconInfo.exportName} };\n`
- : '';
-
- // Resolve token values — tuples become light-dark() strings
- /** @type {Record<string, unknown>} */
- const resolvedTokens = {};
- if (themeDef.tokens) {
- for (const [key, value] of Object.entries(themeDef.tokens)) {
- resolvedTokens[key] = resolveTokenValue(value);
- }
- }
-
- const tokensStr = JSON.stringify(resolvedTokens, null, 2)
- .split('\n')
- .map((line, i) => (i === 0 ? line : ' ' + line))
- .join('\n');
-
- return `${iconImport}/**
- * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
- * Import the CSS file alongside this module:
- *
- * import { ${toIdentifier(themeDef.name)}Theme } from './${themeDef.name}';
- * import './${themeDef.name}.css';
- */
-export const ${toIdentifier(themeDef.name)}Theme = {
- name: '${themeDef.name}',
- __built: true,
- tokens: ${tokensStr},
-${iconsField}
-};
-${iconReExport}`;
-}
-
-/**
- * Generate TypeScript declarations for a built theme module.
- * @param {any} themeDef
- * @param {{exportName: string, importPath: string} | null} iconInfo
- * @param {string | null} variantsFileName
- * @returns {string}
- */
-function generateBuiltTypes(themeDef, iconInfo, variantsFileName) {
- const iconType = iconInfo
- ? `import type { IconRegistry } from '@astryxdesign/core/Icon';
-export declare const ${iconInfo.exportName}: IconRegistry;
-`
- : '';
- // Pull in the generated custom-variant augmentations so that importing the
- // theme's types also loads the module augmentations (otherwise the
- // `.variants.d.ts` is emitted but never referenced, and the custom variants
- // never widen the component prop unions for consumers).
- const variantsRef = variantsFileName
- ? `/// <reference path="./${variantsFileName}" />
-`
- : '';
- return `${variantsRef}import type { DefinedTheme } from '@astryxdesign/core/theme';
-${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedTheme;
-`;
-}
-
-// =============================================================================
-// Component validation
-// =============================================================================
-
-/**
- * Known Astryx component names and their visual props.
- * Used to warn on typos in defineTheme component overrides.
- * @type {Record<string, string[]>}
- */
-const KNOWN_COMPONENTS = {
- appshell: ['position'],
- aspectratio: [],
- avatar: ['size'],
- badge: ['variant', 'color'],
- banner: ['container', 'status'],
- breadcrumbs: ['variant'],
- button: ['variant', 'size'],
- calendar: [],
- card: ['variant'],
- center: [],
- checkboxinput: [],
- collapsible: [],
- dateinput: [],
- dialog: ['variant', 'position'],
- divider: ['variant', 'orientation'],
- dropdownmenu: [],
- 'empty-state': [],
- field: [],
- formlayout: [],
- grid: ['align'],
- heading: ['level'],
- icon: ['size', 'color'],
- kbd: [],
- layer: [],
- layout: [],
- link: ['color'],
- list: ['type', 'density'],
- mobilenav: [],
- moremenu: [],
- navicon: [],
- numberinput: [],
- pagination: ['variant'],
- progressbar: ['variant', 'size'],
- radiolist: ['orientation'],
- section: ['variant'],
- selector: ['type', 'size', 'color'],
- sidenav: [],
- skeleton: [],
- slider: ['orientation'],
- spinner: ['size'],
- stack: [],
- statusdot: ['variant', 'size'],
- switch: [],
- table: [],
- tablist: ['type'],
- text: ['type', 'color'],
- textarea: [],
- textinput: [],
- timeinput: [],
- token: ['color'],
- tokenizer: [],
- topnav: [],
- typeahead: ['type', 'size', 'color'],
-};
-
-/**
- * Validate component overrides in a theme definition.
- * Warns on unknown component names and unknown prop names.
- * Returns array of warning strings.
- * @param {{components?: Record<string, Record<string, unknown>>}} themeDef
- * @returns {string[]}
- */
-function validateComponentOverrides(themeDef) {
- /** @type {string[]} */
- const warnings = [];
- if (!themeDef.components) return warnings;
-
- for (const [component, rules] of Object.entries(themeDef.components)) {
- // Check component name
- if (!(component in KNOWN_COMPONENTS)) {
- const similar = Object.keys(KNOWN_COMPONENTS)
- .filter((k) => {
- if (k.includes(component) || component.includes(k)) return true;
- // Levenshtein distance 1-2 for short names
- if (Math.abs(k.length - component.length) <= 2) {
- let diff = 0;
- const longer = k.length >= component.length ? k : component;
- const shorter = k.length < component.length ? k : component;
- let j = 0;
- for (let i = 0; i < longer.length && diff <= 2; i++) {
- if (longer[i] !== shorter[j]) diff++;
- else j++;
- }
- diff += shorter.length - j;
- return diff <= 2;
- }
- return false;
- })
- .slice(0, 3);
- const hint = similar.length > 0 ? ` Did you mean: ${similar.join(', ')}?` : '';
- warnings.push(`Unknown component "${component}".${hint}`);
- continue;
- }
-
- // Check prop names in prop:value keys
- const knownProps = KNOWN_COMPONENTS[component];
- for (const key of Object.keys(rules)) {
- if (key === 'base') continue;
-
- // Parse prop:value pairs (e.g. 'variant:secondary' or 'variant:destructive+size:sm')
- const pairs = key.split('+');
- for (const pair of pairs) {
- const [prop] = pair.split(':');
- if (prop && !knownProps.includes(prop)) {
- const hint =
- knownProps.length > 0
- ? ` Known props: ${knownProps.join(', ')}`
- : ' This component has no variant props.';
- warnings.push(
- `Unknown prop "${prop}" on component "${component}".${hint}`,
- );
- }
- }
- }
- }
-
- return warnings;
-}
-
-/**
- * Validate that themes don't set private (--_*) CSS custom properties directly.
- * Private vars are internal implementation details managed by the derived var
- * expansion pipeline. Theme authors should write standard CSS properties
- * (e.g. borderRadius, padding) instead.
- *
- * Returns array of error strings.
- * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef
- * @returns {string[]}
- */
-function validatePrivateVars(themeDef) {
- /** @type {string[]} */
- const errors = [];
- if (!themeDef.components) return errors;
-
- for (const [component, rules] of Object.entries(themeDef.components)) {
- for (const [key, styles] of Object.entries(rules)) {
- for (const prop of Object.keys(styles)) {
- if (typeof prop === 'string' && prop.startsWith('--_')) {
- errors.push(
- `Component "${component}" (${key}) sets private var "${prop}". ` +
- `Private vars (--_*) are internal — use standard CSS properties ` +
- `(e.g. borderRadius, padding) instead. The pipeline expands them automatically.`,
- );
- }
- }
- }
- }
-
- return errors;
-}
+import {themeBuild, importSpecifier} from '../../api/theme/build/build.mjs';
/**
* Path to this CLI's real entry (bin/astryx.mjs), resolved from this module's
@@ -901,274 +179,25 @@ export function registerTheme(program) {
return;
}
- if (!json) humanLog(`\nBuilding theme from ${path.relative(process.cwd(), filePath)}...`);
-
- // Extract theme definition
- let themeDef;
+ // Non-watch: delegate to the API compiler. The logger keeps human output
+ // byte-identical — humanLog → stdout, console.warn/error → stderr — while
+ // --json mode uses a no-op logger so only the envelope reaches stdout. The
+ // "Building theme from" line, the ✓/warning lines, and the install
+ // instructions are all emitted from inside themeBuild via this logger.
+ /** @type {{log: (m?: string) => void, warn: (m?: string) => void, error: (m?: string) => void}} */
+ const logger = json
+ ? {log() {}, warn() {}, error() {}}
+ : {
+ log: humanLog,
+ warn: m => console.warn(m),
+ error: m => console.error(m),
+ };
try {
- themeDef = await extractThemeDefinition(filePath);
+ const result = await themeBuild(file, {out: options.out}, {cwd: process.cwd(), logger});
+ if (json && result) jsonOut(result);
} catch (e) {
- const err = /** @type {Error} */ (e);
- cliError(err.message, {code: ERROR_CODES.ERR_THEME_LOAD});
- return;
- }
-
- if (!themeDef.name) {
- cliError('Theme must have a name property.', {code: ERROR_CODES.ERR_THEME_INVALID});
- return;
- }
-
- // Path-safety: the theme name is used to derive output filenames
- // (e.g. `${name}.css`, `${name}.js`). Reject names containing path
- // separators or traversal markers — `../../escaped` would otherwise
- // write JS modules outside the input directory.
- try {
- sanitizeName(themeDef.name, {label: 'theme name'});
- } catch (err) {
- if (err instanceof PathSafetyError) {
- cliError(err.message, {code: ERROR_CODES.ERR_PATH_TRAVERSAL});
- return;
- }
- throw err;
- }
-
- // Validate component overrides
- const warnings = validateComponentOverrides(themeDef);
- const warningMessages = [];
- for (const w of warnings) {
- warningMessages.push(w);
- if (!json) console.warn(` ⚠ ${w}`);
- }
-
- // Validate no private vars are set directly
- const privateVarErrors = validatePrivateVars(themeDef);
- for (const e of privateVarErrors) {
- warningMessages.push(e);
- if (!json) console.error(` ✗ ${e}`);
- }
- if (privateVarErrors.length > 0 && !json) {
- console.error(`\n ${privateVarErrors.length} private var error(s). Use standard CSS properties instead.`);
- }
-
- // Generate CSS via core's shared generator — the SINGLE source of truth.
- // `astryx theme build` and the `<Theme>` runtime MUST emit identical CSS, so
- // there is exactly one generation path: @astryxdesign/core/theme. If core could not
- // be imported, fail hard rather than silently producing divergent output.
- if (!_defineTheme || !_generateThemeRulesSplit) {
- cliError(
- 'Could not load @astryxdesign/core/theme — `astryx theme build` requires a ' +
- 'built, resolvable @astryxdesign/core so it emits the same CSS as the ' +
- 'runtime <Theme>. Build @astryxdesign/core first (e.g. `pnpm -F @astryxdesign/core ' +
- 'build`)' +
- (_coreImportError ? `.\n Import error: ${_coreImportError.message}` : '.'),
- {code: ERROR_CODES.ERR_CORE_NOT_FOUND},
- );
- }
-
- let css;
- let resolvedTheme;
- {
- // jiti returns an already-resolved theme; legacy eval returns raw input.
- const isAlreadyResolved =
- !themeDef.typography && !themeDef.motion && !themeDef.radius;
- if (isAlreadyResolved) {
- resolvedTheme = themeDef;
- } else {
- resolvedTheme = _defineTheme({
- name: themeDef.name,
- typography: themeDef.typography,
- motion: themeDef.motion,
- radius: themeDef.radius,
- tokens: themeDef.tokens,
- components: themeDef.components,
- });
- }
- const scopeSelector = themeScopeStart(themeDef.name);
- const scopeTo = THEME_SCOPE_TO;
-
- const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
- const cssParts = [];
- // Prose element defaults always ship — the `<Theme>` runtime
- // (generateThemeCSS) always emits them, so the build must too, or the
- // CLI output would diverge from runtime. They go in @layer reset
- // (zero-specificity :where()) so component/Markdown StyleX always wins.
- if (prose.length > 0) {
- const proseInner = prose.join('\n\n');
- cssParts.push(
- `@layer reset {\n@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}\n}`,
- );
- }
- if (component.length > 0) {
- const componentInner = component.join('\n\n');
- const componentScope = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
- // #3658: also emit attribute-specific rules so <Theme mode> can override color-scheme
- const colorSchemeDecl = componentScope.includes('light-dark(')
- ? ' :root { color-scheme: light dark; }\n html[data-theme="light"] { color-scheme: light; }\n html[data-theme="dark"] { color-scheme: dark; }\n\n'
- : '';
- cssParts.push(
- `@layer astryx-theme {\n${colorSchemeDecl}${componentScope}\n}`,
- );
- }
- // On-media rules (MediaTheme dark/light surface overrides)
- if (_generateOnMediaCSS) {
- const onMediaCss = _generateOnMediaCSS(resolvedTheme);
- if (onMediaCss) {
- cssParts.push(`@layer astryx-theme {\n${onMediaCss}\n}`);
- }
- }
- if (cssParts.length === 0) {
- if (!json) humanLog('No overrides found — nothing to build.');
- return;
- }
- css = cssParts.join('\n\n') + '\n';
- }
-
- // Source path relative to cwd — used in @generated headers
- const sourceRelative = path.relative(process.cwd(), filePath);
- const buildCommand = `astryx theme build ${sourceRelative}${options.out ? ' --out ' + path.relative(process.cwd(), path.resolve(process.cwd(), options.out)) : ''}`;
-
- // Derive the default CSS name from the theme name so .css/.js/.d.ts
- // share one scheme; an explicit --out still wins.
- const baseName = themeDef.name;
- const outPath = options.out
- ? path.resolve(process.cwd(), options.out)
- : path.join(path.dirname(filePath), `${baseName}.css`);
-
- const displayTheme = resolvedTheme || themeDef;
- const tokenCount = displayTheme.tokens ? Object.keys(displayTheme.tokens).length : 0;
- const componentCount = displayTheme.components ? Object.keys(displayTheme.components).length : 0;
- const size = (Buffer.byteLength(css) / 1024).toFixed(1);
-
- // Compute all output paths up front so we can validate them as a
- // group BEFORE writing anything. Previously the CSS would be written
- // first; if the JS write failed (e.g. ENOENT, permission), the CSS
- // was left as orphaned half-built output. Stage-then-commit avoids
- // that.
- const outDir = path.dirname(outPath);
- const jsPath = path.join(outDir, `${baseName}.js`);
- const dtsPath = path.join(outDir, `${baseName}.d.ts`);
-
- const iconInfo = extractIconInfo(filePath);
-
- // Type augmentation .d.ts if theme has custom prop values. Computed
- // before the main .d.ts so the latter can reference it (see below).
- const augmentationSource = resolvedTheme || themeDef;
- const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);
- const variantsFileName = variantDecl ? `${baseName}.variants.d.ts` : null;
- const variantDtsPath =
- variantDecl && variantsFileName
- ? path.join(outDir, variantsFileName)
- : null;
- const variantContent = variantDecl
- ? generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl
- : null;
-
- // Generate all file contents in memory first. The main .d.ts references
- // the variants file (when present) via a triple-slash directive so
- // importing the theme also loads the custom-variant augmentations.
- const cssContent = generatedHeader(sourceRelative, 'css', buildCommand) + css;
- const jsContent = generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo);
- const dtsContent = generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo, variantsFileName);
-
- // Atomic-ish write: stage every file as `<dest>.tmp`, then rename
- // each into place. If any stage step fails we clean up partials and
- // exit; if a rename fails mid-way we still have the originals (or
- // nothing) — never a half-built output set.
- const writes = [
- {dest: outPath, content: cssContent},
- {dest: jsPath, content: jsContent},
- {dest: dtsPath, content: dtsContent},
- ];
- if (variantDtsPath && variantContent) {
- writes.push({dest: variantDtsPath, content: variantContent});
- }
-
- fs.mkdirSync(outDir, {recursive: true});
- /** @type {Array<{tmp: string, dest: string}>} */
- const staged = [];
- try {
- for (const w of writes) {
- const tmp = `${w.dest}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, w.content);
- staged.push({tmp, dest: w.dest});
- }
- for (const s of staged) {
- fs.renameSync(s.tmp, s.dest);
- }
- } catch (err) {
- // Roll back any temp files we managed to create.
- for (const s of staged) {
- try { fs.rmSync(s.tmp, {force: true}); } catch { /* best-effort */ }
- }
- const msg = `Failed to write theme outputs: ${/** @type {Error} */ (err).message}`;
- cliError(msg, {code: ERROR_CODES.ERR_WRITE_FAILED});
- return;
- }
-
- if (!json) {
- humanLog(`\n✓ ${path.relative(process.cwd(), outPath)}`);
- humanLog(` ${tokenCount} token overrides, ${componentCount} component overrides`);
- humanLog(` ${size} KB`);
- humanLog(`✓ ${path.relative(process.cwd(), jsPath)}`);
- humanLog(`✓ ${path.relative(process.cwd(), dtsPath)}`);
- if (variantDtsPath && variantDecl) {
- const augCount = (variantDecl.match(/': true;/g) || []).length;
- humanLog(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
- }
- }
-
- if (json) {
- return jsonOut({
- type: 'theme.build',
- data: {
- name: themeDef.name,
- tokenCount,
- componentCount,
- sizeKB: parseFloat(size),
- outputs: {
- css: path.relative(process.cwd(), outPath),
- js: path.relative(process.cwd(), jsPath),
- dts: path.relative(process.cwd(), dtsPath),
- ...(variantDecl && variantDtsPath ? {variantsDts: path.relative(process.cwd(), variantDtsPath)} : {}),
- },
- warnings: warningMessages,
- },
- });
- }
-
- const relOutDir = path.relative(process.cwd(), outDir) || '.';
- const cssBase = path.basename(outPath, '.css');
- const jsImport = importSpecifier(relOutDir, baseName);
- const cssImport = importSpecifier(relOutDir, cssBase) + '.css';
- const exportName = `${toIdentifier(baseName)}Theme`;
- humanLog(`
-Install in your app (paths are relative to a file in src/ — adjust if yours lives elsewhere):
-
- import { ${exportName} } from '${jsImport}';
- import '${cssImport}';
-
- <Theme theme={${exportName}}>
- <App />
- </Theme>
-
-Or with a <link> tag:
-
- import { ${exportName} } from '${jsImport}';
-
- <link rel="stylesheet" href="${cssImport}" />
- <Theme theme={${exportName}}>
- <App />
- </Theme>
-`);
-
- // Print font declaration warnings (derived from typography roles)
- if (resolvedTheme && resolvedTheme.fonts && resolvedTheme.fonts.length > 0) {
- humanLog(`\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`);
- for (const font of resolvedTheme.fonts) {
- humanLog(` ${font.family} — add to your document <head>:`);
- humanLog(` <link rel="stylesheet" href="${font.url}" />`);
- }
- humanLog('');
+ const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
+ cliError(err.message, {suggestions: err.suggestions, code: err.code});
}
});
@@ -1272,4 +301,3 @@ This is your copy of the ${displayName} theme — edit ${entry} to make it your
`);
});
}
-
diff --git a/packages/cli/types/api.d.ts b/packages/cli/types/api.d.ts
index afcc6d0894..6b8306d2a4 100644
--- a/packages/cli/types/api.d.ts
+++ b/packages/cli/types/api.d.ts
@@ -61,6 +61,7 @@ import type {
} from './upgrade';
import type {BlogListResponse, BlogDetailResponse} from './blog';
import type {InitRunResponse, InitRemoveResponse} from './init';
+import type {ThemeBuildResponse} from './theme';
import type {Suggestion} from './base';
/** Structured API error with a stable machine-readable code. */
@@ -379,3 +380,17 @@ export declare function init(
options?: InitOptions,
ctx?: {cwd?: string},
): Promise<InitRunResponse | InitRemoveResponse>;
+
+// ── Theme build ──────────────────────────────────────────────────────
+
+/**
+ * Compile a defineTheme file to CSS + JS + .d.ts (and an optional
+ * `.variants.d.ts`). Writes the outputs and returns a `theme.build` receipt,
+ * or `null` when the theme produced no CSS (nothing to build). Throws
+ * AstryxError on failure. `out` overrides the output CSS path.
+ */
+export declare function themeBuild(
+ file: string,
+ options?: {out?: string},
+ ctx?: {cwd?: string},
+): Promise<ThemeBuildResponse | null>;