An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): theme build emits correct custom-variant type augmentations (#3469)
Joey9332fcff31ab
diff --git a/.changeset/theme-build-variant-augmentation.md b/.changeset/theme-build-variant-augmentation.mdnew file mode 100644index 0000000000..ff4d726997--- /dev/null+++ b/.changeset/theme-build-variant-augmentation.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx theme build`: custom component variants declared in a theme (e.g. `button['variant:accentOutline']`) now generate a type augmentation against the component's real interface (`ButtonVariantMap`) instead of a non-existent `XDS`-prefixed one, so `variant="accentOutline"` type-checks. Props with no augmentation point (closed unions like Button `size` or Heading `type`) are skipped instead of emitting dead augmentations, and the generated `.variants.d.ts` is now referenced from the theme's `.d.ts` so the augmentation actually loads. (#3371)++@josephfarinadiff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjsindex 8a8db47adf..a308300a6c 100644--- a/packages/cli/src/commands/build-theme.mjs+++ b/packages/cli/src/commands/build-theme.mjs@@ -175,14 +175,85 @@ async function getKnownValues(componentName) {return _knownValuesCache.get(componentName);}+/**+ * Resolve `@astryxdesign/core`'s package root relative to the CLI package. Core+ * and the CLI ship as siblings (`@astryxdesign/core`, `@astryxdesign/cli`), so+ * `../../../core` from `src/commands/` reaches core whether installed from npm+ * or run inside the monorepo. Returns null if it can't be found.+ */+function resolveCoreRoot() {+ const cliDir = path.dirname(fileURLToPath(import.meta.url));+ const coreRoot = path.resolve(cliDir, '../../../core');+ return fs.existsSync(coreRoot) ? coreRoot : null;+}++/**+ * Read the type declarations `@astryxdesign/core/<Component>` exposes so we can+ * check whether a given augmentation-target interface actually exists before+ * generating a module augmentation against it.+ *+ * Reads the shipped `dist/<Component>/index.d.ts` (what a consumer's TypeScript+ * actually sees), falling back to the `src/<Component>/index.ts` in the+ * monorepo. Returns the file contents, or '' if nothing is found.+ */+const _componentDeclCache = new Map();+function readComponentDeclarations(pascalName) {+ if (_componentDeclCache.has(pascalName)) {+ return _componentDeclCache.get(pascalName);+ }+ let contents = '';+ const coreRoot = resolveCoreRoot();+ if (coreRoot) {+ const candidates = [+ path.join(coreRoot, 'dist', pascalName, 'index.d.ts'),+ path.join(coreRoot, 'src', pascalName, 'index.ts'),+ ];+ for (const file of candidates) {+ try {+ if (fs.existsSync(file)) {+ contents = fs.readFileSync(file, 'utf-8');+ break;+ }+ } catch {+ // ignore and try the next candidate+ }+ }+ }+ _componentDeclCache.set(pascalName, contents);+ return contents;+}++/**+ * Determine whether `@astryxdesign/core/<Component>` exports an interface named+ * `interfaceName` that can be augmented via module augmentation.+ *+ * Only interfaces are extension points — closed literal-union types (e.g.+ * `HeadingType`, `ButtonSize`) are NOT augmentable, so a generated augmentation+ * against them is dead code. We check that the name is exported (directly or+ * re-exported) as a type/interface.+ */+function componentHasAugmentableInterface(pascalName, interfaceName) {+ const decl = readComponentDeclarations(pascalName);+ if (!decl) return false;+ // Word-boundary match so `ButtonVariantMap` doesn't match `XButtonVariantMap`.+ const re = new RegExp(`\\b${interfaceName}\\b`);+ return re.test(decl);+}+/*** Generate TypeScript declaration content with module augmentation for custom* component prop values found in the theme's `components` keys. Reads known* values from doc files to filter out base prop values.*- * Interface naming convention: Astryx + PascalCase(component) + PascalCase(prop) + Map- * banner + status → XDSBannerStatusMap- * button + variant → XDSButtonVariantMap+ * Interface naming convention: PascalCase(component) + PascalCase(prop) + Map+ * banner + status → BannerStatusMap+ * button + variant → ButtonVariantMap+ *+ * An augmentation is only emitted when `@astryxdesign/core/<Component>` actually+ * exports a matching interface. Props backed by closed literal-union types+ * (e.g. Button `size`, Heading `type`/`level`) have no augmentation point, so+ * generating a `declare module` block for them would be dead code — those are+ * skipped.** @param {object} themeDef - Theme definition (resolved by defineTheme)* @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed@@ -234,7 +305,14 @@ async function generateVariantDeclarationsAsync(themeDef) {const pascal = toPascalCase(component);const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);const modulePath = `@astryxdesign/core/${pascal}`;- const interfaceName = `XDS${pascal}${propPascal}Map`;+ const interfaceName = `${pascal}${propPascal}Map`;++ // Only augment interfaces that actually exist as an extension point in+ // core. Props backed by closed literal-union types (e.g. Button `size`,+ // Heading `type`/`level`) have no `*Map` interface — a `declare module`+ // block against a non-existent interface just creates a new, unused+ // interface and never extends the component's prop union, so skip it.+ if (!componentHasAugmentableInterface(pascal, interfaceName)) continue;sections.push(`declare module '${modulePath}' {`);sections.push(` interface ${interfaceName} {`);@@ -247,6 +325,13 @@ async function generateVariantDeclarationsAsync(themeDef) {}}+ // If every custom value targeted a non-augmentable prop, there's nothing to+ // emit beyond the header — return null so no `.variants.d.ts` is written.+ const hasEmittedAugmentation = sections.some(line =>+ line.startsWith('declare module'),+ );+ if (!hasEmittedAugmentation) return null;+return sections.join('\n');}@@ -433,13 +518,21 @@ ${iconReExport}`;/*** Generate TypeScript declarations for a built theme module.*/-function generateBuiltTypes(themeDef, iconInfo) {+function generateBuiltTypes(themeDef, iconInfo, variantsFileName) {const iconType = iconInfo? `import type { IconRegistry } from '@astryxdesign/core/Icon';export declare const ${iconInfo.exportName}: IconRegistry;`: '';- return `import type { DefinedTheme } from '@astryxdesign/core/theme';+ // Pull in the generated custom-variant augmentations so that importing the+ // theme's types also loads the module augmentations (otherwise the+ // `.variants.d.ts` is emitted but never referenced, and the custom variants+ // never widen the component prop unions for consumers).+ const variantsRef = variantsFileName+ ? `/// <reference path="./${variantsFileName}" />+`+ : '';+ return `${variantsRef}import type { DefinedTheme } from '@astryxdesign/core/theme';${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedTheme;`;}@@ -894,19 +987,23 @@ export function registerTheme(program) {const iconInfo = extractIconInfo(filePath);- // Generate all file contents in memory first.- const cssContent = generatedHeader(sourceRelative, 'css', buildCommand) + css;- const jsContent = generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo);- const dtsContent = generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo);-- // Type augmentation .d.ts if theme has custom prop values+ // Type augmentation .d.ts if theme has custom prop values. Computed+ // before the main .d.ts so the latter can reference it (see below).const augmentationSource = resolvedTheme || themeDef;const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);- const variantDtsPath = variantDecl ? path.join(outDir, `${baseName}.variants.d.ts`) : null;+ const variantsFileName = variantDecl ? `${baseName}.variants.d.ts` : null;+ const variantDtsPath = variantDecl ? path.join(outDir, variantsFileName) : null;const variantContent = variantDecl? generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl: null;+ // Generate all file contents in memory first. The main .d.ts references+ // the variants file (when present) via a triple-slash directive so+ // importing the theme also loads the custom-variant augmentations.+ const cssContent = generatedHeader(sourceRelative, 'css', buildCommand) + css;+ const jsContent = generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo);+ const dtsContent = generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo, variantsFileName);+// Atomic-ish write: stage every file as `<dest>.tmp`, then rename// each into place. If any stage step fails we clean up partials and// exit; if a rename fails mid-way we still have the originals (ordiff --git a/packages/cli/src/commands/build-theme.variants.test.mjs b/packages/cli/src/commands/build-theme.variants.test.mjsnew file mode 100644index 0000000000..54403db92f--- /dev/null+++ b/packages/cli/src/commands/build-theme.variants.test.mjs@@ -0,0 +1,204 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Regression test for the custom-variant type augmentations emitted by+ * `astryx theme build` (#3391 companion: #3371).+ *+ * When a theme declares a custom component prop value (e.g.+ * `button['variant:accentOutline']`), the build emits a `<name>.variants.d.ts`+ * with a module augmentation so the custom value type-checks. This suite pins+ * the two bugs that made that augmentation dead code:+ *+ * 1. The augmentation targeted a non-existent, `XDS`-prefixed interface+ * (`XDSButtonVariantMap`) instead of core's real `ButtonVariantMap`, so it+ * created a new unused interface and never widened the prop union.+ * 2. Props with no augmentation point (closed literal-union types such as+ * Button `size` or Heading `type`/`level`) still got a `declare module`+ * block against a `*Map` interface that doesn't exist.+ * 3. The generated `.variants.d.ts` was never referenced by the main+ * `<name>.d.ts`, so even a correct augmentation never loaded.+ *+ * Building `astryx theme build` requires a compiled @astryxdesign/core, so this+ * suite builds core once in beforeAll (mirrors build-theme.prose.test.mjs).+ */++import {describe, it, expect, beforeAll, beforeEach, afterEach} from 'vitest';+import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {fileURLToPath} from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CLI_BIN = path.resolve(__dirname, '../../bin/astryx.mjs');+const REPO_ROOT = path.resolve(__dirname, '../../../..');+const CORE_THEME_ENTRY = path.join(+ REPO_ROOT,+ 'packages/core/dist/theme/index.js',+);+// The fix reads core's shipped component declarations to decide whether an+// interface is augmentable; those .d.ts files come from the same core build.+const CORE_BUTTON_DTS = path.join(+ REPO_ROOT,+ 'packages/core/dist/Button/index.d.ts',+);++function runCli(args, cwd) {+ try {+ const out = execFileSync('node', [CLI_BIN, ...args], {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {...process.env, FORCE_COLOR: '0'},+ });+ return {code: 0, stdout: out, stderr: ''};+ } catch (e) {+ return {+ code: e.status ?? 1,+ stdout: e.stdout?.toString() ?? '',+ stderr: e.stderr?.toString() ?? '',+ };+ }+}++function writeTheme(dir, contents) {+ fs.mkdirSync(dir, {recursive: true});+ const file = path.join(dir, 'variants-theme.mjs');+ fs.writeFileSync(file, contents);+ return file;+}++beforeAll(() => {+ if (!fs.existsSync(CORE_THEME_ENTRY) || !fs.existsSync(CORE_BUTTON_DTS)) {+ execFileSync('pnpm', ['-F', '@astryxdesign/core', 'build'], {+ cwd: REPO_ROOT,+ stdio: 'pipe',+ timeout: 180_000,+ });+ }+}, 200_000);++let tmpDir;+beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-build-theme-variants-'));+});+afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('theme build custom-variant augmentations', () => {+ it('targets the real (un-prefixed) core interface for a custom variant', () => {+ const themeFile = writeTheme(+ tmpDir,+ `export default {+ name: 'variants-theme',+ tokens: { '--color-bg': '#fff' },+ components: {+ button: { 'variant:accentOutline': { backgroundColor: 'transparent' } },+ },+ };\n`,+ );++ const result = runCli(+ ['theme', 'build', path.relative(tmpDir, themeFile)],+ tmpDir,+ );+ expect(result.code).toBe(0);++ const variantsPath = path.join(tmpDir, 'variants-theme.variants.d.ts');+ expect(fs.existsSync(variantsPath)).toBe(true);+ const dts = fs.readFileSync(variantsPath, 'utf-8');++ // Targets core's actual augmentation point…+ expect(dts).toContain("declare module '@astryxdesign/core/Button'");+ expect(dts).toMatch(/interface ButtonVariantMap\b/);+ expect(dts).toContain("'accentOutline': true;");+ // …and NOT the old, non-existent XDS-prefixed interface.+ expect(dts).not.toMatch(/XDSButtonVariantMap/);+ });++ it('skips props with no augmentation point (Button size, Heading type)', () => {+ const themeFile = writeTheme(+ tmpDir,+ `export default {+ name: 'variants-theme',+ tokens: { '--color-bg': '#fff' },+ components: {+ button: {+ 'variant:accentOutline': { backgroundColor: 'transparent' },+ 'size:jumbo': { paddingBlock: '40px' },+ },+ heading: { 'type:hero': { fontSize: '80px' } },+ },+ };\n`,+ );++ const result = runCli(+ ['theme', 'build', path.relative(tmpDir, themeFile)],+ tmpDir,+ );+ expect(result.code).toBe(0);++ const variantsPath = path.join(tmpDir, 'variants-theme.variants.d.ts');+ expect(fs.existsSync(variantsPath)).toBe(true);+ const dts = fs.readFileSync(variantsPath, 'utf-8');++ // The augmentable variant is emitted…+ expect(dts).toMatch(/interface ButtonVariantMap\b/);+ // …but closed literal-union props get no dead augmentation.+ expect(dts).not.toMatch(/ButtonSizeMap/);+ expect(dts).not.toMatch(/HeadingTypeMap/);+ expect(dts).not.toContain("declare module '@astryxdesign/core/Heading'");+ });++ it('does not emit a .variants.d.ts when every custom value is non-augmentable', () => {+ const themeFile = writeTheme(+ tmpDir,+ `export default {+ name: 'variants-theme',+ tokens: { '--color-bg': '#fff' },+ components: {+ button: { 'size:jumbo': { paddingBlock: '40px' } },+ },+ };\n`,+ );++ const result = runCli(+ ['theme', 'build', path.relative(tmpDir, themeFile)],+ tmpDir,+ );+ expect(result.code).toBe(0);+ expect(+ fs.existsSync(path.join(tmpDir, 'variants-theme.variants.d.ts')),+ ).toBe(false);+ });++ it('references the variants file from the main .d.ts so the augmentation loads', () => {+ const themeFile = writeTheme(+ tmpDir,+ `export default {+ name: 'variants-theme',+ tokens: { '--color-bg': '#fff' },+ components: {+ button: { 'variant:accentOutline': { backgroundColor: 'transparent' } },+ },+ };\n`,+ );++ const result = runCli(+ ['theme', 'build', path.relative(tmpDir, themeFile)],+ tmpDir,+ );+ expect(result.code).toBe(0);++ const dts = fs.readFileSync(+ path.join(tmpDir, 'variants-theme.d.ts'),+ 'utf-8',+ );+ // A triple-slash reference to the variants file, so importing the theme's+ // types also loads the module augmentation.+ expect(dts).toMatch(+ /\/\/\/\s*<reference path="\.\/variants-theme\.variants\.d\.ts"\s*\/>/,+ );+ });+});