Skip to content

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

TypeScript

[CLI] Show where Theme comes from wherever the CLI shows the wrapper (#7182)

Joeyca2b7e30cb62
diff --git a/.changeset/theme-import-line.md b/.changeset/theme-import-line.md
new file mode 100644
index 0000000000..c74dce8999
--- /dev/null
+++ b/.changeset/theme-import-line.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Wherever the CLI shows the `<Theme>` wrapper, it now also shows where `Theme` comes from: `import {Theme} from '@astryxdesign/core'`. This covers the `astryx init` next steps, `theme add` and `theme build` output, the doctor fix for an unimported theme module, `build` help, and the theme guides.
+
+@josephfarina
diff --git a/packages/cli/api/build/help/help.mjs b/packages/cli/api/build/help/help.mjs
index 70a3ae5228..6a6d07ace6 100644
--- a/packages/cli/api/build/help/help.mjs
+++ b/packages/cli/api/build/help/help.mjs
@@ -63,7 +63,7 @@ export function buildHelp() {
"Keep the template's page frame, gap, and padding values. Replace its data, copy, and sections.",
'No <div>/raw HTML for layout — use VStack/HStack/Grid/Stack/Card etc.',
'No style={{}} — use component props, and design tokens for values.',
- 'Wrap the app in <Theme theme={...}> and import core reset.css + astryx.css.',
+ "Wrap the app in <Theme theme={...}> (import {Theme} from '@astryxdesign/core') and import core reset.css + astryx.css.",
],
related: [
{
diff --git a/packages/cli/api/doctor/theme-checks.mjs b/packages/cli/api/doctor/theme-checks.mjs
index da307d37df..72220d3feb 100644
--- a/packages/cli/api/doctor/theme-checks.mjs
+++ b/packages/cli/api/doctor/theme-checks.mjs
@@ -736,7 +736,7 @@ export async function checkAppThemes(cwd) {
label: 'App imports the theme module',
status: 'warn',
message: `Could not prove that project source imports ${state.module.path}${importEvidence.parseFailures ? `; ${importEvidence.parseFailures} source file(s) could not be parsed` : ''}.`,
- fix: `Import {themes, defaultThemeSlug} from the generated module and render <Theme theme={themes[defaultThemeSlug]}>.`,
+ fix: `Import {themes, defaultThemeSlug} from the generated module and {Theme} from '@astryxdesign/core', then render <Theme theme={themes[defaultThemeSlug]}>.`,
});
}
diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjs
index d79c8f1f74..e9f30b56cd 100644
--- a/packages/cli/api/init/run/run.mjs
+++ b/packages/cli/api/init/run/run.mjs
@@ -54,6 +54,7 @@ export function getNextSteps(invocation) {
' 4. Add and wire a theme:',
' npm install @astryxdesign/theme-neutral',
` ${invocation} theme add neutral --import`,
+ " import { Theme } from '@astryxdesign/core'",
" import { themes, defaultThemeSlug } from './astryx-themes'",
' <Theme theme={themes[defaultThemeSlug]}>...</Theme>',
` Extend an imported theme to customize it. Run \`${invocation} theme eject <slug>\` only to fork source.`,
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 456a23f8d5..ff9060047d 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -2956,6 +2956,7 @@ async function themeBuildInternal(
logger.log(`
Install in your app (paths are relative to a file in src/; adjust if yours lives elsewhere):
+ import { Theme } from '@astryxdesign/core';
import { ${exportName} } from '${jsImport}';
import '${cssImport}';
@@ -2965,6 +2966,7 @@ Install in your app (paths are relative to a file in src/; adjust if yours lives
Or with a <link> tag:
+ import { Theme } from '@astryxdesign/core';
import { ${exportName} } from '${jsImport}';
<link rel="stylesheet" href="${cssImport}" />
diff --git a/packages/cli/assets/docs/author-a-theme.doc.mjs b/packages/cli/assets/docs/author-a-theme.doc.mjs
index be83fdf484..c4123a86b8 100644
--- a/packages/cli/assets/docs/author-a-theme.doc.mjs
+++ b/packages/cli/assets/docs/author-a-theme.doc.mjs
@@ -118,7 +118,7 @@ export const docs = {
['ocean.d.ts', 'TypeScript declarations for the theme and icon registry exports'],
['ocean.variants.d.ts', "(Optional) Module augmentations for custom component prop values"],
]},
- {type: 'code', lang: 'tsx', label: 'Using a custom built theme', code: "import {oceanTheme} from './themes/ocean';\nimport './themes/ocean.css';\n\n<Theme theme={oceanTheme}>\n <App />\n</Theme>"},
+ {type: 'code', lang: 'tsx', label: 'Using a custom built theme', code: "import {Theme} from '@astryxdesign/core';\nimport {oceanTheme} from './themes/ocean';\nimport './themes/ocean.css';\n\n<Theme theme={oceanTheme}>\n <App />\n</Theme>"},
{type: 'prose', text: "After upgrading Astryx, rerun `astryx theme build` for every custom prebuilt theme. Deploy the regenerated files together. The build also warns when the theme names font families it does not load. See {@link generic:typography} for the full recipe."},
{type: 'prose', text: 'For the runtime vs built tradeoff, see the Runtime vs Built section of {@link generic:use-a-theme}.'},
],
diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjs
index 424b60332e..9610078d84 100644
--- a/packages/cli/assets/docs/theme.doc.dense.mjs
+++ b/packages/cli/assets/docs/theme.doc.dense.mjs
@@ -9,7 +9,7 @@ export const docsDense = {
section: 'Wrap your app in a theme',
title: 'Quick start',
content: [
- {type: 'prose', text: 'Install a theme, wrap in `<Theme>`. {@link generic:use-a-theme} for full guide.'},
+ {type: 'prose', text: "Install a theme, wrap in `<Theme>` (`import {Theme} from '@astryxdesign/core'`). {@link generic:use-a-theme} for full guide."},
],
},
{
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index 506cf70552..72ad3d5e16 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -361,7 +361,8 @@ function printThemeApp(result) {
emit(
text('Wire the generated module once in the app root:'),
code(
- `import {themes, defaultThemeSlug} from './${stem}';\n\n` +
+ "import {Theme} from '@astryxdesign/core';\n" +
+ `import {themes, defaultThemeSlug} from './${stem}';\n\n` +
'<Theme theme={themes[defaultThemeSlug]}>\n <App />\n</Theme>',
),
);
@@ -823,7 +824,8 @@ export function registerTheme(program) {
'Use it in your app (import path is relative to a file in src/ — adjust if yours lives elsewhere):',
),
code(
- `import { ${exportName} } from '${entryModule}';\n\n` +
+ "import { Theme } from '@astryxdesign/core';\n" +
+ `import { ${exportName} } from '${entryModule}';\n\n` +
`<Theme theme={${exportName}}>\n <App />\n</Theme>`,
),
text(
diff --git a/packages/cli/test/taught-core-imports.test.mjs b/packages/cli/test/taught-core-imports.test.mjs
new file mode 100644
index 0000000000..f4e3a43f64
--- /dev/null
+++ b/packages/cli/test/taught-core-imports.test.mjs
@@ -0,0 +1,133 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Every `@astryxdesign/core` import the CLI teaches must work in an app.
+ *
+ * The CLI prints code in its docs and in command output (`init` next steps,
+ * `theme add`, `theme build`, doctor fixes, `build` help). A specifier that
+ * names a subpath Core does not export, or names it with the wrong case, fails
+ * in the user's app, so every specifier must match an entry in Core's
+ * package.json `exports`. Wherever command output shows the `<Theme>` wrapper,
+ * it also shows where `Theme` comes from.
+ *
+ * @position packages/cli/test — taught imports
+ */
+
+import {describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+const CLI = path.resolve(import.meta.dirname, '..');
+const CORE_PACKAGE = path.resolve(CLI, '..', 'core', 'package.json');
+
+/** Command modules whose printed text shows app code. */
+const OUTPUT_MODULES = [
+ 'api/init/run/run.mjs',
+ 'clients/cli/commands/build-theme.mjs',
+ 'api/theme/build/build.mjs',
+ 'api/doctor/theme-checks.mjs',
+ 'api/build/help/help.mjs',
+];
+
+/** @param {string} dir @returns {string[]} */
+function docFiles(dir) {
+ /** @type {string[]} */
+ const files = [];
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const file = path.join(dir, entry.name);
+ if (entry.isDirectory()) files.push(...docFiles(file));
+ else if (entry.name.endsWith('.mjs') && !entry.name.endsWith('.test.mjs')) {
+ files.push(file);
+ }
+ }
+ return files;
+}
+
+/**
+ * Whether `subpath` (e.g. `./theme`) is exported by Core, matching export
+ * keys exactly and `*` patterns the way Node does: case-sensitive, with `*`
+ * standing for any string.
+ * @param {string[]} keys
+ * @param {string} subpath
+ */
+function isExported(keys, subpath) {
+ return keys.some(key => {
+ if (!key.includes('*')) return key === subpath;
+ const [before, after] = key.split('*');
+ return (
+ subpath.length > before.length + after.length &&
+ subpath.startsWith(before) &&
+ subpath.endsWith(after)
+ );
+ });
+}
+
+/** @param {string} source */
+function coreSpecifiers(source) {
+ return [
+ ...source.matchAll(
+ /(?:from\s+|import\s+|import\(\s*)['"](@astryxdesign\/core(?:\/[^'"\s]*)?)['"]/g,
+ ),
+ ].map(match => match[1]);
+}
+
+describe('taught @astryxdesign/core imports', () => {
+ const exportKeys = Object.keys(
+ JSON.parse(fs.readFileSync(CORE_PACKAGE, 'utf8')).exports,
+ );
+ const files = [
+ ...docFiles(path.join(CLI, 'assets', 'docs')),
+ ...OUTPUT_MODULES.map(file => path.join(CLI, file)),
+ ];
+
+ it('resolve against the exports in Core package.json, case included', () => {
+ /** @type {string[]} */
+ const unresolved = [];
+ let count = 0;
+ for (const file of files) {
+ for (const specifier of coreSpecifiers(fs.readFileSync(file, 'utf8'))) {
+ count++;
+ const subpath =
+ specifier === '@astryxdesign/core'
+ ? '.'
+ : `./${specifier.slice('@astryxdesign/core/'.length)}`;
+ if (!isExported(exportKeys, subpath)) {
+ unresolved.push(`${path.relative(CLI, file)}: ${specifier}`);
+ }
+ }
+ }
+ expect(count).toBeGreaterThan(0);
+ expect(unresolved).toEqual([]);
+ });
+
+ it('rejects a subpath Core does not export, or the wrong case', () => {
+ expect(isExported(exportKeys, './theme')).toBe(true);
+ expect(isExported(exportKeys, './Theme')).toBe(false);
+ expect(isExported(exportKeys, './locales/fr-FR.generated.js')).toBe(true);
+ });
+
+ it.each(OUTPUT_MODULES)(
+ '%s shows where Theme comes from wherever it shows the <Theme> wrapper',
+ file => {
+ const source = fs.readFileSync(path.join(CLI, file), 'utf8');
+ const wrappers = [...source.matchAll(/<Theme theme=/g)].map(
+ match => match.index ?? 0,
+ );
+ expect(wrappers.length).toBeGreaterThan(0);
+ wrappers.forEach((index, n) => {
+ // Look back from this wrapper, but not past the previous one, so one
+ // example's import cannot stand in for another's. A sentence can name
+ // the import after the wrapper on the same line.
+ const previous = n > 0 ? wrappers[n - 1] + 1 : 0;
+ const lineEnd = source.indexOf('\n', index);
+ const nearby = source.slice(
+ Math.max(previous, index - 400),
+ lineEnd === -1 ? source.length : lineEnd,
+ );
+ expect(nearby, `${file} at offset ${index}`).toMatch(
+ /\{\s*Theme\s*\}\s+from\s+'@astryxdesign\/core'/,
+ );
+ });
+ },
+ );
+});