Skip to content

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

TypeScript

feat(cli): `astryx theme template` — an annotated, drift-guarded theme reference (#5048)

Cindy Zhange1331932f5d6
diff --git a/.changeset/theme-template.md b/.changeset/theme-template.md
new file mode 100644
index 0000000000..43fa6a2f95
--- /dev/null
+++ b/.changeset/theme-template.md
@@ -0,0 +1,14 @@
+---
+'@astryxdesign/cli': patch
+'@astryxdesign/core': patch
+---
+
+[feat] `astryx theme template` writes an annotated theme template into your project.
+
+New sibling of `theme add`: where `add` starts you from a theme we ship, `template` starts you from a blank annotated one. `astryx init --features theme` calls the same leaf, so project setup writes it too — it previously printed a one-line hint and wrote nothing, which is the weakest form of the help a theme author needs, since the first problem is not knowing the command but not knowing what the theme surface contains. The file is `theme.template.ts`: every `defineTheme` field with a note on when to reach for it, the token families, the component override syntax, and the consumption steps (providing the theme, loading the fonts you name, building for SSR), each section naming the CLI command that prints its authoritative reference. An existing file is never clobbered.
+
+This came out of a vibe test (#5047): agents given an annotated template reached twice as far into the theme surface as agents given only the docs (17 component targets vs 8, and the only arm to use interaction states, custom variants and `onDark`), and shipped a third of the contrast defects.
+
+A template that lies is worse than no template, so its claims are machine-checked against live sources rather than trusted: `scripts/check-theme-template.test.mjs` fails when a `defineTheme` field is added and left undocumented, when a token family is missing from the inventory, when a CSS variable or component key it names does not exist, when it cites a docs topic that does not, or when a theme source drops its SYNC reference. `theme build` compiles it warning-free in CI, and the CLI typecheck now covers it.
+
+@cixzhang
diff --git a/.claude/commands/create-theme.md b/.claude/commands/create-theme.md
index fe63815b66..ddc5e7d54c 100644
--- a/.claude/commands/create-theme.md
+++ b/.claude/commands/create-theme.md
@@ -2,6 +2,12 @@
Create a new Astryx theme using `defineTheme`.
+> Read `packages/cli/assets/theme.template.ts` first (`astryx theme template` writes it into a consumer project). It is the annotated,
+> drift-guarded map of the whole theme surface — every field, the token
+> families, the override syntax — and it names the CLI command that prints the
+> authoritative reference for each. What follows is the packaging around a
+> theme; the template is what goes inside it.
+
## Theme Name
$ARGUMENTS
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 3e94f517aa..98050cb3d4 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -416,6 +416,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `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.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. |
| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
diff --git a/packages/cli/api/init/init.doc.mjs b/packages/cli/api/init/init.doc.mjs
index 1115ca65d6..873b1ef431 100644
--- a/packages/cli/api/init/init.doc.mjs
+++ b/packages/cli/api/init/init.doc.mjs
@@ -30,7 +30,7 @@ export const doc = {
name: 'options.features',
type: 'string',
description:
- 'Comma-separated features to install: agents, theme, template.',
+ 'Comma-separated features to install: agents (agent docs), theme (writes the annotated theme.template.ts), template (page-template guidance).',
},
{
name: 'options.all',
@@ -64,7 +64,7 @@ export const doc = {
{
type: 'init.run',
description:
- 'The install receipt: the `mode` (`default` | `features`), the features run, agent-doc files written, any soft docsError, whether theme guidance was emitted, the template outcome (`workflow` | `created` | `skipped`) plus its path, and whether the next-steps were emitted.',
+ 'The install receipt: the `mode` (`default` | `features`), the features run, agent-doc files written, any soft docsError, the theme-template outcome (`created` | `skipped` | `failed`) plus its path, the page-template outcome (`workflow` | `created` | `skipped`) plus its path, and whether the next-steps were emitted.',
},
{
type: 'init.remove',
diff --git a/packages/cli/api/init/init.test.mjs b/packages/cli/api/init/init.test.mjs
index a6f0dba6f4..a69ff7e614 100644
--- a/packages/cli/api/init/init.test.mjs
+++ b/packages/cli/api/init/init.test.mjs
@@ -57,13 +57,30 @@ describe('init() — receipts + side effects', () => {
expect(res.type === 'init.run' && res.data.docsWritten).toContain('AGENTS.md');
});
- it('--features theme emits guidance, writes no files, and flags theme', async () => {
+ it('--features theme writes the annotated template and reports it on the receipt', async () => {
const res = await init({features: 'theme'}, {cwd: tmpDir});
expect(res.type).toBe('init.run');
if (res.type !== 'init.run') return;
expect(res.data.theme).toBe(true);
+ expect(res.data.themeTemplate).toBe('created');
+ expect(res.data.themeTemplatePath).toBe('theme.template.ts');
expect(res.data.docsWritten).toEqual([]);
- expect(fs.readdirSync(tmpDir)).toEqual([]);
+ expect(fs.readdirSync(tmpDir)).toEqual(['theme.template.ts']);
+ // The consumer's copy is their file: it must not carry our repo header,
+ // which their own lint would flag.
+ const written = fs.readFileSync(path.join(tmpDir, 'theme.template.ts'), 'utf-8');
+ expect(written).not.toMatch(/Copyright \(c\) Meta Platforms/);
+ expect(written.startsWith('/**')).toBe(true);
+ });
+
+ it('--features theme reports `skipped` rather than overwriting an existing template', async () => {
+ fs.writeFileSync(path.join(tmpDir, 'theme.template.ts'), '// mine\n');
+ const res = await init({features: 'theme'}, {cwd: tmpDir});
+ expect(res.type).toBe('init.run');
+ if (res.type !== 'init.run') return;
+ expect(res.data.themeTemplate).toBe('skipped');
+ expect(res.data.themeTemplatePath).toBe(null);
+ expect(fs.readFileSync(path.join(tmpDir, 'theme.template.ts'), 'utf-8')).toBe('// mine\n');
});
it('--features template returns the workflow (or skipped) outcome, no crash', async () => {
diff --git a/packages/cli/api/init/init.type.mjs b/packages/cli/api/init/init.type.mjs
index 272c1ee2ea..80cf89acb6 100644
--- a/packages/cli/api/init/init.type.mjs
+++ b/packages/cli/api/init/init.type.mjs
@@ -12,7 +12,9 @@
* @property {string[]} features Features that were run, in order.
* @property {string[]} docsWritten Agent-doc files written (empty if agents weren't run or install failed).
* @property {{kind: 'path-safety' | 'install-failed', message?: string} | null} docsError Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit.
- * @property {boolean} theme Whether theme guidance was emitted.
+ * @property {boolean} theme Whether the theme feature ran.
+ * @property {'created' | 'skipped' | 'failed' | null} themeTemplate Outcome of writing the annotated theme template (`skipped` = a file was already there).
+ * @property {string | null} themeTemplatePath Relative output path when `themeTemplate === 'created'`.
* @property {'workflow' | 'created' | 'skipped' | null} template Template outcome (`workflow` is the CLI default; `created`/`skipped` are programmatic).
* @property {string | null} templatePath Relative output path when `template === 'created'`.
* @property {boolean} nextSteps Whether the getting-started "Next steps" were emitted (default mode).
diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjs
index e95adda6a6..d3a7824f6d 100644
--- a/packages/cli/api/init/run/run.mjs
+++ b/packages/cli/api/init/run/run.mjs
@@ -20,6 +20,7 @@ import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';
import {PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
import {installAgentDocs} from '../../../foundation/agent-docs/agent-docs.mjs';
+import {themeTemplate} from '../../theme/template/template.mjs';
import {listTemplates} from '../../template/template.mjs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
@@ -106,6 +107,36 @@ function applyAgents(cwd, options, invocation, data) {
}
}
+/**
+ * Write the annotated theme template, via the same leaf `astryx theme template`
+ * uses — init is a convenience wrapper over the theme command, not a second
+ * implementation of it.
+ *
+ * @param {string} cwd
+ * @param {string} invocation
+ * @param {import('../init.type.mjs').InitRunData} data
+ */
+function applyTheme(cwd, invocation, data) {
+ data.theme = true;
+ try {
+ const {path: written, written: didWrite} = themeTemplate({cwd}).data;
+ data.themeTemplate = didWrite ? 'created' : 'skipped';
+ data.themeTemplatePath = didWrite ? written : null;
+ logger.log(
+ didWrite
+ ? `✓ Theme template written → ${written}`
+ : `• ${written} already exists — left as is.`,
+ );
+ } catch {
+ // Soft failure, like agent docs: the guidance below is still useful.
+ data.themeTemplate = 'failed';
+ logger.error('Could not write the theme template.');
+ }
+ logger.log(
+ ` Copy it to your theme file and edit, or run \`${invocation} theme add <slug>\` to start from a shipped theme (\`${invocation} theme list\` to browse).`,
+ );
+}
+
/**
* Emit the template guidance, or (programmatic-only) scaffold a named template.
* The CLI never passes `templateName`, so from the CLI this always emits the
@@ -210,18 +241,15 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
docsWritten: [],
docsError: null,
theme: false,
+ themeTemplate: null,
+ themeTemplatePath: null,
template: null,
templatePath: null,
nextSteps: false,
};
for (const feature of features) {
if (feature === 'agents') applyAgents(cwd, options, invocation, data);
- if (feature === 'theme') {
- logger.log(
- `✓ For a custom theme, run \`${invocation} theme\` (browse) or \`${invocation} theme add <slug>\` (scaffold).`,
- );
- data.theme = true;
- }
+ if (feature === 'theme') applyTheme(cwd, invocation, data);
if (feature === 'template') {
applyTemplate(cwd, {templateName: options.templateName}, invocation, data);
}
@@ -238,6 +266,8 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
docsWritten: [],
docsError: null,
theme: false,
+ themeTemplate: null,
+ themeTemplatePath: null,
template: null,
templatePath: null,
nextSteps: true,
diff --git a/packages/cli/api/theme/add/add.mjs b/packages/cli/api/theme/add/add.mjs
index e07c07d750..60a5667d0e 100644
--- a/packages/cli/api/theme/add/add.mjs
+++ b/packages/cli/api/theme/add/add.mjs
@@ -13,19 +13,8 @@ import {assertWithin, PathSafetyError} from '../../../foundation/fs/path-safety.
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {THEMES_DIR, listThemes, findTheme} from '../_adapter.mjs';
-
-// Stripped from scaffolded files so the consumer's copy doesn't carry our
-// repo boilerplate (mirrors the docsite). Preserves a leading BOM/shebang.
-const META_COPYRIGHT_HEADER_RE =
- /^(\uFEFF?(?:#![^\r\n]*(?:\r?\n))?)\/\/ Copyright \(c\) Meta Platforms, Inc\. and affiliates\.\r?\n(?:\r?\n)*/;
-
-/**
- * @param {string} source
- * @returns {string}
- */
-function stripCopyrightHeader(source) {
- return source.replace(META_COPYRIGHT_HEADER_RE, '$1');
-}
+// Scaffolded files must not carry our repo boilerplate into a consumer's tree.
+import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';
/**
* @param {string} slug
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
index 31b957db58..e8cfc62fb5 100644
--- a/packages/cli/api/theme/build/build.test.mjs
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -295,3 +295,26 @@ describe('themeBuild() — component override validation', () => {
]);
});
});
+
+describe('themeBuild() — the shipped theme template', () => {
+ // `assets/theme.template.ts` is what `astryx theme template` puts in a
+ // consumer's project. It is the one theme file we hand out, so it has to
+ // compile as shipped — and cleanly: a template that greets its first reader
+ // with warnings teaches them to ignore warnings. The claims its comments make
+ // are checked separately by scripts/check-theme-template.test.mjs.
+ it('compiles as shipped, with no warnings', async () => {
+ const src = path.resolve(
+ import.meta.dirname,
+ '../../../assets/theme.template.ts',
+ );
+ fs.copyFileSync(src, path.join(tmpDir, 'theme.template.ts'));
+
+ const result = await themeBuild('theme.template.ts', {}, {cwd: tmpDir});
+
+ expect(result?.data.warnings).toEqual([]);
+ expect(fs.existsSync(path.join(tmpDir, 'my-theme.css'))).toBe(true);
+ // The template teaches custom variants; the augmentation it promises the
+ // reader has to actually be generated.
+ expect(fs.existsSync(path.join(tmpDir, 'my-theme.variants.d.ts'))).toBe(true);
+ });
+});
diff --git a/packages/cli/api/theme/template/template.mjs b/packages/cli/api/theme/template/template.mjs
new file mode 100644
index 0000000000..b1fb08e692
--- /dev/null
+++ b/packages/cli/api/theme/template/template.mjs
@@ -0,0 +1,69 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx theme template` leaf — writes the annotated theme template into the
+ * consumer's project.
+ *
+ * Sibling of `theme add`: both answer "put a theme starting point in my
+ * project", and they split on where you start. `add` copies a theme we ship
+ * (you like stone, you want to own it); `template` writes the blank annotated
+ * reference (you want your own, and need to know what the surface contains).
+ *
+ * The template is a doc that happens to compile, so it is one file at the
+ * project root by default rather than a package under src/themes/ — you read
+ * it, copy what you need into your own theme file, and delete it.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';
+import {assertWithin, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
+import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';
+import {AstryxError} from '../../error.mjs';
+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
+
+/** The annotated `defineTheme` reference that ships with the CLI. */
+export const THEME_TEMPLATE_SRC = path.join(CLI_ROOT, 'assets', 'theme.template.ts');
+
+/** Where it lands when the caller does not say. */
+export const THEME_TEMPLATE_DEFAULT_PATH = 'theme.template.ts';
+
+/**
+ * Write the annotated theme template into a project.
+ *
+ * Refuses to overwrite without `overwrite`: an edited copy is the consumer's
+ * work, and this command is safe to re-run (init calls it on every setup).
+ *
+ * @param {{targetPath?: string, overwrite?: boolean, cwd?: string}} [options]
+ * @returns {import('../theme.type.mjs').ThemeTemplateResponse}
+ */
+export function themeTemplate(options = {}) {
+ const {
+ targetPath = THEME_TEMPLATE_DEFAULT_PATH,
+ overwrite = false,
+ cwd = process.cwd(),
+ } = options;
+
+ let resolved;
+ try {
+ resolved = assertWithin(targetPath, cwd, {label: 'theme template path'});
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
+ }
+ throw err;
+ }
+
+ const relative = path.relative(cwd, resolved) || targetPath;
+
+ if (fs.existsSync(resolved) && !overwrite) {
+ return {type: 'theme.template', data: {path: relative, written: false, reason: 'exists'}};
+ }
+
+ // Our repo header has no business in someone else's source tree.
+ const contents = stripCopyrightHeader(fs.readFileSync(THEME_TEMPLATE_SRC, 'utf-8'));
+ fs.mkdirSync(path.dirname(resolved), {recursive: true});
+ fs.writeFileSync(resolved, contents);
+
+ return {type: 'theme.template', data: {path: relative, written: true, reason: null}};
+}
diff --git a/packages/cli/api/theme/template/template.test.mjs b/packages/cli/api/theme/template/template.test.mjs
new file mode 100644
index 0000000000..70bb376ee9
--- /dev/null
+++ b/packages/cli/api/theme/template/template.test.mjs
@@ -0,0 +1,82 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Direct API tests for `themeTemplate()` — the function behind
+ * `astryx theme template` and `astryx init --features theme`.
+ *
+ * What matters here is that it never destroys work: the template lands once,
+ * a second run leaves an edited copy alone, and a path that escapes the
+ * project is refused.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {themeTemplate, THEME_TEMPLATE_DEFAULT_PATH} from './template.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-template-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('themeTemplate()', () => {
+ it('writes the template and returns a theme.template receipt', () => {
+ const res = themeTemplate({cwd: tmpDir});
+
+ expect(res).toEqual({
+ type: 'theme.template',
+ data: {path: THEME_TEMPLATE_DEFAULT_PATH, written: true, reason: null},
+ });
+ const written = fs.readFileSync(path.join(tmpDir, THEME_TEMPLATE_DEFAULT_PATH), 'utf-8');
+ expect(written).toMatch(/defineTheme/);
+ });
+
+ it('does not carry our copyright header into the consumer tree', () => {
+ themeTemplate({cwd: tmpDir});
+ const written = fs.readFileSync(path.join(tmpDir, THEME_TEMPLATE_DEFAULT_PATH), 'utf-8');
+ expect(written).not.toMatch(/Copyright \(c\) Meta Platforms/);
+ expect(written.startsWith('/**')).toBe(true);
+ });
+
+ it('leaves an existing file alone and says so', () => {
+ const dest = path.join(tmpDir, THEME_TEMPLATE_DEFAULT_PATH);
+ fs.writeFileSync(dest, '// mine\n');
+
+ const res = themeTemplate({cwd: tmpDir});
+
+ expect(res.data).toEqual({
+ path: THEME_TEMPLATE_DEFAULT_PATH,
+ written: false,
+ reason: 'exists',
+ });
+ expect(fs.readFileSync(dest, 'utf-8')).toBe('// mine\n');
+ });
+
+ it('overwrites when asked', () => {
+ const dest = path.join(tmpDir, THEME_TEMPLATE_DEFAULT_PATH);
+ fs.writeFileSync(dest, '// mine\n');
+
+ const res = themeTemplate({cwd: tmpDir, overwrite: true});
+
+ expect(res.data.written).toBe(true);
+ expect(fs.readFileSync(dest, 'utf-8')).toMatch(/defineTheme/);
+ });
+
+ it('honors a custom path and creates its directory', () => {
+ const res = themeTemplate({cwd: tmpDir, targetPath: 'src/themes/starter.ts'});
+
+ expect(res.data.path).toBe(path.join('src', 'themes', 'starter.ts'));
+ expect(fs.existsSync(path.join(tmpDir, 'src/themes/starter.ts'))).toBe(true);
+ });
+
+ it('refuses a path that escapes the project', () => {
+ expect(() => themeTemplate({cwd: tmpDir, targetPath: '../escaped.ts'})).toThrow(
+ /theme template path/,
+ );
+ expect(fs.existsSync(path.join(path.dirname(tmpDir), 'escaped.ts'))).toBe(false);
+ });
+});
diff --git a/packages/cli/api/theme/theme.mjs b/packages/cli/api/theme/theme.mjs
index fde7301971..5fad0627a2 100644
--- a/packages/cli/api/theme/theme.mjs
+++ b/packages/cli/api/theme/theme.mjs
@@ -10,5 +10,6 @@
export {themeBuild, importSpecifier} from './build/build.mjs';
export {themeAdd} from './add/add.mjs';
+export {themeTemplate} from './template/template.mjs';
export {themeList} from './list/list.mjs';
export {listThemes} from './_adapter.mjs';
diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjs
index eafc74446f..5b2f9b71d3 100644
--- a/packages/cli/api/theme/theme.type.mjs
+++ b/packages/cli/api/theme/theme.type.mjs
@@ -12,9 +12,10 @@
* xds --json theme build <file> --check -> theme.build.check
* xds --json theme list -> theme.list
* xds --json theme add <slug> -> theme.add
+ * xds --json theme template -> theme.template
* (file not found / parse error) -> CLIError
*
- * @position api — colocated typedefs for api/theme/{theme,build,add,list,_adapter}
+ * @position api — colocated typedefs for api/theme/{theme,build,add,list,template,_adapter}
*/
/**
@@ -54,6 +55,15 @@
* @property {{slug: string, displayName: string, maintained: boolean, outputDir: string, entry: string, exportName: string, files: string[]}} data
*/
+/**
+ * xds --json theme template
+ * `written: false` with `reason: 'exists'` is a success: the command is safe to
+ * re-run, and an edited template is the consumer's file to keep.
+ * @typedef {object} ThemeTemplateResponse
+ * @property {'theme.template'} type
+ * @property {{path: string, written: boolean, reason: 'exists' | null}} data
+ */
+
// Make this a module so the @typedefs above are importable as types via
// `import('./theme.type.mjs').ThemeBuildResponse` (and re-exportable from a .d.ts).
export {};
diff --git a/packages/cli/api/theme/themeTemplate.doc.mjs b/packages/cli/api/theme/themeTemplate.doc.mjs
new file mode 100644
index 0000000000..a33f33a296
--- /dev/null
+++ b/packages/cli/api/theme/themeTemplate.doc.mjs
@@ -0,0 +1,64 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `themeTemplate()` / `astryx theme template`. Colocated with the
+ * API function it documents; the response-shape source of truth stays in
+ * `theme.type.mjs`.
+ * @position packages/cli/api/theme — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'themeTemplate',
+ displayName: 'themeTemplate()',
+ summary: 'Write the annotated theme template into a project.',
+ description:
+ 'Writes theme.template.ts: the annotated reference for the whole theme surface — every ' +
+ 'defineTheme field, the token families, the component override syntax, and how a theme is ' +
+ 'consumed — with the CLI command that prints the authoritative reference for each section. ' +
+ 'Read it, copy what you need into your own theme file, delete it. Where `theme add` starts ' +
+ 'you from a theme we ship, this starts you from a blank one. Refuses to overwrite without ' +
+ '`overwrite`, so it is safe to re-run.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'themeTemplate(options?: {targetPath?: string, overwrite?: boolean, cwd?: string}): ThemeNewResponse',
+ keywords: ['theme', 'template', 'starter', 'defineTheme', 'scaffold', 'reference', 'tokens'],
+ params: [
+ {
+ name: 'options.targetPath',
+ type: 'string',
+ description: 'Destination file. Must resolve within cwd.',
+ default: "'theme.template.ts'",
+ },
+ {
+ name: 'options.overwrite',
+ type: 'boolean',
+ description: 'Replace an existing file instead of reporting it untouched.',
+ default: 'false',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Directory the target path resolves against.',
+ },
+ ],
+ returns: [
+ {
+ type: 'theme.template',
+ description:
+ 'Receipt: 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, not a failure.',
+ },
+ ],
+ throws: [{code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'}],
+ examples: [
+ {label: 'Write it at the project root', code: 'themeTemplate();'},
+ {
+ label: 'Somewhere else, replacing what is there',
+ code: "themeTemplate({targetPath: 'src/themes/template.ts', overwrite: true});",
+ },
+ ],
+ command: 'theme template',
+ related: ['themeAdd', 'themeBuild', 'themeList'],
+};
diff --git a/packages/cli/assets/docs/getting-started.doc.mjs b/packages/cli/assets/docs/getting-started.doc.mjs
index ac491ffb5a..a739f2410d 100644
--- a/packages/cli/assets/docs/getting-started.doc.mjs
+++ b/packages/cli/assets/docs/getting-started.doc.mjs
@@ -20,9 +20,19 @@ export const docs = {
{
type: 'code',
lang: 'text',
- label: 'Paste this into your AI',
+ label: 'Set up the design system',
code: 'Install @astryxdesign/core, @stylexjs/stylex, @astryxdesign/theme-neutral, and @astryxdesign/cli in this project, then run `npx @astryxdesign/cli init` to set up agent docs. Read the generated files to learn the conventions.',
},
+ {
+ type: 'prose',
+ text: 'Then give it a look. Every app gets a theme whether or not anyone picks one, so it is worth one question at setup rather than revisiting screens later that were built around the wrong look:',
+ },
+ {
+ type: 'code',
+ lang: 'text',
+ label: 'Give it a look',
+ code: "Ask me what look and feel this app should have. Run `npx @astryxdesign/cli theme list` and start from the closest shipped theme with `theme add <slug>`, which copies it in as editable source; if none of them fit, run `npx @astryxdesign/cli theme template` and fill in the annotated template it writes. Default to neutral if I have no preference, and show me the result before moving on.",
+ },
],
},
{
diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjs
index 6a20b78928..71de45989d 100644
--- a/packages/cli/assets/docs/theme.doc.dense.mjs
+++ b/packages/cli/assets/docs/theme.doc.dense.mjs
@@ -8,7 +8,7 @@ export const docsDense = {
{ section: 'Quick Start', title: 'Quick Start', content: [null, null, null, null, { type: 'prose', text: 'default import = runtime injection. /built import = pre-compiled CSS (pair with theme.css).' }] },
{ section: 'Available Themes', title: 'Themes', content: [null, null, { type: 'prose', text: 'published: neutral (start here), butter, chocolate, gothic (dark-only), matcha, stone, y2k. @astryxdesign/theme-{name} = source (runtime). @astryxdesign/theme-{name}/built = optimized (+ theme.css).' }] },
{ section: 'Theme Props', title: 'Props', content: [null] },
- { section: 'Creating a Custom Theme', title: 'Custom Theme', content: [{ type: 'prose', text: 'CLI wizard or manual defineTheme. only override tokens that differ.' }, null] },
+ { section: 'Creating a Custom Theme', title: 'Custom Theme', content: [{ type: 'prose', text: '`theme list` + `theme add <slug>` to start from a shipped theme, or defineTheme from scratch. only override tokens that differ.' }, null, { type: 'prose', text: '`astryx theme template` writes theme.template.ts: every defineTheme field + token families + override syntax, annotated, with the CLI command that prints each reference.' }] },
{ section: 'defineTheme', title: 'defineTheme', content: [{ type: 'prose', text: 'scale configs (color, typography, radius, motion) + explicit token overrides + component overrides. color derives full palette from accent hex via HCT.' }, null, null] },
{ section: 'Component Style Overrides', title: 'Component Overrides', content: [{ type: 'prose', text: 'components field uses semantic component keys + style keys (base, variant:value, stateName), not raw selectors. for external CSS, prefer data-* selectors from `astryx docs styling`. write standard CSS (borderRadius, padding) — pipeline expands to internal vars. public vars (--button-focus-offset etc) set directly. private vars (--_*) cannot be set — use CSS properties. run `astryx component <Name>` for details.' }, null, null, null, null] },
{ section: 'Custom Variants', title: 'Custom Variants', content: [{ type: 'prose', text: 'any unknown prop:value in components becomes a new variant. astryx theme build generates TS augmentations. works on any extensible prop axis (variant, status, etc).' }, null, null, null, null] },
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index 9a08a62619..899f05b59d 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -142,13 +142,17 @@ function App() {
content: [
{
type: 'prose',
- text: 'Use the CLI wizard (recommended) or create manually with defineTheme. Only override tokens that differ from defaults; omitted tokens use the design system defaults.',
+ text: 'Start from a theme we ship, or write one from scratch with defineTheme. Only override tokens that differ from defaults; omitted tokens use the design system defaults.',
},
{
type: 'code',
lang: 'bash',
- label: 'Scaffold with CLI',
- code: 'astryx theme',
+ label: 'Browse, then copy a theme in as editable source',
+ code: 'astryx theme list\nastryx theme add stone',
+ },
+ {
+ type: 'prose',
+ text: 'For an annotated map of the whole surface — every defineTheme field, the token families, and the component override syntax, each with the CLI command that prints its reference — run `astryx theme template`. It writes `theme.template.ts` into your project to read and copy from (`astryx init --features theme` writes it as part of project setup).',
},
],
},
diff --git a/packages/cli/assets/docs/theme.doc.zh.mjs b/packages/cli/assets/docs/theme.doc.zh.mjs
index 8d99d76252..a444c09738 100644
--- a/packages/cli/assets/docs/theme.doc.zh.mjs
+++ b/packages/cli/assets/docs/theme.doc.zh.mjs
@@ -8,7 +8,7 @@ export const docsZh = {
{ section: 'Quick Start', title: '快速开始', content: [null, null, null, null, { type: 'prose', text: '默认导入使用运行时样式注入。/built 导入使用预编译 CSS(需配合 theme.css)。' }] },
{ section: 'Available Themes', title: '可用主题', content: [null, null, { type: 'prose', text: '已发布主题:neutral(推荐起点)、butter、chocolate、gothic(仅暗色)、matcha、stone、y2k。@astryxdesign/theme-{name} = 源码版(运行时注入)。@astryxdesign/theme-{name}/built = 优化版(配合 theme.css)。' }] },
{ section: 'Theme Props', title: 'Theme 属性', content: [null] },
- { section: 'Creating a Custom Theme', title: '创建自定义主题', content: [{ type: 'prose', text: '使用 CLI 向导(推荐)或手动 defineTheme。只覆盖与默认值不同的令牌。' }, null] },
+ { section: 'Creating a Custom Theme', title: '创建自定义主题', content: [{ type: 'prose', text: '用 `theme list` + `theme add <slug>` 从内置主题开始,或用 defineTheme 从零编写。只覆盖与默认值不同的令牌。' }, null, { type: 'prose', text: '`astryx theme template` 会写入 theme.template.ts:带注释的完整参考,涵盖每个 defineTheme 字段、令牌族和覆盖语法,并标明打印各自参考的 CLI 命令。' }] },
{ section: 'defineTheme', title: 'defineTheme', content: [{ type: 'prose', text: '支持比例配置(typography、radius、motion)+ 显式令牌覆盖 + 组件覆盖。' }, null, null] },
{ section: 'Building Themes for Production', title: '生产构建', content: [{ type: 'prose', text: 'astryx theme build 将 defineTheme 编译为静态 CSS。输出 .css + .js(__built:true)+ .d.ts。' }, null, null, null, null] },
{ section: 'Runtime vs Built Themes', title: '运行时 vs 构建', content: [{ type: 'prose', text: '运行时:useInsertionEffect 在客户端注入样式。构建:静态 CSS 在首次渲染时就存在。SSR 应用请使用 /built + theme.css。' }, null, null, null] },
diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.ts
new file mode 100644
index 0000000000..486955b56a
--- /dev/null
+++ b/packages/cli/assets/theme.template.ts
@@ -0,0 +1,321 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Astryx theme template — every `defineTheme` field, with a note on what it
+ * does and when to reach for it.
+ *
+ * Only `name` is required. Delete what you do not need: the values here are
+ * placeholders that reproduce the built-in defaults, so a field you leave
+ * untouched changes nothing.
+ *
+ * Each section names the CLI command that prints the authoritative reference
+ * for it. These comments are a map; the CLI is the territory — it reads the
+ * same source the components do. `astryx docs` lists every topic.
+ *
+ * ═══════════════════════════════════════════════════════════════════════
+ * HOW A THEME IS CONSUMED
+ * ═══════════════════════════════════════════════════════════════════════
+ *
+ * 1. WRAP THE APP. A theme does nothing until it is provided.
+ *
+ * import {Theme} from '@astryxdesign/core';
+ * import {myTheme} from './theme';
+ *
+ * <Theme theme={myTheme} mode="system"> // 'system' | 'light' | 'dark'
+ * <App />
+ * </Theme>
+ *
+ * `system` follows the OS. Nest a second `<Theme>` to give one region its
+ * own theme or mode — a dark sidebar inside a light page.
+ *
+ * 2. SHIP THE FONTS YOU NAME. Astryx sets the `--font-family-*` tokens; it
+ * never loads a font file, so use whatever typeface the design needs and
+ * load it yourself. Either add it to your app's <head>:
+ *
+ * <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ * <link rel="stylesheet"
+ * href="https://fonts.googleapis.com/css2?family=Inter:[email protected]&display=swap" />
+ *
+ * or self-host it in your global CSS:
+ *
+ * @font-face {
+ * font-family: 'Inter';
+ * src: url('/fonts/Inter.woff2') format('woff2');
+ * font-weight: 100 900;
+ * font-display: swap;
+ * }
+ *
+ * Always give `fallbacks` as well. A named family with no file loads
+ * nothing and warns about nothing — the fallback silently becomes your
+ * theme.
+ *
+ * 3. BUILD IT FOR PRODUCTION.
+ *
+ * astryx theme build src/theme.ts
+ *
+ * writes `<name>.css` (tokens, component overrides and prose styles in
+ * `@scope` rules), `<name>.js` (the theme with `__built: true` and
+ * pre-resolved values), `<name>.d.ts`, and `<name>.variants.d.ts` when the
+ * theme adds custom prop values. Import the module and the CSS together:
+ *
+ * import {myThemeTheme} from './theme/my-theme';
+ * import './theme/my-theme.css';
+ *
+ * Unbuilt, `<Theme>` injects a <style> tag at hydration instead — fine for
+ * dev and client-only apps, but under SSR the component overrides flash on
+ * hydration. Build for Next.js and Remix. Run the build after every edit:
+ * it also validates the theme and regenerates the types for custom
+ * variants.
+ *
+ * 4. LOOK AT IT IN BOTH COLOUR MODES before you ship, including the states you
+ * did not write. Full guide: `astryx docs theme`.
+ *
+ * SYNC: this template mirrors the theme system. When you change one of these,
+ * update it here — scripts/check-theme-template.test.mjs fails when they drift:
+ * - /packages/core/src/theme/defineTheme.ts (the fields)
+ * - /packages/core/src/theme/tokens.stylex.ts (the token families)
+ * - /packages/core/src/theme/expandColorScale.ts
+ * - /packages/core/src/theme/expandTypeScale.ts
+ * - /packages/core/src/theme/expandRadiusScale.ts
+ * - /packages/core/src/theme/expandMotionScale.ts
+ */
+
+import {defineTheme} from '@astryxdesign/core/theme';
+// import {dracula} from '@astryxdesign/core/theme/syntax';
+// import {neutralTheme} from '@astryxdesign/theme-neutral';
+
+export const myTheme = defineTheme({
+ /** Required. Becomes the `data-astryx-theme` attribute and the registry key. */
+ name: 'my-theme',
+
+ /**
+ * Start from another theme instead of the defaults. Tokens are copied then
+ * overridden, `components` deep-merge, `icons` shallow-merge — but the scale
+ * configs below REPLACE the base's rather than merging, because they are
+ * inputs to a generator, not values.
+ *
+ * Reference: `astryx theme list` (themes you can install and extend).
+ */
+ // extends: neutralTheme,
+
+ // ───────────────────────────────────────────────────────────────────────
+ // Scale configs — a few parameters generate a whole family of tokens.
+ // Reach for these first. They keep a theme internally consistent and cover
+ // far more ground than you would hand-write.
+ // ───────────────────────────────────────────────────────────────────────
+
+ /**
+ * Generates the neutral ramp and the accent tokens from one seed colour
+ * using the HCT perceptual model: surfaces, text, icons, borders, muted
+ * fills, hover and pressed overlays — light and dark both.
+ *
+ * accent seed hex; omit to keep the default accent and re-tone only
+ * the neutrals
+ * neutralStyle 'warm' | 'cool' | 'neutral' — the temperature of the greys
+ * contrast 'standard' | 'high' — 'high' widens the text/surface tone
+ * gap, for dense data UI or bright and clinical screens
+ *
+ * Whatever seed you pass, generated text holds >= 4.5:1 against its surface
+ * and --color-border-emphasized >= 3:1. Two limits on that guarantee:
+ *
+ * - It covers what this config generates. Write one side of a pair by hand
+ * in `tokens` below — an accent without its --color-on-accent, a surface
+ * without its text — and you own the contrast for that pair.
+ * - Status colours (success, warning, error) and the categorical data hues
+ * are not derived from the accent. They keep their defaults, which are
+ * tuned for the default surfaces; check them against yours.
+ *
+ * Either way the check is the same: resolve the pair in BOTH modes and
+ * measure it. `useTheme()` and `resolveThemeTokens()` return the resolved
+ * values, and the rendered DOM is the final word.
+ *
+ * Reference: `astryx docs color` for what each semantic role means,
+ * `astryx docs tokens` for every colour token and its light/dark default.
+ */
+ color: {accent: '#0064E0', neutralStyle: 'cool', contrast: 'standard'},
+
+ /**
+ * Type scale and the three font roles.
+ * scale.base body size in px; scale.ratio step between sizes
+ * (1.125 tight/dense · 1.2 default · 1.333 dramatic)
+ * body / heading / code: {family, fallbacks, weight, weights}
+ * heading inherits family and fallbacks from body when omitted; `weights`
+ * sets per-level weight for headings 1–6.
+ *
+ * See §2 above — naming a family here does not load it.
+ *
+ * Reference: `astryx docs typography`.
+ */
+ typography: {
+ scale: {base: 16, ratio: 1.2},
+ body: {family: 'Inter', fallbacks: '-apple-system, system-ui, sans-serif'},
+ heading: {weight: 'semibold', weights: {1: 'bold', 2: 'bold'}},
+ code: {
+ family: 'Geist Mono',
+ fallbacks: '"SF Mono", ui-monospace, monospace',
+ },
+ },
+
+ /**
+ * Radius scale. `base` is the unit in px; `multiplier` scales every step
+ * (0 = square and brutalist, 2 = very soft). --radius-none and --radius-full
+ * are fixed and never scaled.
+ *
+ * Reference: `astryx docs shape`.
+ */
+ radius: {base: 4, multiplier: 1},
+
+ /**
+ * Duration scale in ms. Each of fast/medium/slow also gets a -min and -max
+ * sibling computed with `ratio` (min = base × ratio, max = base ÷ ratio), so
+ * a component can pick a longer or shorter variant of the same tempo.
+ * Snappy {fast: 100, medium: 250} · Default {fast: 175, medium: 410, slow: 975}
+ * Cinematic {fast: 200, medium: 500, slow: 1200}
+ * `easing` overrides --ease-standard.
+ *
+ * Reference: `astryx docs motion`.
+ */
+ motion: {fast: 175, medium: 410, slow: 975, ratio: 0.75},
+
+ // ───────────────────────────────────────────────────────────────────────
+ // tokens — explicit overrides, which beat anything the scales generated.
+ // A string applies to both colour modes; a [light, dark] tuple compiles to
+ // CSS light-dark(). List only what you want to change.
+ //
+ // `astryx docs tokens` PRINTS THE WHOLE TABLE — every token with its light
+ // and dark default. Read it before hand-writing colours: most of what you
+ // want already has a semantic name, and the defaults tell you what you are
+ // moving away from.
+ //
+ // The families, so you know what exists:
+ // --color-* accent, on-accent · background-{body,surface,card,popover,
+ // muted,inverted} · text-* · icon-* · border,
+ // border-emphasized · overlay{,-hover,-pressed} ·
+ // success/warning/error (+ -muted, on-*) · skeleton, track,
+ // shadow, tint-hover · categorical {blue,cyan,gray,green,
+ // orange,pink,purple,red,teal,yellow} ×
+ // {background,border,icon,text}
+ // --spacing-* 0 · 0-5 · 1 … 12
+ // --size-element-* sm · md · lg (control heights)
+ // --focus-outline-* width · style · color · offset
+ // --radius-* none · inner · element · container · page · chat · full
+ // --shadow-* low/med/high + inset-{hover,selected,success,warning,error}
+ // --duration-* {fast,medium,slow} × {-min, base, -max}
+ // --ease-standard
+ // --font-family-* body · heading · code
+ // --font-size-* 4xs … 5xl
+ // --font-weight-* normal · medium · semibold · bold
+ // --text-* {heading-1…6, body, large, label, code, supporting,
+ // display-1…3} × {-size, -weight, -leading}
+ // --color-syntax-* code highlighting · --color-data-* charts
+ // ───────────────────────────────────────────────────────────────────────
+ tokens: {
+ '--color-accent': ['#0064E0', '#2694FE'],
+ // Changing an accent means owning its on-colour: this is the label that
+ // sits on top of the fill above, in each mode.
+ '--color-on-accent': ['#FFFFFF', '#FFFFFF'],
+ '--color-background-body': ['#F1F4F7', '#111112'],
+ '--color-background-surface': ['#FFFFFF', '#1F1F22'],
+ '--focus-outline-color': 'var(--color-accent)',
+ '--shadow-low': '0 1px 2px light-dark(#0000001A, #00000066)',
+ },
+
+ // ───────────────────────────────────────────────────────────────────────
+ // components — per-component CSS, emitted inside
+ // `@scope ([data-astryx-theme="my-theme"])`, so it only touches your theme.
+ //
+ // Keys are the component's stable class minus the `astryx-` prefix
+ // (`astryx-button` → `button`, `astryx-side-nav-item` → `side-nav-item`),
+ // including inner parts like `progressbar-fill`.
+ //
+ // `astryx component <Name>` IS THE REFERENCE HERE. It prints that
+ // component's theming targets, the visual props and states you can key on,
+ // its public CSS variables with defaults, and which standard CSS properties
+ // it expands. `astryx component --list` names every component, and
+ // `astryx docs styling` covers the escape hatches outside a theme.
+ //
+ // Style-key forms:
+ // 'base' every instance
+ // 'variant:ghost' one prop value (any visual prop, not just variant)
+ // 'variant:ghost+size:sm' intersection of two
+ // 'checked' a state the component reflects
+ // ':hover' / ':focus-visible' / ':disabled' — nested inside any of the above
+ //
+ // Write ordinary CSS properties: `borderRadius` and `padding` expand into
+ // the component's internal vars for you, concentric radius math included.
+ // Set a public CSS var directly when no standard property reaches it — take
+ // the name from `astryx component <Name>`, since a var no component defines
+ // compiles to CSS that never applies. Never set a private `--_`-prefixed
+ // var; the build rejects it.
+ // ───────────────────────────────────────────────────────────────────────
+ components: {
+ button: {
+ base: {
+ borderRadius: 'var(--radius-full)',
+ fontWeight: 'var(--font-weight-semibold)',
+ // A public var from `astryx component Button` — no CSS-property
+ // equivalent exists for it.
+ '--button-focus-offset': '2px',
+ // Interaction states live inside the same block.
+ ':hover': {transform: 'translateY(-1px)'},
+ ':active': {transform: 'translateY(0)'},
+ },
+ 'variant:ghost': {borderWidth: '1px', borderStyle: 'solid'},
+ 'variant:destructive+size:sm': {letterSpacing: '0.02em'},
+ // A value that is not built in becomes a NEW variant: `astryx theme
+ // build` writes the module augmentation, so <Button variant="quiet" />
+ // typechecks wherever this theme is active. Add one only where the
+ // product will render it — an unused variant is invisible work.
+ 'variant:quiet': {
+ backgroundColor: 'var(--color-background-muted)',
+ color: 'var(--color-text-secondary)',
+ },
+ },
+ // Container components take `padding` too; it expands to their layout tokens.
+ card: {
+ base: {
+ borderRadius: 'var(--radius-container)',
+ padding: 'var(--spacing-6)',
+ },
+ },
+ // The same mechanism adds custom Text types: <Text type="hero" />.
+ text: {'type:hero': {fontSize: 'var(--font-size-4xl)', lineHeight: '1.05'}},
+ },
+
+ // ───────────────────────────────────────────────────────────────────────
+ // Everything below takes React values, so it needs a .tsx file or an
+ // imported module. Commented out for that reason.
+ // ───────────────────────────────────────────────────────────────────────
+
+ /**
+ * Swap the artwork behind semantic icon names — every component that asks
+ * for `check`, `close`, `chevron-down` gets yours.
+ * Reference: `astryx docs icons` lists the names.
+ */
+ // icons: {check: <MyCheck />, close: <MyClose />},
+
+ /**
+ * Replace the small components that DRAW control state — the checkbox box,
+ * the radio dot, the mark on a chosen option — by indicator name rather than
+ * per call site. Replacing `check` re-skins every single-selection mark in
+ * the app at once.
+ * Reference: `astryx component Indicator`.
+ */
+ // indicators: {check: RadioIndicator},
+
+ /**
+ * Code highlighting: sets the --color-syntax-* tokens. Presets live in
+ * `@astryxdesign/core/theme/syntax`.
+ */
+ // syntax: dracula,
+
+ /**
+ * Content sitting on an inverted surface — a dark toast in light mode, a
+ * light popover in dark mode. Same shape as the theme itself (tokens and
+ * components). Sensible values are generated if you say nothing, so override
+ * only where your palette needs it.
+ * Reference: `astryx component MediaTheme`, which reads these.
+ */
+ // onDark: {tokens: {'--color-accent': '#90CAF9'}, components: {button: {'variant:ghost': {borderWidth: '1px'}}}},
+ // onLight: {tokens: {'--color-accent': '#0B5FCC'}},
+});
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index 6907a989f2..e78beb22a4 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -30,6 +30,7 @@ import {logger} from '../../../api/logger.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {themeAdd} from '../../../api/theme/add/add.mjs';
+import {themeTemplate} from '../../../api/theme/template/template.mjs';
import {themeList} from '../../../api/theme/list/list.mjs';
import {themeBuild, importSpecifier} from '../../../api/theme/build/build.mjs';
import {defineCommand} from '../lib/define-command.mjs';
@@ -37,9 +38,11 @@ import {doc as themeGroup} from './theme.doc.mjs';
import {doc as themeBuildCommand} from './theme-build.doc.mjs';
import {doc as themeListCommand} from './theme-list.doc.mjs';
import {doc as themeAddCommand} from './theme-add.doc.mjs';
+import {doc as themeTemplateCommand} from './theme-template.doc.mjs';
import {doc as themeBuildFn} from '../../../api/theme/themeBuild.doc.mjs';
import {doc as themeListFn} from '../../../api/theme/themeList.doc.mjs';
import {doc as themeAddFn} from '../../../api/theme/themeAdd.doc.mjs';
+import {doc as themeTemplateFn} from '../../../api/theme/themeTemplate.doc.mjs';
/**
* Path to this CLI's real entry (clients/cli/bin/astryx.mjs), resolved from
@@ -363,4 +366,51 @@ export function registerTheme(program) {
);
},
});
+
+ defineCommand(theme, themeTemplateCommand, {
+ fn: themeTemplateFn,
+ action: (
+ /** @type {string | undefined} */ targetPath,
+ /** @type {{overwrite?: boolean}} */ options,
+ ) => {
+ const json = program.opts().json || false;
+
+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeTemplateResponse} */
+ let result;
+ try {
+ result = themeTemplate({
+ targetPath,
+ overwrite: options.overwrite,
+ cwd: process.cwd(),
+ });
+ } catch (e) {
+ const err =
+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
+ cliError(err.message, {
+ suggestions: err.suggestions || [],
+ code: err.code,
+ });
+ return;
+ }
+
+ if (json) return jsonOut(result);
+
+ const invocation = getCliInvocation(process.cwd());
+ if (!result.data.written) {
+ emit(
+ text(`[skip] ${result.data.path} already exists — left as is.`),
+ text(`Pass --overwrite to replace it with a fresh copy.`),
+ );
+ return;
+ }
+ emit(
+ text(`[ok] Wrote ${result.data.path}`),
+ text(
+ 'It documents every defineTheme field, the token families, and the component override syntax. ' +
+ 'Copy what you need into your own theme file, then delete it.',
+ ),
+ code(`${invocation} theme build ${result.data.path}`),
+ );
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/init.behavior.test.mjs b/packages/cli/clients/cli/commands/init.behavior.test.mjs
index 5f825eff4c..66c38d9a04 100644
--- a/packages/cli/clients/cli/commands/init.behavior.test.mjs
+++ b/packages/cli/clients/cli/commands/init.behavior.test.mjs
@@ -71,13 +71,24 @@ describe('astryx init --features', () => {
expect(exists('AGENTS.md')).toBe(true);
});
- it('--features theme writes no files and points at the theme workflow', async () => {
+ it('--features theme writes the annotated theme template', async () => {
const {status, stdout} = await runCli(['init', '--features', 'theme'], {cwd: tmpDir});
expect(status).toBe(0);
- expect(fs.readdirSync(tmpDir)).toEqual([]);
+ expect(exists('theme.template.ts')).toBe(true);
+ expect(read('theme.template.ts')).toMatch(/defineTheme/);
+ expect(read('theme.template.ts')).not.toMatch(/Copyright \(c\) Meta Platforms/);
expect(stdout).toMatch(/theme/i);
});
+ it('--features theme never clobbers an existing theme.template.ts', async () => {
+ // Someone's edited copy outranks ours; re-running init must be safe.
+ fs.writeFileSync(path.join(tmpDir, 'theme.template.ts'), '// mine\n');
+ const {status, stdout} = await runCli(['init', '--features', 'theme'], {cwd: tmpDir});
+ expect(status).toBe(0);
+ expect(read('theme.template.ts')).toBe('// mine\n');
+ expect(stdout).toMatch(/already exists/);
+ });
+
it('rejects an unknown feature with exit 1 and a helpful message', async () => {
const {status, stderr} = await runCli(['init', '--features', 'bogus'], {cwd: tmpDir});
expect(status).toBe(1);
diff --git a/packages/cli/clients/cli/commands/theme-template.behavior.test.mjs b/packages/cli/clients/cli/commands/theme-template.behavior.test.mjs
new file mode 100644
index 0000000000..fb58372e52
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-template.behavior.test.mjs
@@ -0,0 +1,85 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CLI behavior for `astryx theme template`.
+ *
+ * The API leaf is covered by api/theme/template/template.test.mjs; what is only
+ * reachable here is the terminal binding — which message the user sees, and the
+ * JSON envelope. The first version of this command read `result.written`
+ * instead of `result.data.written`, so it wrote the file and then told the user
+ * it had skipped: a receipt read at the wrong depth is invisible to a unit test
+ * of the leaf.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-cli-theme-template-'));
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'tmp', private: true}),
+ );
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+const read = f => fs.readFileSync(path.join(tmpDir, f), 'utf-8');
+
+describe('astryx theme template', () => {
+ it('writes the template and says it wrote it', async () => {
+ const {status, stdout} = await runCli(['theme', 'template'], {cwd: tmpDir});
+
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/Wrote theme\.template\.ts/);
+ expect(stdout).not.toMatch(/already exists/);
+ expect(read('theme.template.ts')).toMatch(/defineTheme/);
+ });
+
+ it('leaves an existing file alone, and says that instead', async () => {
+ fs.writeFileSync(path.join(tmpDir, 'theme.template.ts'), '// mine\n');
+
+ const {status, stdout} = await runCli(['theme', 'template'], {cwd: tmpDir});
+
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/already exists/);
+ expect(read('theme.template.ts')).toBe('// mine\n');
+ });
+
+ it('replaces it with --overwrite', async () => {
+ fs.writeFileSync(path.join(tmpDir, 'theme.template.ts'), '// mine\n');
+
+ const {status} = await runCli(['theme', 'template', '--overwrite'], {cwd: tmpDir});
+
+ expect(status).toBe(0);
+ expect(read('theme.template.ts')).toMatch(/defineTheme/);
+ });
+
+ it('returns a theme.template envelope under --json', async () => {
+ const {status, stdout} = await runCli(['--json', 'theme', 'template'], {cwd: tmpDir});
+
+ expect(status).toBe(0);
+ const payload = JSON.parse(stdout);
+ expect(payload.type).toBe('theme.template');
+ expect(payload.data).toEqual({
+ path: 'theme.template.ts',
+ written: true,
+ reason: null,
+ });
+ });
+
+ it('refuses a path that escapes the project', async () => {
+ const {status, stderr} = await runCli(['theme', 'template', '../escaped.ts'], {
+ cwd: tmpDir,
+ });
+
+ expect(status).toBe(1);
+ expect(stderr).toMatch(/outside the project root/);
+ expect(fs.existsSync(path.join(path.dirname(tmpDir), 'escaped.ts'))).toBe(false);
+ });
+});
diff --git a/packages/cli/clients/cli/commands/theme-template.doc.mjs b/packages/cli/clients/cli/commands/theme-template.doc.mjs
new file mode 100644
index 0000000000..af4087d078
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-template.doc.mjs
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx theme template`. The terminal binding of the
+ * `themeTemplate()` function (referenced via `fn`); its args/flags map to that
+ * function's params so a converter can build Commander config + --help from one
+ * source of truth.
+ * @position packages/cli/clients/cli/commands — command documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const doc = {
+ type: 'command',
+ name: 'theme template',
+ displayName: 'astryx theme template',
+ namespace: 'cli',
+ summary: 'Write the annotated theme template into your project',
+ description:
+ 'Writes theme.template.ts: the annotated reference for the whole theme surface — every ' +
+ 'defineTheme field, the token families, the component override syntax, and how a theme is ' +
+ 'consumed — naming the CLI command that prints the authoritative reference for each. Read ' +
+ 'it, copy what you need into your own theme file, delete it. Use `theme add <slug>` instead ' +
+ 'to start from a theme we ship. Leaves an existing file untouched unless --overwrite.',
+ fn: 'themeTemplate',
+ args: [{name: 'path', param: 'options.targetPath', required: false}],
+ options: [
+ {
+ flag: '-f, --overwrite',
+ param: 'options.overwrite',
+ description: 'Replace an existing file',
+ },
+ ],
+ examples: [
+ {label: 'Write it at the project root', cli: 'astryx theme template'},
+ {label: 'Somewhere else', cli: 'astryx theme template src/themes/starter.ts'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success, including when an existing file was left untouched'},
+ {code: 1, when: 'the target path escapes the project'},
+ ],
+ related: ['theme add', 'theme list', 'theme build'],
+};
diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjs
index 504133ed43..a92a933fc2 100644
--- a/packages/cli/clients/cli/commands/theme.doc.mjs
+++ b/packages/cli/clients/cli/commands/theme.doc.mjs
@@ -17,8 +17,8 @@ export const doc = {
description:
'The theme command group. Running astryx theme with no subcommand prints the ' +
'subcommand list; the work happens in the subcommands: compile a theme (build), ' +
- 'scaffold one into your project (add), or list the bundled themes (list).',
- subcommands: ['build', 'add', 'list'],
+ 'scaffold one into your project (add), start a custom one from the annotated template (template), or list the bundled themes (list).',
+ subcommands: ['build', 'add', 'list', 'template'],
examples: [
{label: 'List bundled themes', cli: 'astryx theme list'},
{label: 'Scaffold a theme', cli: 'astryx theme add matcha'},
diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjs
index 989cb81416..bb054bb0a4 100644
--- a/packages/cli/clients/cli/index.mjs
+++ b/packages/cli/clients/cli/index.mjs
@@ -69,6 +69,7 @@ export const JSON_SUPPORTED = new Set([
'theme build',
'theme list',
'theme add',
+ 'theme template',
'upgrade',
'manifest',
'doctor',
diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjs
index 8d7510d957..16e2c75c10 100644
--- a/packages/cli/clients/cli/lib/manifest.mjs
+++ b/packages/cli/clients/cli/lib/manifest.mjs
@@ -75,6 +75,7 @@ export const RESPONSE_TYPES = {
'theme build': ['theme.build', 'theme.build.check'],
'theme list': ['theme.list'],
'theme add': ['theme.list', 'theme.add'],
+ 'theme template': ['theme.template'],
upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],
manifest: ['manifest'],
doctor: ['doctor'],
@@ -113,6 +114,7 @@ const EXAMPLES = {
'astryx theme add matcha',
'astryx theme add matcha ./src/themes/matcha',
],
+ 'theme template': ['astryx theme template', 'astryx theme template --json'],
upgrade: ['astryx upgrade --json'],
manifest: ['astryx manifest --json', 'astryx --json'],
doctor: ['astryx doctor', 'astryx doctor --json'],
diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjs
index eef9829bf8..562da5688d 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs
@@ -354,7 +354,7 @@ export function generateCompressedIndex(version, {coreDir, invocation = getCliIn
} else {
lines.push("- Custom styling: component props first; else style/className with tokens — var(--color-*|--spacing-*|--radius-*). No raw hex/px. (No StyleX/Tailwind compiler here — don't use xstyle/utility classes.)");
}
- lines.push('- Tokens for every value (`astryx docs tokens`). Brand/accent via `astryx theme` — never override --color-* in :root.');
+ lines.push('- Tokens for every value (`astryx docs tokens`). Brand/accent belongs in the theme (`astryx theme list` / `theme add <slug>`, or `astryx theme template` for a custom one) — never override --color-* in :root.');
// Self-check — post-generation pass. Validated via vibe tests (internal/vibe-tests/
// prompt-purity-test): on complex multi-step UIs the rules above alone still leave raw
// CSS in ~11-13% of runs; a re-read-and-fix pass cuts that ~4x at negligible token cost.
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 5febe82138..15ffa670ef 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -183,6 +183,11 @@ export const doc = {
description:
'A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written.',
},
+ {
+ value: 'theme.template',
+ description:
+ 'A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not — `exists` when a file was already there, which is a success.',
+ },
// upgrade
{
diff --git a/packages/cli/foundation/text/copyright-header.mjs b/packages/cli/foundation/text/copyright-header.mjs
new file mode 100644
index 0000000000..b1e10f5ee8
--- /dev/null
+++ b/packages/cli/foundation/text/copyright-header.mjs
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Strips our repo's copyright header from files we scaffold into someone
+ * else's project.
+ *
+ * Every file in this repo carries the Meta copyright header, and several
+ * commands copy repo files out verbatim — `theme add` (bundled theme sources),
+ * `init --features theme` (the annotated theme template). A consumer's own
+ * source tree should not inherit our boilerplate, and their lint may well
+ * reject it.
+ *
+ * SYNC: the same regex is applied by apps/docsite/src/lib/codeExamples.ts for
+ * rendered code samples. That copy lives in a different package (the docsite
+ * cannot import CLI internals), so a change to the header format has to land in
+ * both.
+ */
+
+/**
+ * Matches our header at the very start of a file, with the leading BOM and/or
+ * shebang captured so they survive the strip.
+ */
+const META_COPYRIGHT_HEADER_RE =
+ /^(\uFEFF?(?:#![^\r\n]*(?:\r?\n))?)\/\/ Copyright \(c\) Meta Platforms, Inc\. and affiliates\.\r?\n(?:\r?\n)*/;
+
+/**
+ * Remove the leading Meta copyright header, preserving any BOM/shebang before
+ * it. Returns the source unchanged when the header is absent.
+ *
+ * @param {string} source
+ * @returns {string}
+ */
+export function stripCopyrightHeader(source) {
+ return source.replace(META_COPYRIGHT_HEADER_RE, '$1');
+}
diff --git a/packages/cli/foundation/text/copyright-header.test.mjs b/packages/cli/foundation/text/copyright-header.test.mjs
new file mode 100644
index 0000000000..434afbcb2f
--- /dev/null
+++ b/packages/cli/foundation/text/copyright-header.test.mjs
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for the shared copyright-header stripper.
+ *
+ * Two commands copy repo files into a consumer's project (`theme add`,
+ * `init --features theme`); this is what keeps our boilerplate out of their
+ * tree. The BOM/shebang cases are the ones worth pinning — a naive strip
+ * corrupts the file rather than merely leaving a stray comment.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {stripCopyrightHeader} from './copyright-header.mjs';
+
+const HEADER = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n';
+
+describe('stripCopyrightHeader', () => {
+ it('removes the header and the blank line after it', () => {
+ expect(stripCopyrightHeader(`${HEADER}\nexport const a = 1;\n`)).toBe(
+ 'export const a = 1;\n',
+ );
+ });
+
+ it('removes it with no blank line after', () => {
+ expect(stripCopyrightHeader(`${HEADER}export const a = 1;\n`)).toBe(
+ 'export const a = 1;\n',
+ );
+ });
+
+ it('keeps a shebang, which must stay on line 1', () => {
+ expect(stripCopyrightHeader(`#!/usr/bin/env node\n${HEADER}\nrun();\n`)).toBe(
+ '#!/usr/bin/env node\nrun();\n',
+ );
+ });
+
+ it('keeps a BOM', () => {
+ expect(stripCopyrightHeader(`\uFEFF${HEADER}\nexport const a = 1;\n`)).toBe(
+ '\uFEFFexport const a = 1;\n',
+ );
+ });
+
+ it('handles CRLF line endings', () => {
+ expect(
+ stripCopyrightHeader(
+ '// Copyright (c) Meta Platforms, Inc. and affiliates.\r\n\r\nexport const a = 1;\r\n',
+ ),
+ ).toBe('export const a = 1;\r\n');
+ });
+
+ it('leaves a file without the header alone', () => {
+ expect(stripCopyrightHeader('export const a = 1;\n')).toBe('export const a = 1;\n');
+ });
+
+ it('only strips at the top — a mention further down is content', () => {
+ const source = `export const a = 1;\n${HEADER}`;
+ expect(stripCopyrightHeader(source)).toBe(source);
+ });
+});
diff --git a/packages/cli/tsconfig.template-docs.json b/packages/cli/tsconfig.template-docs.json
index b342d3ea7a..da5d77fb44 100644
--- a/packages/cli/tsconfig.template-docs.json
+++ b/packages/cli/tsconfig.template-docs.json
@@ -8,6 +8,7 @@
},
"include": [
"assets/templates/**/template.doc.mjs",
- "assets/templates/**/*.doc.mjs"
+ "assets/templates/**/*.doc.mjs",
+ "assets/theme.template.ts"
]
}
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index e557c4998a..f041d4a9d3 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -28,6 +28,12 @@
* <App />
* </Theme>
* ```
+ *
+ * SYNC: `DefineThemeInput` is the theme surface. Adding, removing, or renaming
+ * a field means updating:
+ * - /packages/cli/assets/theme.template.ts (documents every field; the
+ * drift guard is scripts/check-theme-template.test.mjs)
+ * - /packages/cli/assets/docs/theme.doc.mjs (`astryx docs theme`)
*/
import type {IconRegistry} from '../Icon/globalIconRegistry';
diff --git a/packages/core/src/theme/expandColorScale.ts b/packages/core/src/theme/expandColorScale.ts
index a584a2df11..a1c439f7fe 100644
--- a/packages/core/src/theme/expandColorScale.ts
+++ b/packages/core/src/theme/expandColorScale.ts
@@ -28,6 +28,7 @@
*
* SYNC: When modified, update:
* - /packages/core/src/theme/defineTheme.ts
+ * - /packages/cli/assets/theme.template.ts (the annotated field reference)
*/
import {contrastRatio} from './contrast';
diff --git a/packages/core/src/theme/expandMotionScale.ts b/packages/core/src/theme/expandMotionScale.ts
index f7be0fb405..60feb0602e 100644
--- a/packages/core/src/theme/expandMotionScale.ts
+++ b/packages/core/src/theme/expandMotionScale.ts
@@ -18,6 +18,7 @@
* SYNC: When modified, update:
* - /packages/core/src/theme/expandMotionScale.test.ts
* - /packages/core/src/theme/defineTheme.ts
+ * - /packages/cli/assets/theme.template.ts (the annotated field reference)
*/
// =============================================================================
diff --git a/packages/core/src/theme/expandRadiusScale.ts b/packages/core/src/theme/expandRadiusScale.ts
index 18db9736b3..fad132b2ff 100644
--- a/packages/core/src/theme/expandRadiusScale.ts
+++ b/packages/core/src/theme/expandRadiusScale.ts
@@ -22,6 +22,7 @@
* SYNC: When modified, update:
* - /packages/core/src/theme/expandRadiusScale.test.ts
* - /packages/core/src/theme/defineTheme.ts
+ * - /packages/cli/assets/theme.template.ts (the annotated field reference)
*/
// =============================================================================
diff --git a/packages/core/src/theme/expandTypeScale.ts b/packages/core/src/theme/expandTypeScale.ts
index 7efc95667b..88a7be9db4 100644
--- a/packages/core/src/theme/expandTypeScale.ts
+++ b/packages/core/src/theme/expandTypeScale.ts
@@ -44,6 +44,7 @@
* SYNC: When modified, update:
* - /packages/core/src/theme/expandTypeScale.test.ts
* - /packages/core/src/theme/defineTheme.ts
+ * - /packages/cli/assets/theme.template.ts (the annotated field reference)
*/
// =============================================================================
diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.ts
index d0c93be655..4ea09ea68e 100644
--- a/packages/core/src/theme/tokens.stylex.ts
+++ b/packages/core/src/theme/tokens.stylex.ts
@@ -8,7 +8,9 @@
* - *Vars: CSS custom properties that themes can override via createTheme
*
* SYNC: When modified, run `node scripts/generate-token-docs.mjs` to update docs.
- * CI checks for drift via --check flag.
+ * CI checks for drift via --check flag. Adding or removing a token FAMILY (a
+ * whole `*Defaults` group) also means updating:
+ * - /packages/cli/assets/theme.template.ts (its inventory of what exists)
*
* Domain tokens (syntax highlighting, data visualization) live separately in
* /packages/core/src/theme/domainTokens/ — they're tree-shaken from core components.
diff --git a/scripts/check-theme-template.test.mjs b/scripts/check-theme-template.test.mjs
new file mode 100644
index 0000000000..e82210c912
--- /dev/null
+++ b/scripts/check-theme-template.test.mjs
@@ -0,0 +1,297 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Drift guard for the shipped theme template.
+ *
+ * `packages/cli/assets/theme.template.ts` is the annotated map of the theme
+ * surface: every `defineTheme` field, the token families, the component
+ * override syntax. `astryx theme template` copies it into a consumer's
+ * project, so a claim that has rotted is not a stale comment in our repo — it
+ * is wrong instruction sitting in someone else's.
+ *
+ * Documentation rots silently, and this kind especially: the theme docs shipped
+ * `--button-press-scale` (#5012) for long enough that a generated theme carried
+ * a declaration no component could ever read. SYNC comments in the theme
+ * sources point here; this file is what makes them more than a wish.
+ *
+ * What is checked — all of it derived from live sources, never hardcoded:
+ * 1. Every `DefineThemeInput` field is documented (and nothing invented).
+ * 2. Every settable token family appears in the inventory.
+ * 3. Every `--token` the template names is a real token.
+ * 4. Every component key is a real theming target, and every public
+ * `--var` it sets is one that component declares.
+ * 5. Every `astryx docs <topic>` it cites exists.
+ * 6. Every theme source carrying a SYNC reference here still exists.
+ *
+ * That the template COMPILES is proved separately, end to end, by
+ * `builds the shipped theme template with no warnings` in
+ * packages/cli/api/theme/build/build.test.mjs.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, it, expect} from 'vitest';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(__dirname, '..');
+const TEMPLATE = path.join(REPO_ROOT, 'packages/cli/assets/theme.template.ts');
+const THEME_SRC = path.join(REPO_ROOT, 'packages/core/src/theme');
+const CORE_SRC = path.join(REPO_ROOT, 'packages/core/src');
+const DOCS_DIR = path.join(REPO_ROOT, 'packages/cli/assets/docs');
+
+const template = fs.readFileSync(TEMPLATE, 'utf-8');
+
+/** Theme sources whose SYNC comments name the template. */
+const SYNC_SOURCES = [
+ 'defineTheme.ts',
+ 'tokens.stylex.ts',
+ 'expandColorScale.ts',
+ 'expandTypeScale.ts',
+ 'expandRadiusScale.ts',
+ 'expandMotionScale.ts',
+];
+
+// ---------------------------------------------------------------------------
+// Live facts
+// ---------------------------------------------------------------------------
+
+const defineThemeSrc = fs.readFileSync(path.join(THEME_SRC, 'defineTheme.ts'), 'utf-8');
+const tokensSrc = fs.readFileSync(path.join(THEME_SRC, 'tokens.stylex.ts'), 'utf-8');
+
+/** Field names declared on `DefineThemeInput`. */
+function defineThemeFields() {
+ const body = defineThemeSrc.match(
+ /export interface DefineThemeInput \{([\s\S]*?)\n\}/,
+ );
+ if (!body) throw new Error('DefineThemeInput not found in defineTheme.ts');
+ return [...body[1].matchAll(/^ {2}(\w+)\??:/gm)].map(m => m[1]);
+}
+
+/** Every `*Defaults` group in tokens.stylex.ts, with its token names. */
+function tokenGroups() {
+ /** @type {Record<string, string[]>} */
+ const groups = {};
+ for (const chunk of tokensSrc.split('export const ').slice(1)) {
+ const name = chunk.split(/[\s:=]/)[0];
+ if (!name.endsWith('Defaults')) continue;
+ const body = chunk.split('export const')[0];
+ groups[name] = [...body.matchAll(/'(--[a-zA-Z0-9-]+)'\s*:/g)].map(m => m[1]);
+ }
+ return groups;
+}
+
+/**
+ * The token groups a theme can actually set — the ones unioned into
+ * `CoreTokenName`. `borderDefaults` is deliberately outside it today (#5017):
+ * `--border-width` is documented and emitted but rejected by the type, so the
+ * template must not teach it. When #5017 lands, that family joins the union and
+ * this guard starts requiring the template to cover it.
+ */
+function settableTokenGroups() {
+ const union = defineThemeSrc.match(
+ /export type CoreTokenName =([\s\S]*?);/,
+ );
+ if (!union) throw new Error('CoreTokenName not found in defineTheme.ts');
+ return [...union[1].matchAll(/typeof (\w+Defaults)/g)].map(m => m[1]);
+}
+
+/** Every documented theming target, and the public vars it declares. */
+function themingTargets() {
+ /** @type {Record<string, Set<string>>} */
+ const targets = {};
+ /** @type {Set<string>} */
+ const publicVars = new Set();
+ const walk = dir => {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const p = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(p);
+ continue;
+ }
+ if (!entry.name.endsWith('.doc.mjs')) continue;
+ const src = fs.readFileSync(p, 'utf-8');
+ for (const m of src.matchAll(/className:\s*'astryx-([a-z0-9-]+)'/g)) {
+ targets[m[1]] ??= new Set();
+ }
+ // `vars: [{name: '--button-focus-offset', ...}]` — private `--_` vars are
+ // not a theme's to set, so they are not collected.
+ for (const m of src.matchAll(/name:\s*'(--[a-z0-9-]+)'/g)) {
+ publicVars.add(m[1]);
+ }
+ }
+ };
+ walk(CORE_SRC);
+ return {targets, publicVars};
+}
+
+/** Doc topics `astryx docs <topic>` can print. */
+function docTopics() {
+ return fs
+ .readdirSync(DOCS_DIR)
+ .map(f => f.match(/^([\w-]+)\.doc\.mjs$/))
+ .filter(Boolean)
+ .map(m => m[1]);
+}
+
+// ---------------------------------------------------------------------------
+// Template claims
+// ---------------------------------------------------------------------------
+
+/**
+ * Top-level keys the template sets, plus the optional ones it shows commented
+ * out (`// syntax: dracula,`). A commented field must carry a value, so an
+ * ordinary prose comment is not mistaken for one.
+ */
+function templateFields() {
+ const set = [...template.matchAll(/^ {2}(\w+):/gm)].map(m => m[1]);
+ const commented = [...template.matchAll(/^ {2}\/\/ (\w+): .+,$/gm)].map(m => m[1]);
+ return [...new Set([...set, ...commented])];
+}
+
+/**
+ * Every CSS variable the template uses in a code position — set as a property
+ * (`'--x': …`) or read (`var(--x)`). Prose mentions of a family (`--spacing-*`)
+ * and CLI flags (`--list`) are not claims about a variable's existence.
+ */
+function templateVars() {
+ const set = [...template.matchAll(/'(--[a-z][a-z0-9-]*)':/g)].map(m => m[1]);
+ const read = [...template.matchAll(/var\((--[a-z][a-z0-9-]*)\)/g)].map(m => m[1]);
+ return [...new Set([...set, ...read])];
+}
+
+/**
+ * The inventory block — the comment listing what token families exist. Scoped
+ * deliberately: a family named only in a passing example (`var(--spacing-6)`)
+ * is not an inventory an author can read to learn what the system has.
+ */
+function templateInventory() {
+ const marker = '// The families, so you know what exists:';
+ const start = template.indexOf(marker);
+ if (start === -1) {
+ throw new Error(
+ `The token inventory marker ("${marker}") is gone from the template. ` +
+ `If the inventory moved, point this guard at its new home.`,
+ );
+ }
+ return template.slice(start, template.indexOf('\n tokens: {', start));
+}
+
+/**
+ * The prefix a family shares — `--spacing-`, `--font-weight-`, `--ease-standard`.
+ * A family is only "covered" when the template names this, which keeps the
+ * three `--font-*` families (family, size, weight) distinguishable instead of
+ * collapsing them into one prefix that any of them satisfies.
+ *
+ * @param {string[]} names
+ */
+function commonPrefix(names) {
+ return names.reduce((prefix, name) => {
+ let i = 0;
+ while (i < prefix.length && i < name.length && prefix[i] === name[i]) i++;
+ return prefix.slice(0, i);
+ });
+}
+
+/** Component keys in the template's `components` block. */
+function templateComponentKeys() {
+ const block = template.match(/\n {2}components: \{([\s\S]*?)\n {2}\},/);
+ if (!block) throw new Error('components block not found in the template');
+ return [...block[1].matchAll(/^ {4}'?([a-z][a-z0-9-]*)'?: \{/gm)].map(m => m[1]);
+}
+
+// ---------------------------------------------------------------------------
+// Guards
+// ---------------------------------------------------------------------------
+
+describe('theme template stays in sync with the theme system', () => {
+ it('documents every defineTheme field', () => {
+ const documented = new Set(templateFields());
+ const missing = defineThemeFields().filter(f => !documented.has(f));
+ expect(
+ missing,
+ `packages/cli/assets/theme.template.ts documents no ${missing.join(', ')} — ` +
+ `DefineThemeInput gained a field the template never mentions, so every ` +
+ `author who reads the template will not know it exists.`,
+ ).toEqual([]);
+ });
+
+ it('invents no field that defineTheme does not accept', () => {
+ const real = new Set([...defineThemeFields(), 'name']);
+ const invented = templateFields().filter(f => !real.has(f));
+ expect(
+ invented,
+ `The template shows ${invented.join(', ')}, which DefineThemeInput does ` +
+ `not accept — a field was renamed or removed and the template kept teaching it.`,
+ ).toEqual([]);
+ });
+
+ it('lists every settable token family in its inventory', () => {
+ const groups = tokenGroups();
+ const inventory = templateInventory();
+ const missing = settableTokenGroups().filter(group => {
+ const tokens = groups[group] ?? [];
+ if (tokens.length === 0) return false;
+ return !inventory.includes(commonPrefix(tokens));
+ });
+ expect(
+ missing,
+ `The template's token inventory covers no ${missing.join(', ')}. A whole ` +
+ `token family exists that an author reading the template cannot discover.`,
+ ).toEqual([]);
+ });
+
+ it('names only tokens and public vars that exist', () => {
+ const known = new Set(Object.values(tokenGroups()).flat());
+ const {publicVars} = themingTargets();
+ // Domain tokens (syntax, data-viz) live outside tokens.stylex.ts and are
+ // referenced by prefix in the inventory, not by full name.
+ const domainPrefixes = ['--color-syntax-', '--color-data-'];
+ const bogus = templateVars().filter(
+ v =>
+ !known.has(v) &&
+ !publicVars.has(v) &&
+ !domainPrefixes.some(p => v.startsWith(p) || p.startsWith(v)),
+ );
+ expect(
+ bogus,
+ `The template names ${bogus.join(', ')}, which no token group and no ` +
+ `component declares. A CSS variable nothing defines compiles to a ` +
+ `declaration that never applies (#5012).`,
+ ).toEqual([]);
+ });
+
+ it('overrides only real theming targets', () => {
+ const {targets} = themingTargets();
+ const unknown = templateComponentKeys().filter(k => !(k in targets));
+ expect(
+ unknown,
+ `The template themes ${unknown.join(', ')}, which is not a documented ` +
+ `theming target — the component was renamed or its class changed.`,
+ ).toEqual([]);
+ });
+
+ it('cites only doc topics that exist', () => {
+ const topics = new Set(docTopics());
+ const cited = [...new Set([...template.matchAll(/astryx docs ([a-z-]+)/g)].map(m => m[1]))];
+ const dead = cited.filter(t => !topics.has(t));
+ expect(
+ dead,
+ `The template tells authors to run \`astryx docs ${dead.join('`, `astryx docs ')}\`, ` +
+ `which prints nothing — the topic was renamed or removed.`,
+ ).toEqual([]);
+ });
+
+ it('is still named by the SYNC comment in every theme source that points here', () => {
+ const relTemplate = 'packages/cli/assets/theme.template.ts';
+ const orphaned = SYNC_SOURCES.filter(
+ f => !fs.readFileSync(path.join(THEME_SRC, f), 'utf-8').includes(relTemplate),
+ );
+ expect(
+ orphaned,
+ `${orphaned.join(', ')} lost the SYNC reference to the template. The ` +
+ `reference is how the next person editing the theme system learns the ` +
+ `template mirrors it.`,
+ ).toEqual([]);
+ });
+});