Skip to content

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

TypeScript

feat(cli): `astryx theme build` takes any number of themes — one invocation, identical bytes (#5121)

Cindy Zhang71781fc039c9
diff --git a/.changeset/cli-theme-build-multi.md b/.changeset/cli-theme-build-multi.md
new file mode 100644
index 0000000000..6a0e54f340
--- /dev/null
+++ b/.changeset/cli-theme-build-multi.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx theme build` takes any number of theme files — `astryx theme build themes/*.ts` compiles them all in one process, so an app with several themes no longer hand-rolls a loop that re-enters the CLI once per theme. Outputs are byte-identical to the serial invocations; the run stops at the first failure and names the theme that failed. The CLI's Node floor (>=22.13) is now declared in `engines`, so a package manager can enforce it at install instead of the build failing later.
+
+@cixzhang
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 991d7d560f..fdde4d4583 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -415,6 +415,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |
| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |
| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
+| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
| `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. |
diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjs
index fd84d60232..438e0c3b95 100644
--- a/packages/cli/api/theme/theme.type.mjs
+++ b/packages/cli/api/theme/theme.type.mjs
@@ -10,6 +10,7 @@
* ------------------------------------------------------------------
* xds --json theme build <file> -> theme.build
* xds --json theme build <file> --check -> theme.build.check
+ * xds --json theme build <a> <b> … -> theme.build.batch
* xds --json theme list -> theme.list
* xds --json theme add <slug> -> theme.add
* xds --json theme template -> theme.template
@@ -35,6 +36,16 @@
* @property {{name: string, upToDate: boolean, stale: Array<{path: string, reason: 'missing' | 'outdated'}>, checked: string[]}} data
*/
+/**
+ * xds --json theme build <a> <b> … — several themes in one invocation. Each
+ * result carries the file as it was passed and the receipt a single-file build
+ * would have returned (null when that theme produced no CSS). One file still
+ * returns the bare theme.build / theme.build.check envelope.
+ * @typedef {object} ThemeBuildBatchResponse
+ * @property {'theme.build.batch'} type
+ * @property {{count: number, results: Array<{file: string, receipt: ThemeBuildResponse | ThemeBuildCheckResponse | null}>}} data
+ */
+
/**
* A single theme entry as surfaced by `theme list`.
* @typedef {object} ThemeListEntry
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index e78beb22a4..5f48247991 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -17,6 +17,12 @@
* Usage:
* astryx theme build ./src/themes/ocean.ts
* astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css
+ * astryx theme build ./src/themes/*.ts
+ *
+ * `build` takes one or more theme files. Each is compiled by the same
+ * single-file API call, in argument order, in one process — so the outputs are
+ * byte-identical to running the CLI once per theme, and the first failure stops
+ * the run exactly as a shell loop under `set -e` would.
*/
import * as fs from 'node:fs';
@@ -80,66 +86,80 @@ function runThemeBuildOnceChild(file, options) {
}
/**
- * Watch a theme file and rebuild on change. Runs an initial build, then
- * rebuilds (debounced) whenever the file changes, until interrupted with
- * Ctrl-C. Each rebuild runs in a child process so a build error (which the
- * single-build path reports via a hard exit) is contained and the watcher
- * keeps running.
+ * Watch theme files and rebuild on change. Runs an initial build of each, then
+ * rebuilds (debounced) the file that changed, until interrupted with Ctrl-C.
+ * Rebuilds are serialized: one at a time, in the order the changes arrived, so
+ * the log stays readable. Each rebuild runs in a child process so a build error
+ * (which the single-build path reports via a hard exit) is contained and the
+ * watcher keeps running.
*
- * @param {string} file - The theme file argument, as the user passed it.
- * @param {string} filePath - Absolute path to the theme file.
+ * @param {Array<{file: string, filePath: string}>} entries - The theme file
+ * arguments as the user passed them, with their resolved absolute paths.
* @param {{out?: string, iconsSpecifier?: string}} options - Parsed command options.
* @returns {Promise<void>} Resolves when the watcher is stopped (Ctrl-C).
*/
-async function runThemeBuildWatch(file, filePath, options) {
- const rel = path.relative(process.cwd(), filePath);
+async function runThemeBuildWatch(entries, options) {
+ const rel = (/** @type {string} */ filePath) =>
+ path.relative(process.cwd(), filePath);
+ const watchingLine = `\nWatching ${entries
+ .map(e => rel(e.filePath))
+ .join(', ')} for changes — press Ctrl-C to stop.`;
// Initial build.
- await runThemeBuildOnceChild(file, options);
+ for (const entry of entries) {
+ await runThemeBuildOnceChild(entry.file, options);
+ }
let building = false;
- let queued = false;
- /** @type {ReturnType<typeof setTimeout> | undefined} */
- let debounce;
+ /** @type {Set<{file: string, filePath: string}>} */
+ const queued = new Set();
+ /** @type {Map<string, ReturnType<typeof setTimeout>>} */
+ const debounces = new Map();
- const rebuild = async () => {
+ /** @param {{file: string, filePath: string}} entry */
+ const rebuild = async entry => {
if (building) {
// Coalesce changes that land mid-build into a single follow-up run.
- queued = true;
+ queued.add(entry);
return;
}
building = true;
- emit(text(`\nChange detected — rebuilding ${rel}...`));
- await runThemeBuildOnceChild(file, options);
+ emit(text(`\nChange detected — rebuilding ${rel(entry.filePath)}...`));
+ await runThemeBuildOnceChild(entry.file, options);
building = false;
- emit(text(`\nWatching ${rel} for changes — press Ctrl-C to stop.`));
- if (queued) {
- queued = false;
- rebuild();
+ emit(text(watchingLine));
+ const next = queued.values().next();
+ if (!next.done) {
+ queued.delete(next.value);
+ rebuild(next.value);
}
};
// Some editors replace the file (rename) rather than writing in place, which
// can drop the watch. Watch the containing directory and filter to our file
// so edits survive atomic-save/rename.
- const watchDir = path.dirname(filePath);
- const baseName = path.basename(filePath);
- const watcher = fs.watch(watchDir, (_eventType, changed) => {
- if (changed && changed !== baseName) return;
- clearTimeout(debounce);
- // Debounce: editors often emit several events per save.
- debounce = setTimeout(rebuild, 100);
+ const watchers = entries.map(entry => {
+ const baseName = path.basename(entry.filePath);
+ return fs.watch(path.dirname(entry.filePath), (_eventType, changed) => {
+ if (changed && changed !== baseName) return;
+ clearTimeout(debounces.get(entry.filePath));
+ // Debounce: editors often emit several events per save.
+ debounces.set(
+ entry.filePath,
+ setTimeout(() => rebuild(entry), 100),
+ );
+ });
});
// Announce readiness only AFTER fs.watch is armed — the log is the "safe to
// edit" signal (tests and humans rely on it), so printing it before the watch
// is registered would race: a change in that gap is silently missed.
- emit(text(`\nWatching ${rel} for changes — press Ctrl-C to stop.`));
+ emit(text(watchingLine));
await new Promise((/** @type {(value?: void) => void} */ resolve) => {
const stop = () => {
- clearTimeout(debounce);
- watcher.close();
+ for (const d of debounces.values()) clearTimeout(d);
+ for (const w of watchers) w.close();
emit(text('\nStopped watching.'));
resolve();
};
@@ -208,15 +228,31 @@ export function registerTheme(program) {
defineCommand(theme, themeBuildCommand, {
fn: themeBuildFn,
action: async (
- /** @type {string} */ file,
+ /** @type {string[]} */ files,
/** @type {{out?: string, watch?: boolean, check?: boolean, iconsSpecifier?: string}} */ options,
) => {
- const filePath = path.resolve(process.cwd(), file);
const json = program.opts().json || false;
+ const entries = files.map(file => ({
+ file,
+ filePath: path.resolve(process.cwd(), file),
+ }));
- if (!fs.existsSync(filePath)) {
- cliError(`File not found: ${filePath}`, {
+ for (const entry of entries) {
+ if (fs.existsSync(entry.filePath)) continue;
+ // A quoted glob reaches us unexpanded: say so rather than reporting a
+ // literal `themes/*.ts` as a missing file.
+ const looksGlobby = /[*?[\]{}]/.test(entry.file);
+ cliError(`File not found: ${entry.filePath}`, {
code: ERROR_CODES.ERR_FILE_NOT_FOUND,
+ suggestions: looksGlobby
+ ? [
+ {
+ name: `astryx theme build ${entry.file.replace(/['"]/g, '')}`,
+ reason:
+ 'globs are expanded by your shell — pass the pattern unquoted, or list the files',
+ },
+ ]
+ : undefined,
});
return;
}
@@ -230,6 +266,19 @@ export function registerTheme(program) {
return;
}
+ // --out names one output file, so it cannot describe N themes. Without
+ // it each theme writes `<theme name>.css` beside its source, which is
+ // what a multi-theme build wants anyway.
+ if (options.out && entries.length > 1) {
+ cliError(
+ `--out takes a single output path and ${entries.length} theme files were given. ` +
+ 'Build them without --out (each theme writes <name>.css next to its source), ' +
+ 'or run one invocation per theme.',
+ {code: ERROR_CODES.ERR_THEME_INVALID},
+ );
+ return;
+ }
+
// Watch mode: run an initial build, then rebuild on every change to the
// theme file. Watch is a human-interactive, long-running mode — it is not
// supported in --json (machine) mode, which expects a single envelope.
@@ -240,41 +289,81 @@ export function registerTheme(program) {
});
return;
}
- await runThemeBuildWatch(file, filePath, options);
+ await runThemeBuildWatch(entries, options);
return;
}
- // Non-watch: delegate to the API compiler. Enable human output unless in
- // --json mode (log → stdout via humanLog, warn/error → stderr). The
- // "Building theme from" line, the ✓/warning lines, and the install
- // instructions are all emitted from inside themeBuild via the shared logger.
+ // Non-watch: delegate to the API compiler, once per theme, in argument
+ // order. Enable human output unless in --json mode (log → stdout via
+ // humanLog, warn/error → stderr). The "Building theme from" line, the
+ // ✓/warning lines, and the install instructions are all emitted from
+ // inside themeBuild via the shared logger.
logger.setSilent(json);
- try {
- const result = await themeBuild(
- file,
- {
- out: options.out,
- check: options.check,
- iconsSpecifier: options.iconsSpecifier,
- },
- {cwd: process.cwd()},
- );
- if (json && result) jsonOut(result);
- // In --check mode a stale/missing output is a failure: exit non-zero
- // (after emitting the receipt) so CI can gate on it. The receipt is
- // already printed above (shared logger or --json envelope).
- if (
- options.check &&
- result &&
- result.type === 'theme.build.check' &&
- !result.data.upToDate
- ) {
- process.exitCode = 1;
+ /** @type {Array<{file: string, receipt: import('../../../api/theme/theme.type.mjs').ThemeBuildResponse | import('../../../api/theme/theme.type.mjs').ThemeBuildCheckResponse | null}>} */
+ const results = [];
+ let stale = false;
+ for (const entry of entries) {
+ try {
+ const result = await themeBuild(
+ entry.file,
+ {
+ out: options.out,
+ check: options.check,
+ iconsSpecifier: options.iconsSpecifier,
+ },
+ {cwd: process.cwd()},
+ );
+ results.push({file: entry.file, receipt: result ?? null});
+ if (
+ options.check &&
+ result &&
+ result.type === 'theme.build.check' &&
+ !result.data.upToDate
+ ) {
+ stale = true;
+ }
+ } catch (e) {
+ const err =
+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
+ // Stop at the first failure, as a shell loop under `set -e` does.
+ // With several themes in flight the message alone rarely says which
+ // one broke, so name it.
+ cliError(
+ entries.length > 1 ? `${entry.file}: ${err.message}` : err.message,
+ {suggestions: err.suggestions, code: err.code},
+ );
+ return;
}
- } catch (e) {
- const err =
- /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
- cliError(err.message, {suggestions: err.suggestions, code: err.code});
+ }
+
+ if (json) {
+ // One theme keeps the single-envelope contract it has always had; a
+ // batch gets its own discriminant rather than N envelopes on stdout.
+ if (entries.length === 1) {
+ if (results[0].receipt) jsonOut(results[0].receipt);
+ } else {
+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeBuildBatchResponse} */
+ const batch = {
+ type: 'theme.build.batch',
+ data: {count: results.length, results},
+ };
+ jsonOut(batch);
+ }
+ } else if (entries.length > 1) {
+ emit(
+ text(
+ options.check
+ ? `\n${stale ? '✗' : '✓'} Checked ${entries.length} themes.`
+ : `\n✓ Built ${entries.length} themes.`,
+ ),
+ );
+ }
+
+ // In --check mode a stale/missing output is a failure: exit non-zero
+ // (after emitting the receipt) so CI can gate on it. The receipt is
+ // already printed above (shared logger or --json envelope).
+ if (options.check && stale) {
+ process.exitCode = 1;
}
},
});
diff --git a/packages/cli/clients/cli/commands/build-theme.multi.test.mjs b/packages/cli/clients/cli/commands/build-theme.multi.test.mjs
new file mode 100644
index 0000000000..5224d54e44
--- /dev/null
+++ b/packages/cli/clients/cli/commands/build-theme.multi.test.mjs
@@ -0,0 +1,148 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for `astryx theme build <a> <b> …` — several themes per
+ * invocation (kt-lc9s).
+ *
+ * The load-bearing guarantee is equivalence: one invocation over N theme files
+ * must write exactly the bytes N serial invocations write. Everything else here
+ * guards the edges that only exist once the argument is variadic — the JSON
+ * envelope, --check across a set, --out (which names one file), and fail-fast.
+ *
+ * `astryx theme build` needs a compiled @astryxdesign/core, so this suite
+ * builds core once via the shared ensureCoreBuilt() helper.
+ */
+
+import {describe, it, expect, beforeAll, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {ensureCoreBuilt} from './ensure-core-built.mjs';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+const THEMES = {
+ 'alpha.mjs': `export default { name: 'alpha', tokens: { '--color-bg': '#ffffff' } };\n`,
+ 'beta.mjs': `export default { name: 'beta', tokens: { '--color-bg': '#010203' } };\n`,
+ 'gamma.mjs': `export default { name: 'gamma', tokens: { '--color-bg': '#ff00ff' } };\n`,
+};
+const FILES = Object.keys(THEMES);
+const OUTPUTS = ['alpha', 'beta', 'gamma'].flatMap(n => [
+ `${n}.css`,
+ `${n}.js`,
+ `${n}.d.ts`,
+]);
+
+/** A fresh temp dir holding the three theme sources. */
+function themeDir() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-multi-'));
+ for (const [name, source] of Object.entries(THEMES)) {
+ fs.writeFileSync(path.join(dir, name), source);
+ }
+ dirs.push(dir);
+ return dir;
+}
+
+/** @type {string[]} */
+let dirs;
+
+beforeAll(() => {
+ ensureCoreBuilt();
+}, 200_000);
+
+beforeEach(() => {
+ dirs = [];
+});
+afterEach(() => {
+ for (const dir of dirs) fs.rmSync(dir, {recursive: true, force: true});
+});
+
+describe('theme build with several files', () => {
+ it('writes byte-identical output to one invocation per theme', async () => {
+ const serial = themeDir();
+ for (const file of FILES) {
+ const r = await runCli(['theme', 'build', file], serial);
+ expect(r.status).toBe(0);
+ }
+
+ const batch = themeDir();
+ const r = await runCli(['theme', 'build', ...FILES], batch);
+ expect(r.status).toBe(0);
+
+ for (const output of OUTPUTS) {
+ const one = fs.readFileSync(path.join(serial, output), 'utf8');
+ const many = fs.readFileSync(path.join(batch, output), 'utf8');
+ expect({output, content: many}).toEqual({output, content: one});
+ }
+ }, 120_000);
+
+ it('reports every theme in one theme.build.batch envelope', async () => {
+ const dir = themeDir();
+ const r = await runCli(['--json', 'theme', 'build', ...FILES], dir);
+ expect(r.status).toBe(0);
+
+ const envelope = JSON.parse(r.stdout);
+ expect(envelope.type).toBe('theme.build.batch');
+ expect(envelope.data.count).toBe(3);
+ expect(envelope.data.results.map(x => x.file)).toEqual(FILES);
+ expect(envelope.data.results.map(x => x.receipt.data.name)).toEqual([
+ 'alpha',
+ 'beta',
+ 'gamma',
+ ]);
+ expect(envelope.data.results[0].receipt.type).toBe('theme.build');
+ }, 120_000);
+
+ it('keeps the bare theme.build envelope for a single file', async () => {
+ const dir = themeDir();
+ const r = await runCli(['--json', 'theme', 'build', 'alpha.mjs'], dir);
+ expect(r.status).toBe(0);
+ expect(JSON.parse(r.stdout).type).toBe('theme.build');
+ }, 120_000);
+
+ it('--check passes when every theme is current and fails when one drifts', async () => {
+ const dir = themeDir();
+ expect((await runCli(['theme', 'build', ...FILES], dir)).status).toBe(0);
+
+ const fresh = await runCli(['theme', 'build', ...FILES, '--check'], dir);
+ expect(fresh.status).toBe(0);
+
+ // Drift one committed output rather than its source: the harness runs the
+ // CLI in-process, where jiti would serve a re-read theme file from its
+ // module cache.
+ fs.writeFileSync(path.join(dir, 'beta.css'), '/* hand-edited */\n');
+ const drifted = await runCli(['theme', 'build', ...FILES, '--check'], dir);
+ expect(drifted.status).toBe(1);
+ expect(drifted.stdout + drifted.stderr).toMatch(/beta\.css/);
+ }, 120_000);
+
+ it('rejects --out with more than one theme', async () => {
+ const dir = themeDir();
+ const r = await runCli(
+ ['theme', 'build', 'alpha.mjs', 'beta.mjs', '--out', 'one.css'],
+ dir,
+ );
+ expect(r.status).toBe(1);
+ expect(r.stderr).toMatch(/--out takes a single output path/);
+ expect(fs.existsSync(path.join(dir, 'one.css'))).toBe(false);
+ }, 120_000);
+
+ it('stops at the first failure and names the theme that failed', async () => {
+ const dir = themeDir();
+ fs.writeFileSync(
+ path.join(dir, 'beta.mjs'),
+ `export default { tokens: { '--color-bg': '#010203' } };\n`,
+ );
+ const r = await runCli(['theme', 'build', ...FILES], dir);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toMatch(/beta\.mjs: Theme must have a name/);
+ expect(fs.existsSync(path.join(dir, 'alpha.css'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'gamma.css'))).toBe(false);
+ }, 120_000);
+
+ it('tells the user a quoted glob was never expanded', async () => {
+ const dir = themeDir();
+ const r = await runCli(['theme', 'build', '*.mjs'], dir);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toMatch(/expanded by your shell/);
+ }, 120_000);
+});
diff --git a/packages/cli/clients/cli/commands/build-theme.watch.test.mjs b/packages/cli/clients/cli/commands/build-theme.watch.test.mjs
index 953d4e2bdd..49fb2db0f3 100644
--- a/packages/cli/clients/cli/commands/build-theme.watch.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.watch.test.mjs
@@ -156,4 +156,71 @@ describe('theme build --watch', () => {
expect(exited).toBe(true);
expect(stdout).toMatch(/Stopped watching/);
}, 30_000);
+
+ it('watches every file it was given and rebuilds only the one that changed', async () => {
+ const first = path.join(tmpDir, 'w1.mjs');
+ const second = path.join(tmpDir, 'w2.mjs');
+ fs.writeFileSync(
+ first,
+ `export default { name: 'w1', tokens: { '--color-bg': '#ffffff' } };\n`,
+ );
+ fs.writeFileSync(
+ second,
+ `export default { name: 'w2', tokens: { '--color-bg': '#eeeeee' } };\n`,
+ );
+
+ const child = spawn(
+ process.execPath,
+ [CLI_BIN, 'theme', 'build', 'w1.mjs', 'w2.mjs', '--watch'],
+ {cwd: tmpDir, env: {...process.env, FORCE_COLOR: '0'}},
+ );
+ let stdout = '';
+ child.stdout.on('data', d => (stdout += d.toString()));
+ child.stderr.on('data', d => (stdout += d.toString()));
+
+ try {
+ const built = await waitFor(
+ () =>
+ fs.existsSync(path.join(tmpDir, 'w1.css')) &&
+ fs.existsSync(path.join(tmpDir, 'w2.css')),
+ );
+ expect(built).toBe(true);
+ await waitFor(() => /Watching w1\.mjs, w2\.mjs/.test(stdout));
+ const firstCssBefore = fs.readFileSync(path.join(tmpDir, 'w1.css'), 'utf-8');
+
+ const changed = `export default { name: 'w2', tokens: { '--color-bg': '#010203' } };\n`;
+ fs.writeFileSync(second, changed);
+
+ const rebuilt = await waitFor(
+ () => {
+ try {
+ if (
+ fs
+ .readFileSync(path.join(tmpDir, 'w2.css'), 'utf-8')
+ .includes('#010203')
+ ) {
+ return true;
+ }
+ } catch {
+ // CSS mid-write; fall through to re-touch.
+ }
+ try {
+ fs.writeFileSync(second, changed);
+ } catch {
+ // Re-touch failed (e.g. dir mid-teardown); the next poll retries.
+ }
+ return false;
+ },
+ {timeout: 20000, interval: 200},
+ );
+ expect(rebuilt).toBe(true);
+ expect(stdout).toMatch(/rebuilding w2\.mjs/);
+ expect(stdout).not.toMatch(/rebuilding w1\.mjs/);
+ expect(fs.readFileSync(path.join(tmpDir, 'w1.css'), 'utf-8')).toBe(
+ firstCssBefore,
+ );
+ } finally {
+ child.kill('SIGINT');
+ }
+ }, 30_000);
});
diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjs
index 52da736c4b..2495b5cf5e 100644
--- a/packages/cli/clients/cli/commands/theme-build.doc.mjs
+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs
@@ -14,17 +14,19 @@ export const doc = {
name: 'theme build',
displayName: 'astryx theme build',
namespace: 'cli',
- summary: 'Compile a defineTheme file to CSS + JS',
+ summary: 'Compile one or more defineTheme files to CSS + JS',
description:
'Compiles a file that calls defineTheme() into a scoped CSS file, a JS module, and ' +
- 'type declarations: the exact CSS the <Theme> runtime emits. With --check it writes ' +
+ 'type declarations: the exact CSS the <Theme> runtime emits. Takes any number of theme ' +
+ 'files and compiles them in one process, in argument order, stopping at the first ' +
+ 'failure — an app with several themes does not need a shell loop. With --check it writes ' +
'nothing and instead reports whether the committed outputs have drifted from source. ' +
'When a separate build step emits the icon registry, --icons-specifier declares the ' +
'fully specified module path that the generated JS should import.',
fn: 'themeBuild',
- args: [{name: 'file', param: 'file', required: true}],
+ args: [{name: 'files', param: 'file', required: true, variadic: true}],
options: [
- {flag: '-o, --out <path>', param: 'options.out', description: 'Output CSS file path'},
+ {flag: '-o, --out <path>', param: 'options.out', description: 'Output CSS file path (single theme only)'},
{
flag: '--icons-specifier <specifier>',
param: 'options.iconsSpecifier',
@@ -33,7 +35,7 @@ export const doc = {
},
{
flag: '-w, --watch',
- description: 'Rebuild automatically when the theme file changes (Ctrl-C to stop)',
+ description: 'Rebuild automatically when a theme file changes (Ctrl-C to stop)',
},
{
flag: '-c, --check',
@@ -47,6 +49,10 @@ export const doc = {
label: 'Build to a CSS file',
cli: 'astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css',
},
+ {
+ label: 'Build every theme in a directory',
+ cli: 'astryx theme build ./src/themes/*.ts',
+ },
{
label: 'Check for drift (CI)',
cli: 'astryx theme build ./src/themes/ocean.ts --check',
diff --git a/packages/cli/clients/cli/lib/json-shim.test.mjs b/packages/cli/clients/cli/lib/json-shim.test.mjs
index e53aaac521..f923cdf6b2 100644
--- a/packages/cli/clients/cli/lib/json-shim.test.mjs
+++ b/packages/cli/clients/cli/lib/json-shim.test.mjs
@@ -61,7 +61,7 @@ describe('--json shim: --help renders JSON envelope', () => {
expect(parsed.apiVersion).toBe(1);
expect(parsed.type).toBe('help');
expect(parsed.data.command).toBe('astryx theme build');
- expect(parsed.data.usage).toMatch(/<file>/);
+ expect(parsed.data.usage).toMatch(/<files\.\.\.>/);
});
});
diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjs
index 227214e147..3962d7ed79 100644
--- a/packages/cli/clients/cli/lib/manifest.mjs
+++ b/packages/cli/clients/cli/lib/manifest.mjs
@@ -73,7 +73,7 @@ export const RESPONSE_TYPES = {
'template.cdn',
],
hook: ['hook.list', 'hook.detail', 'hook.detail.params'],
- 'theme build': ['theme.build', 'theme.build.check'],
+ 'theme build': ['theme.build', 'theme.build.check', 'theme.build.batch'],
'theme list': ['theme.list'],
'theme add': ['theme.list', 'theme.add'],
'theme template': ['theme.template'],
diff --git a/packages/cli/clients/cli/lib/manifest.test.mjs b/packages/cli/clients/cli/lib/manifest.test.mjs
index 51edaa4ed0..930d3ad19b 100644
--- a/packages/cli/clients/cli/lib/manifest.test.mjs
+++ b/packages/cli/clients/cli/lib/manifest.test.mjs
@@ -146,8 +146,10 @@ describe('manifest: shape', () => {
const component = allEntries.find((c) => c.name === 'component');
expect(component.arguments.map((a) => a.name)).toContain('name');
const themeBuild = allEntries.find((c) => c.name === 'theme build');
- expect(themeBuild.arguments.map((a) => a.name)).toContain('file');
- expect(themeBuild.arguments.find((a) => a.name === 'file').required).toBe(true);
+ expect(themeBuild.arguments.map((a) => a.name)).toContain('files');
+ const files = themeBuild.arguments.find((a) => a.name === 'files');
+ expect(files.required).toBe(true);
+ expect(files.variadic).toBe(true);
});
});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index d021f1862c..06b19c3998 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -179,6 +179,11 @@ export const doc = {
description:
'The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing | outdated}), and the full list of checked paths. Writes nothing.',
},
+ {
+ value: 'theme.build.batch',
+ description:
+ 'Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme\'s theme.build (or theme.build.check) envelope, or null when it produced no CSS.',
+ },
{
value: 'theme.list',
description:
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 698f854089..5eea1bbbec 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -25,6 +25,9 @@
"agent-docs"
],
"type": "module",
+ "engines": {
+ "node": ">=22.13.0"
+ },
"bin": {
"astryx": "./clients/cli/bin/astryx.mjs",
"cli": "./clients/cli/bin/astryx.mjs"