Skip to content

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

TypeScript

fix(cli): doctor counts themes an app wires itself (#10353)

Joey0d62e692fad4
diff --git a/.changeset/cli-doctor-themes-wired-by-import.md b/.changeset/cli-doctor-themes-wired-by-import.md
new file mode 100644
index 0000000000..ada3ef4860
--- /dev/null
+++ b/.changeset/cli-doctor-themes-wired-by-import.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx doctor` no longer warns that no theme is wired in an app that imports its themes itself. Without a generated theme module or a package.json `astryx.theme`, the `themes` check now passes when the source of the app imports a theme's built module or stylesheet (the imports `theme add` writes) or passes a theme to `Theme`, followed through module-scope variables, `defineTheme({extends})`, re-exports and installed packages to its package, and names the file. Only a theme whose package is installed, or a local theme, counts. A theme passed to `Theme` that doctor cannot trace (a prop, a function result, a variable declared inside a component) is reported as not confirmed (info), not as missing.
+@josephfarina
diff --git a/packages/cli/api/doctor/_adapter.mjs b/packages/cli/api/doctor/_adapter.mjs
index a676a4a1b9..011398a7da 100644
--- a/packages/cli/api/doctor/_adapter.mjs
+++ b/packages/cli/api/doctor/_adapter.mjs
@@ -39,6 +39,8 @@ import {
} from '../../foundation/agent-docs/computer-agent-text.mjs';
import {computerAgentTextSettings} from '../../foundation/env/user-settings.mjs';
import * as fs from 'node:fs';
+import {elementPropOrigins} from '../../foundation/discovery/module-exports.mjs';
+import {cssImports} from '../../foundation/render/embedded-imports.mjs';
import * as path from 'node:path';
import {
Project,
@@ -113,8 +115,9 @@ export function readTextFileIfExists(file) {
* links. The doctor parses the returned bytes without executing app code.
* @param {string} root
* @param {string} generatedModule
+ * @param {{stylesheets?: boolean}} [options] - also list `.css` files
*/
-export function listProjectSourceFiles(root, generatedModule) {
+export function listProjectSourceFiles(root, generatedModule, options = {}) {
/** @type {string[]} */
const files = [];
/** @type {string[]} */
@@ -137,7 +140,8 @@ export function listProjectSourceFiles(root, generatedModule) {
} else if (
entry.isFile() &&
file !== generatedModule &&
- SOURCE_EXTENSIONS.has(path.extname(entry.name))
+ (SOURCE_EXTENSIONS.has(path.extname(entry.name)) ||
+ (options.stylesheets === true && path.extname(entry.name) === '.css'))
) {
files.push(file);
}
@@ -166,6 +170,39 @@ export function discoverDoctorUnmigratedCopies(projectDir) {
return discoverUnmigratedThemeCopies(projectDir);
}
+/**
+ * The real path of a file, links resolved; null when it does not exist.
+ * @param {string} file
+ * @returns {string | null}
+ */
+export function realDoctorFile(file) {
+ try {
+ return fs.realpathSync(file);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Where each `<Name prop={value}>` value of a module is declared (see
+ * `elementPropOrigins`).
+ * @param {string} file
+ * @param {Parameters<typeof elementPropOrigins>[1]} element
+ */
+export function doctorElementPropOrigins(file, element) {
+ return elementPropOrigins(file, element);
+}
+
+/**
+ * The `@import` specifiers of a stylesheet, quoted or in `url()`, in any case
+ * (see `cssImports`); empty for CSS that does not parse.
+ * @param {string} css
+ * @returns {Set<string>}
+ */
+export function doctorStylesheetImports(css) {
+ return new Set(cssImports(css));
+}
+
/** @param {string} projectDir */
export function findDoctorCoreDir(projectDir) {
return findProjectCoreDir(projectDir);
diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjs
index d155db8851..8b68c935a4 100644
--- a/packages/cli/api/doctor/doctor.doc.mjs
+++ b/packages/cli/api/doctor/doctor.doc.mjs
@@ -24,7 +24,7 @@ export const doc = {
'integration provider identity and contribution issues, agent docs, the ' +
'detected package manager, and the health of the docs the CLI reads (authoring ' +
'and CLI docs, the docs tree, doc size), and returns a structured ' +
- 'report. Theme checks run when the generated app module exists; without one, doctor reports that the CLI manages no themes and names theme add. Earlier descriptor-less copies are a non-failing upgrade warning. It never installs, writes, or mutates. It imports astryx.config, executes every added theme source while validating private inputs, and loads every recorded built theme module to prove its runtime imports work, including themes from installed packages. Local theme source also runs during build-freshness checks. Stylesheets are parsed without execution. Config and theme top-level code therefore run, so use doctor only with project code you trust. Outside a project it checks the computer instead: the Node version (`node-version`), the release that answered (`answering-release`), the newest release the computer knows of (`newest-release`), the astryx commands on the search path (`cli-on-path`), the integrations installed for the computer (`computer-integrations`: each one used outside a project, and a warning for one skipped because its peer range excludes the answering release or that fails to load), and the computer-level agent text (`computer-agent-text`): present and matching this release, present but different, edited, absent, or turned off, and where it is linked, with `{@command init --user}` as the fix for the stale and absent cases. The agent-text check is always info. The newest-release check also runs inside a project: it names a newer release when the computer knows of one; inside a project whose release is older it names the install and upgrade commands; outside one, when the CLI installed for the computer is older, it names the command of the package manager that installed it, after the Node the newest release needs when the computer runs an older one. It is always info and installs nothing. The `cli-on-path` check also runs inside a project: it lists every astryx command on the search path in order, passes when the first is a release that hands each project run to the release of that project, and warns when the first is another program or a release that predates the hand-off, naming `{@pm install @astryxdesign/cli@latest --global}`. Inside a project, `computer-integrations` lists, as info, the integrations installed for the computer that the project does not install, with its install command; they are not used there. It never fails a check because the folder has no project, and installs nothing.' +
+ 'report. Theme checks run when the generated app module exists; without one, doctor reports that the CLI manages no themes and names theme add, and the `themes` check counts a theme as wired when package.json `astryx.theme` names one or when the source of the app (JavaScript, TypeScript and CSS files, outside dependencies and build output; type-only imports do not count) imports the built module or stylesheet of a discovered theme, the same imports theme add writes, or passes one to Theme (followed through module-scope variables, defineTheme extends, re-exports and installed packages; only a theme whose package is installed, or a local theme, counts), naming the file; a theme passed to Theme that cannot be traced, such as a prop or a variable declared inside a component, is reported as unconfirmed (info), not as missing. Earlier descriptor-less copies are a non-failing upgrade warning. It never installs, writes, or mutates. It imports astryx.config, executes every added theme source while validating private inputs, and loads every recorded built theme module to prove its runtime imports work, including themes from installed packages. Local theme source also runs during build-freshness checks. Stylesheets are parsed without execution. Config and theme top-level code therefore run, so use doctor only with project code you trust. Outside a project it checks the computer instead: the Node version (`node-version`), the release that answered (`answering-release`), the newest release the computer knows of (`newest-release`), the astryx commands on the search path (`cli-on-path`), the integrations installed for the computer (`computer-integrations`: each one used outside a project, and a warning for one skipped because its peer range excludes the answering release or that fails to load), and the computer-level agent text (`computer-agent-text`): present and matching this release, present but different, edited, absent, or turned off, and where it is linked, with `{@command init --user}` as the fix for the stale and absent cases. The agent-text check is always info. The newest-release check also runs inside a project: it names a newer release when the computer knows of one; inside a project whose release is older it names the install and upgrade commands; outside one, when the CLI installed for the computer is older, it names the command of the package manager that installed it, after the Node the newest release needs when the computer runs an older one. It is always info and installs nothing. The `cli-on-path` check also runs inside a project: it lists every astryx command on the search path in order, passes when the first is a release that hands each project run to the release of that project, and warns when the first is another program or a release that predates the hand-off, naming `{@pm install @astryxdesign/cli@latest --global}`. Inside a project, `computer-integrations` lists, as info, the integrations installed for the computer that the project does not install, with its install command; they are not used there. It never fails a check because the folder has no project, and installs nothing.' +
' In global mode: with `cwd` outside a project, it checks the computer instead (the Node version, the version that answered, the newest version it knows of, the astryx commands on the search path, the integrations installed globally, and the agent guide for the computer) and never fails a check because the folder has no project. See {@link namespace:global} and {@link generic:who-answers}.',
importPath: '@astryxdesign/cli/api',
signature: 'doctor(options?: DoctorOptions): Promise<DoctorResponse>',
diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs
index 513e1d6b3e..e121a6a55b 100644
--- a/packages/cli/api/doctor/doctor.mjs
+++ b/packages/cli/api/doctor/doctor.mjs
@@ -65,7 +65,11 @@ import {typedEdges} from '../docs/node/node.mjs';
import {detailView, indexView} from '../../foundation/doc-compiler/lenses.mjs';
import {isExperimentalTreeNode} from '../../foundation/doc-compiler/tree.mjs';
import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';
-import {checkAppThemes, checkThemes} from './theme-checks.mjs';
+import {
+ checkAppThemes,
+ checkThemes,
+ themeImportWiring,
+} from './theme-checks.mjs';
import {availableLine, RUN_FROM_PROJECT, upgradeLine} from '../../foundation/release/notices.mjs';
import {COMPUTER_COMMAND, COMPUTER_INSTALL_STEP} from '../../foundation/agent-docs/computer-agent-text.mjs';
import {alignCommand, addCliCommandFor, computerAgentTextState, installCommandFor, insideProjectElsewhere, projectCoreVersion, projectHasOwnCli, computerIntegrationsOutside, computerIntegrationsToAdd, displayHomePath, outsideProject, releaseFacts, builtIntegrationPackages} from './_adapter.mjs';
@@ -2190,7 +2194,10 @@ export async function runChecks(options = {}) {
if (check) checks.push(check);
if (fn === checkVersionAlignment) {
const appThemeChecks = await checkAppThemes(cwd);
- checks.push(checkThemes(cwd, appThemeChecks), ...appThemeChecks);
+ checks.push(
+ checkThemes(cwd, appThemeChecks, await themeImportWiring(cwd)),
+ ...appThemeChecks,
+ );
checks.push(await checkConfig(ctx));
}
}
diff --git a/packages/cli/api/doctor/theme-checks.mjs b/packages/cli/api/doctor/theme-checks.mjs
index bd8427eb96..570eebae43 100644
--- a/packages/cli/api/doctor/theme-checks.mjs
+++ b/packages/cli/api/doctor/theme-checks.mjs
@@ -15,7 +15,10 @@ import {
discoverDoctorThemes,
discoverDoctorUnmigratedCopies,
findDoctorCoreDir,
+ doctorElementPropOrigins,
+ doctorStylesheetImports,
findDoctorInstalledPackage,
+ realDoctorFile,
isLocalThemeOwner,
listDoctorThemePackages,
listProjectSourceFiles,
@@ -135,8 +138,12 @@ function walkAst(value, visit) {
}
}
-/** @param {string} source */
-function moduleSpecifiers(source) {
+/**
+ * @param {string} source
+ * @param {{runtimeOnly?: boolean}} [options] - skip type-only imports and
+ * re-exports, which the build erases
+ */
+function moduleSpecifiers(source, options = {}) {
const values = new Set();
walkAst(parseModule(source), node => {
if (
@@ -145,7 +152,11 @@ function moduleSpecifiers(source) {
'ExportNamedDeclaration',
'ExportAllDeclaration',
].includes(node.type) &&
- typeof node.source?.value === 'string'
+ typeof node.source?.value === 'string' &&
+ !(
+ options.runtimeOnly &&
+ (node.importKind === 'type' || node.exportKind === 'type')
+ )
) {
values.add(node.source.value);
}
@@ -406,18 +417,248 @@ function appPackageNamesTheme(cwd) {
return Boolean(pkg?.astryx?.theme);
}
+/**
+ * Whether one import specifier names a theme's built module or stylesheet.
+ * @param {string} specifier
+ * @param {string} file - the importing file
+ * @param {ResolvedAppTheme} theme
+ */
+function importsTheme(specifier, file, theme) {
+ if (theme.source === 'local') {
+ return (
+ specifierTargets(specifier, file, theme.moduleFile) ||
+ specifierTargets(specifier, file, theme.stylesheetFile)
+ );
+ }
+ return specifier === theme.module || specifier === theme.stylesheet;
+}
+
+const CORE_THEME_SOURCES = new Set([
+ '@astryxdesign/core',
+ '@astryxdesign/core/theme',
+]);
+
+/**
+ * The base a `defineTheme({extends: base})` call extends, for
+ * {@link doctorElementPropOrigins}: a theme made that way stands for its base.
+ * @param {any} init
+ * @returns {any}
+ */
+function definedThemeBase(init) {
+ if (
+ init?.type !== 'CallExpression' ||
+ init.callee?.type !== 'Identifier' ||
+ init.callee.name !== 'defineTheme'
+ ) {
+ return null;
+ }
+ const options = init.arguments?.[0];
+ if (options?.type !== 'ObjectExpression') return null;
+ const base = options.properties.find(
+ (/** @type {any} */ property) =>
+ property.type === 'ObjectProperty' &&
+ !property.computed &&
+ (property.key?.name ?? property.key?.value) === 'extends',
+ );
+ return base?.value ?? null;
+}
+
+/**
+ * The themes the app wires itself, without a generated theme module or a
+ * package.json `astryx.theme`. A theme is wired when the app's own source
+ * imports its built module or stylesheet ({@link resolveDoctorThemeImports}
+ * names them: the imports `theme add` writes), or when the app passes it to
+ * Core's `Theme`: {@link doctorElementPropOrigins} follows the `theme` value through
+ * module-scope aliases, `defineTheme({extends})`, re-exports and installed
+ * packages to where it is declared, which must be inside an installed theme
+ * package or be a local theme's built module. Only themes the app can load
+ * count: a theme whose package is not installed is never wired. A `theme`
+ * value whose origin is anything else (a prop, a function result, a lookup)
+ * is reported as unconfirmed, never as missing. The scan reads app source only
+ * (no dependencies, build output, links or type-only imports) within the
+ * bounded source walk, and executes nothing.
+ * @param {string} cwd
+ * @returns {Promise<{
+ * wired: Array<{slug: string, owner: string, file: string}>,
+ * unconfirmed: Array<{file: string}>,
+ * }>}
+ */
+export async function themeImportWiring(cwd) {
+ const none = {wired: [], unconfirmed: []};
+ let state;
+ try {
+ state = readThemeState(cwd);
+ } catch {
+ return none;
+ }
+ // A generated module or `astryx.theme` already decides the result.
+ if (state.configured || appPackageNamesTheme(cwd)) return none;
+ const projectDir = state.projectDir;
+ /** @type {DiscoveredTheme[]} */
+ let available;
+ try {
+ available = await discoverDoctorThemes(projectDir);
+ } catch {
+ return none;
+ }
+ const ownerCounts = new Map();
+ for (const theme of available) {
+ const owner = themeRecordOwner(theme);
+ ownerCounts.set(owner, (ownerCounts.get(owner) ?? 0) + 1);
+ }
+ /** @type {Map<string, string | null>} */
+ const installedDirs = new Map();
+ const installedDir = (/** @type {string} */ owner) => {
+ if (!installedDirs.has(owner)) {
+ const dir = findDoctorInstalledPackage(projectDir, owner);
+ installedDirs.set(owner, dir ? realDoctorFile(dir) : null);
+ }
+ return installedDirs.get(owner) ?? null;
+ };
+ // Only themes the app can load: local themes, and package themes whose
+ // package is installed (discovery also lists the CLI's bundled themes).
+ /** @type {ResolvedAppTheme[]} */
+ const themes = [];
+ for (const theme of available) {
+ let resolved;
+ try {
+ resolved = resolveDoctorThemeImports(theme, {
+ cwd: projectDir,
+ ownerThemeCount: ownerCounts.get(themeRecordOwner(theme)) ?? 1,
+ });
+ } catch {
+ // A theme without built imports cannot be wired by importing them.
+ continue;
+ }
+ if (resolved.source === 'local' || installedDir(resolved.owner)) {
+ themes.push(resolved);
+ }
+ }
+ if (themes.length === 0) return none;
+ /**
+ * The theme a `Theme` value's origin is, or null.
+ * @param {{file: string, name: string} | null} origin
+ */
+ const themeAt = origin => {
+ const file = origin ? realDoctorFile(origin.file) : null;
+ if (!origin || !file) return null;
+ const local = themes.find(
+ theme =>
+ theme.source === 'local' && realDoctorFile(theme.moduleFile) === file,
+ );
+ if (local) return local;
+ const owned = themes.filter(theme => {
+ const dir = theme.source === 'local' ? null : installedDir(theme.owner);
+ return dir != null && file.startsWith(`${dir}${path.sep}`);
+ });
+ const named = owned.filter(theme => theme.exportName === origin.name);
+ if (named.length === 1) return named[0];
+ return owned.length === 1 ? owned[0] : null;
+ };
+ /** @type {Map<string, {slug: string, owner: string, file: string}>} */
+ const wired = new Map();
+ const keyOf = (/** @type {ResolvedAppTheme} */ theme) =>
+ `${theme.owner}\u0000${theme.slug}`;
+ /** @type {Set<string>} */
+ const unconfirmed = new Set();
+ for (const file of listProjectSourceFiles(projectDir, '', {
+ stylesheets: true,
+ })) {
+ let source;
+ try {
+ source = readTextFile(file);
+ } catch {
+ continue;
+ }
+ const shown = relative(projectDir, file);
+ const candidates = themes.filter(
+ theme =>
+ !wired.has(keyOf(theme)) &&
+ (theme.source === 'local'
+ ? source.includes(path.basename(theme.moduleFile)) ||
+ source.includes(path.basename(theme.stylesheetFile))
+ : source.includes(theme.module) || source.includes(theme.stylesheet)),
+ );
+ if (candidates.length > 0) {
+ let specifiers;
+ try {
+ specifiers =
+ path.extname(file) === '.css'
+ ? doctorStylesheetImports(source)
+ : moduleSpecifiers(source, {runtimeOnly: true});
+ } catch {
+ specifiers = new Set();
+ }
+ for (const theme of candidates) {
+ if ([...specifiers].some(spec => importsTheme(spec, file, theme))) {
+ wired.set(keyOf(theme), {
+ slug: theme.slug,
+ owner: theme.owner,
+ file: shown,
+ });
+ }
+ }
+ }
+ if (path.extname(file) === '.css' || !source.includes('theme=')) continue;
+ for (const origin of doctorElementPropOrigins(file, {
+ sources: CORE_THEME_SOURCES,
+ name: 'Theme',
+ prop: 'theme',
+ unwrap: definedThemeBase,
+ })) {
+ const theme = themeAt(origin);
+ if (!theme) {
+ unconfirmed.add(shown);
+ } else if (!wired.has(keyOf(theme))) {
+ wired.set(keyOf(theme), {
+ slug: theme.slug,
+ owner: theme.owner,
+ file: shown,
+ });
+ }
+ }
+ }
+ // In discovery order, so the report does not depend on the file walk.
+ return {
+ wired: themes.flatMap(theme => {
+ const found = wired.get(keyOf(theme));
+ return found ? [found] : [];
+ }),
+ unconfirmed: [...unconfirmed].sort().map(file => ({file})),
+ };
+}
+
+/**
+ * The pass message's list of themes wired by import, each with the file that
+ * imports it.
+ * @param {Array<{slug: string, file: string}>} wired
+ */
+function wiredByImportList(wired) {
+ const shown = wired.slice(0, 5).map(({slug, file}) => `${slug} (${file})`);
+ const more = wired.length - shown.length;
+ return more > 0 ? `${shown.join(', ')} and ${more} more` : shown.join(', ');
+}
+
/**
* The `themes` check that every released doctor report carries. Its id is
* stable, so it stays beside the app-theme checks. Without a generated theme
* module it reports what it always has: whether an `@astryxdesign/theme-*`
* package is installed, and whether the app's package.json names a theme in
- * `astryx.theme`. With a generated module it reports the overall result of the
- * app-theme checks.
+ * `astryx.theme`, or else whether the app's own source imports a theme's built
+ * module or stylesheet ({@link themeImportWiring}). With a generated module it
+ * reports the overall result of the app-theme checks.
* @param {string} cwd
* @param {DoctorCheck[]} appChecks - the checks {@link checkAppThemes} returned
+ * @param {{wired: Array<{slug: string, file: string}>, unconfirmed: Array<{file: string}>}} [wiring] -
+ * what {@link themeImportWiring} returned
* @returns {DoctorCheck}
*/
-export function checkThemes(cwd, appChecks) {
+export function checkThemes(
+ cwd,
+ appChecks,
+ wiring = {wired: [], unconfirmed: []},
+) {
+ const wiredByImport = wiring.wired;
const label = 'Theme packages';
const managed = appChecks.some(
check => APP_THEME_CHECK_IDS.has(check.id) && check.status !== 'info',
@@ -475,6 +716,14 @@ export function checkThemes(cwd, appChecks) {
const run = getCliInvocation(cwd);
const packages = listDoctorThemePackages(cwd);
+ if (packages.length === 0 && wiredByImport.length > 0) {
+ return {
+ id: 'themes',
+ label,
+ status: 'pass',
+ message: `Themes wired by import: ${wiredByImportList(wiredByImport)}.`,
+ };
+ }
if (packages.length === 0) {
return {
id: 'themes',
@@ -485,6 +734,24 @@ export function checkThemes(cwd, appChecks) {
};
}
const names = packages.join(', ');
+ if (!appPackageNamesTheme(cwd) && wiredByImport.length > 0) {
+ return {
+ id: 'themes',
+ label,
+ status: 'pass',
+ message: `Theme package(s) installed (${names}); wired by import: ${wiredByImportList(wiredByImport)}.`,
+ };
+ }
+ if (!appPackageNamesTheme(cwd) && wiring.unconfirmed.length > 0) {
+ const files = wiring.unconfirmed.map(({file}) => file).join(', ');
+ return {
+ id: 'themes',
+ label,
+ status: 'info',
+ message: `Theme package(s) installed (${names}); ${files} pass${wiring.unconfirmed.length === 1 ? 'es' : ''} a theme to Theme that doctor could not trace to a theme import, so it could not confirm which theme is wired.`,
+ fix: `If no theme is applied, add one with \`${run} theme add <slug>\`.`,
+ };
+ }
if (!appPackageNamesTheme(cwd)) {
return {
id: 'themes',
diff --git a/packages/cli/api/doctor/theme-checks.test.mjs b/packages/cli/api/doctor/theme-checks.test.mjs
index f871183fda..f6e1f040d2 100644
--- a/packages/cli/api/doctor/theme-checks.test.mjs
+++ b/packages/cli/api/doctor/theme-checks.test.mjs
@@ -7,7 +7,11 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {spawnSync} from 'node:child_process';
-import {checkAppThemes, checkThemes} from './theme-checks.mjs';
+import {
+ checkAppThemes,
+ checkThemes,
+ themeImportWiring,
+} from './theme-checks.mjs';
import {runChecks} from './doctor.mjs';
import {themeAdd} from '../theme/add/add.mjs';
import {themeEject} from '../theme/eject/eject.mjs';
@@ -272,6 +276,356 @@ describe('the released themes check', () => {
});
});
+ /**
+ * An app with installed single-theme packages that export their built module
+ * and stylesheet, as the published `@astryxdesign/theme-*` packages do.
+ * @param {string} name @param {string[]} slugs
+ */
+ function appWithBuiltThemes(name, slugs) {
+ const dir = emptyApp(name);
+ write(
+ path.join(dir, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ private: true,
+ dependencies: Object.fromEntries(
+ slugs.map(slug => [`@astryxdesign/theme-${slug}`, CLI_VERSION]),
+ ),
+ }),
+ );
+ write(
+ path.join(dir, 'node_modules/@astryxdesign/core/package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),
+ );
+ for (const slug of slugs) {
+ const packageDir = path.join(
+ dir,
+ 'node_modules/@astryxdesign',
+ `theme-${slug}`,
+ );
+ write(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({
+ name: `@astryxdesign/theme-${slug}`,
+ version: CLI_VERSION,
+ type: 'module',
+ exports: {
+ '.': './dist/index.js',
+ './built': `./dist/${slug}.js`,
+ './theme.css': './dist/theme.css',
+ },
+ }),
+ );
+ write(
+ path.join(packageDir, `dist/${slug}.js`),
+ `export const ${slug}Theme = {name: '${slug}', tokens: {}};\n`,
+ );
+ write(
+ path.join(packageDir, 'dist/index.js'),
+ `export {${slug}Theme} from './${slug}.js';\n`,
+ );
+ write(
+ path.join(packageDir, 'dist/theme.css'),
+ `[data-astryx-theme="${slug}"] { --color-text: black; }\n`,
+ );
+ }
+ return dir;
+ }
+
+ /** @param {string} dir */
+ async function themesCheck(dir) {
+ return checkThemes(
+ dir,
+ await checkAppThemes(dir),
+ await themeImportWiring(dir),
+ );
+ }
+
+ it('counts themes the app imports by their built module or stylesheet as wired, naming the file', async () => {
+ // The shape of an internal app template: a layout that imports each
+ // theme stylesheet and a provider that imports each built theme.
+ const dir = appWithBuiltThemes('themes-imported', ['neutral', 'butter']);
+ write(
+ path.join(dir, 'app/layout.tsx'),
+ "import '@astryxdesign/core/astryx.css';\nimport '@astryxdesign/theme-neutral/theme.css';\nimport '@astryxdesign/theme-butter/theme.css';\nexport default function Layout() { return null; }\n",
+ );
+ write(
+ path.join(dir, 'app/themes/ThemeProvider.tsx'),
+ "import {butterTheme} from '@astryxdesign/theme-butter/built';\nimport {neutralTheme} from '@astryxdesign/theme-neutral/built';\nexport const themes = {butterTheme, neutralTheme};\n",
+ );
+
+ expect((await themeImportWiring(dir)).wired).toEqual([
+ {
+ slug: 'butter',
+ owner: '@astryxdesign/theme-butter',
+ file: 'app/layout.tsx',
+ },
+ {
+ slug: 'neutral',
+ owner: '@astryxdesign/theme-neutral',
+ file: 'app/layout.tsx',
+ },
+ ]);
+ expect(await themesCheck(dir)).toEqual({
+ id: 'themes',
+ label: 'Theme packages',
+ status: 'pass',
+ message:
+ 'Theme package(s) installed (@astryxdesign/theme-butter, @astryxdesign/theme-neutral); wired by import: butter (app/layout.tsx), neutral (app/layout.tsx).',
+ });
+ const report = await runChecks({cwd: dir});
+ expect(report.checks.find(item => item.id === 'themes')).toMatchObject({
+ status: 'pass',
+ message: expect.stringContaining(
+ 'wired by import: butter (app/layout.tsx)',
+ ),
+ });
+ }, 30_000);
+
+ it('counts a built module import alone, and a stylesheet @import', async () => {
+ const dir = appWithBuiltThemes('themes-module-only', ['neutral', 'stone']);
+ write(
+ path.join(dir, 'src/theme.ts'),
+ "export {neutralTheme} from '@astryxdesign/theme-neutral/built';\n",
+ );
+ write(
+ path.join(dir, 'src/globals.css'),
+ '@import "@astryxdesign/theme-stone/theme.css";\n',
+ );
+
+ expect((await themeImportWiring(dir)).wired).toEqual([
+ {
+ slug: 'neutral',
+ owner: '@astryxdesign/theme-neutral',
+ file: 'src/theme.ts',
+ },
+ {
+ slug: 'stone',
+ owner: '@astryxdesign/theme-stone',
+ file: 'src/globals.css',
+ },
+ ]);
+ });
+
+ it('reads a stylesheet @import in url() without quotes, in any case', async () => {
+ const dir = appWithBuiltThemes('themes-css-url', ['stone']);
+ write(
+ path.join(dir, 'src/globals.css'),
+ '@IMPORT url(@astryxdesign/theme-stone/theme.css);\n',
+ );
+
+ expect((await themeImportWiring(dir)).wired).toEqual([
+ {
+ slug: 'stone',
+ owner: '@astryxdesign/theme-stone',
+ file: 'src/globals.css',
+ },
+ ]);
+ });
+
+ it('keeps the warning when the app only installs a theme, imports its types, or imports it from outside its own source', async () => {
+ const dir = appWithBuiltThemes('themes-not-imported', ['neutral']);
+ const warning = {
+ id: 'themes',
+ label: 'Theme packages',
+ status: 'warn',
+ message:
+ 'Theme package(s) installed (@astryxdesign/theme-neutral) but no theme appears wired.',
+ fix: expect.stringContaining('theme add <slug>`.'),
+ };
+ expect(await themesCheck(dir)).toEqual(warning);
+
+ write(
+ path.join(dir, 'src/types.ts'),
+ "import type {neutralTheme} from '@astryxdesign/theme-neutral/built';\nexport type T = typeof neutralTheme;\n",
+ );
+ write(
+ path.join(dir, 'dist/app.js'),
+ "import '@astryxdesign/theme-neutral/theme.css';\n",
+ );
+ write(
+ path.join(dir, 'node_modules/some-lib/index.js'),
+ "import '@astryxdesign/theme-neutral/theme.css';\n",
+ );
+ // Any other subpath of the package is not the theme's built import.
+ write(
+ path.join(dir, 'src/source.ts'),
+ "import {neutralTheme} from '@astryxdesign/theme-neutral';\nvoid neutralTheme;\n",
+ );
+ expect(await themeImportWiring(dir)).toEqual({wired: [], unconfirmed: []});
+ expect(await themesCheck(dir)).toEqual(warning);
+ });
+
+ it('follows a theme passed to Theme through a variable to its package', async () => {
+ // A provider that picks the theme into a variable, from the package root.
+ const dir = appWithBuiltThemes('themes-variable', ['matcha']);
+ write(
+ path.join(dir, 'app/providers.tsx'),
+ [
+ "import {Theme} from '@astryxdesign/core/theme';",
+ "import {matchaTheme} from '@astryxdesign/theme-matcha';",
+ 'const appTheme = matchaTheme;',
+ 'export function Providers({children}: {children: React.ReactNode}) {',
+ ' return <Theme theme={appTheme} mode="system">{children}</Theme>;',
+ '}',
+ '',
+ ].join('\n'),
+ );
+
+ expect(await themeImportWiring(dir)).toEqual({
+ wired: [
+ {
+ slug: 'matcha',
+ owner: '@astryxdesign/theme-matcha',
+ file: 'app/providers.tsx',
+ },
+ ],
+ unconfirmed: [],
+ });
+ expect(await themesCheck(dir)).toMatchObject({
+ status: 'pass',
+ message: expect.stringContaining(
+ 'wired by import: matcha (app/providers.tsx)',
+ ),
+ });
+ });
+
+ it('follows an aliased Theme, defineTheme extends and a relative re-export', async () => {
+ const dir = appWithBuiltThemes('themes-traced', ['neutral', 'stone']);
+ write(
+ path.join(dir, 'src/brand.ts'),
+ [
+ "import {defineTheme} from '@astryxdesign/core';",
+ "import {neutralTheme as base} from '@astryxdesign/theme-neutral';",
+ "export const brandTheme = defineTheme({name: 'brand', extends: base});",
+ "export {stoneTheme as quietTheme} from '@astryxdesign/theme-stone';",
+ '',
+ ].join('\n'),
+ );
+ write(
+ path.join(dir, 'src/App.tsx'),
+ [
+ "import {Theme as AppTheme} from '@astryxdesign/core';",
+ "import {brandTheme, quietTheme} from './brand';",
+ 'export const App = () => (',
+ ' <AppTheme theme={brandTheme}><AppTheme theme={quietTheme as never} /></AppTheme>',
+ ');',
+ '',
+ ].join('\n'),
+ );
+
+ expect((await themeImportWiring(dir)).wired).toEqual([
+ {
+ slug: 'neutral',
+ owner: '@astryxdesign/theme-neutral',
+ file: 'src/App.tsx',
+ },
+ {slug: 'stone', owner: '@astryxdesign/theme-stone', file: 'src/App.tsx'},
+ ]);
+ });
+
+ it('never counts a theme whose package is not installed', async () => {
+ // The CLI bundles a descriptor for every official theme; that is not the
+ // package being installed.
+ const dir = emptyApp('themes-not-installed');
+ write(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name: 'app', private: true}),
+ );
+ write(
+ path.join(dir, 'node_modules/@astryxdesign/core/package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),
+ );
+ write(
+ path.join(dir, 'app/providers.tsx'),
+ [
+ "import {Theme} from '@astryxdesign/core/theme';",
+ "import {neutralTheme} from '@astryxdesign/theme-neutral/built';",
+ "import '@astryxdesign/theme-neutral/theme.css';",
+ 'export const Providers = ({children}: any) => (',
+ ' <Theme theme={neutralTheme}>{children}</Theme>',
+ ');',
+ '',
+ ].join('\n'),
+ );
+
+ expect((await themeImportWiring(dir)).wired).toEqual([]);
+ expect(await themesCheck(dir)).toMatchObject({
+ status: 'warn',
+ message: 'No @astryxdesign/theme-* packages are installed.',
+ });
+ });
+
+ it('leaves a theme declared inside a component unconfirmed, like other module readers', async () => {
+ const dir = appWithBuiltThemes('themes-inner-scope', ['matcha']);
+ write(
+ path.join(dir, 'app/providers.tsx'),
+ [
+ "import {Theme} from '@astryxdesign/core/theme';",
+ "import {matchaTheme} from '@astryxdesign/theme-matcha';",
+ 'export function Providers({children}: any) {',
+ ' const theme = matchaTheme;',
+ ' return <Theme theme={theme}>{children}</Theme>;',
+ '}',
+ '',
+ ].join('\n'),
+ );
+
+ expect(await themeImportWiring(dir)).toEqual({
+ wired: [],
+ unconfirmed: [{file: 'app/providers.tsx'}],
+ });
+ });
+
+ it('says it could not confirm a theme passed to Theme that it cannot trace', async () => {
+ const dir = appWithBuiltThemes('themes-untraced', ['matcha']);
+ write(
+ path.join(dir, 'app/providers.tsx'),
+ [
+ "import {Theme} from '@astryxdesign/core/theme';",
+ 'export function Providers({theme, children}: any) {',
+ ' return <Theme theme={theme}>{children}</Theme>;',
+ '}',
+ '',
+ ].join('\n'),
+ );
+
+ expect(await themeImportWiring(dir)).toEqual({
+ wired: [],
+ unconfirmed: [{file: 'app/providers.tsx'}],
+ });
+ expect(await themesCheck(dir)).toEqual({
+ id: 'themes',
+ label: 'Theme packages',
+ status: 'info',
+ message:
+ 'Theme package(s) installed (@astryxdesign/theme-matcha); app/providers.tsx passes a theme to Theme that doctor could not trace to a theme import, so it could not confirm which theme is wired.',
+ fix: expect.stringContaining('theme add <slug>`.'),
+ });
+ });
+
+ it('leaves package.json astryx.theme deciding the result, without scanning', async () => {
+ const dir = appWithBuiltThemes('themes-astryx-theme', ['neutral']);
+ write(
+ path.join(dir, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ private: true,
+ astryx: {theme: '@astryxdesign/theme-neutral'},
+ }),
+ );
+ write(
+ path.join(dir, 'app/layout.tsx'),
+ "import '@astryxdesign/theme-neutral/theme.css';\n",
+ );
+ expect(await themeImportWiring(dir)).toEqual({wired: [], unconfirmed: []});
+ expect(await themesCheck(dir)).toMatchObject({
+ status: 'pass',
+ message:
+ 'Theme package(s) installed (@astryxdesign/theme-neutral); wired via package.json astryx.theme.',
+ });
+ });
+
it('appears once in the doctor report, right after version alignment, with and without a module', async () => {
const {dir} = await fixture();
for (const cwd of [emptyApp('themes-report'), dir]) {
diff --git a/packages/cli/foundation/discovery/module-exports.mjs b/packages/cli/foundation/discovery/module-exports.mjs
index 01ab5a478b..771d0ddbfe 100644
--- a/packages/cli/foundation/discovery/module-exports.mjs
+++ b/packages/cli/foundation/discovery/module-exports.mjs
@@ -1317,11 +1317,17 @@ export function exportScalarType(file, exportName) {
* then have the same final origin. Null when an alias cannot be followed (to
* a default or namespace import, a member such as `Icons.X`, or an import
* that does not resolve), so a caller leaves the comparison unchecked.
+ * `unwrap`, when given, names a value a declaration stands for besides a
+ * plain alias (a theme made by `defineTheme({extends: base})` stands for
+ * `base`): it receives the declaration's initializer and returns the
+ * expression to follow, or null for none. A followed expression that is not
+ * an identifier makes the origin unknown.
* @param {{file: string, name: string}} origin
* @param {Set<string>} [seen]
+ * @param {(init: any) => any} [unwrap]
* @returns {{file: string, name: string} | null}
*/
-export function aliasedOrigin(origin, seen = new Set()) {
+export function aliasedOrigin(origin, seen = new Set(), unwrap) {
const identity = `${origin.file}\0${origin.name}`;
if (seen.has(identity)) return null;
seen.add(identity);
@@ -1344,16 +1350,88 @@ export function aliasedOrigin(origin, seen = new Set()) {
) {
continue;
}
- const init = withoutTypeWrappers(declarator.init);
+ const declared = withoutTypeWrappers(declarator.init);
+ const followed = declared && unwrap ? unwrap(declared) : null;
+ const init = followed ? withoutTypeWrappers(followed) : declared;
if (init?.type === 'MemberExpression') return null;
- if (init?.type !== 'Identifier') return origin;
+ if (init?.type !== 'Identifier') return followed ? null : origin;
const next = bindingOrigin(ast, origin.file, init.name, new Set());
- return next ? aliasedOrigin(next, seen) : null;
+ return next ? aliasedOrigin(next, seen, unwrap) : null;
}
}
return origin;
}
+/**
+ * Where the value each `<Name prop={value}>` element of a module passes is
+ * declared, one entry per element, read without running anything. `Name` is
+ * a runtime import of `name` from one of `sources` (renames included). The
+ * value is followed with {@link aliasedOrigin} (passing `unwrap`) from the
+ * module-scope binding it names, through local files and installed packages.
+ * An entry is null when the value is not an identifier or its origin cannot
+ * be proved (a parameter or an import that does not resolve gives the
+ * module's own name, and a member or a default import gives null). An element
+ * without `prop` gives no entry.
+ * @param {string} file
+ * @param {{sources: ReadonlySet<string>, name: string, prop: string, unwrap?: (init: any) => any}} element
+ * @returns {Array<{file: string, name: string} | null>}
+ */
+export function elementPropOrigins(file, {sources, name, prop, unwrap}) {
+ let ast;
+ try {
+ ast = parseModule(file);
+ } catch {
+ return [];
+ }
+ /** @type {Set<string>} */
+ const locals = new Set();
+ for (const node of ast.program.body) {
+ if (
+ node.type !== 'ImportDeclaration' ||
+ node.importKind === 'type' ||
+ !sources.has(node.source?.value)
+ ) {
+ continue;
+ }
+ for (const specifier of node.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.importKind !== 'type' &&
+ (specifier.imported?.name ?? specifier.imported?.value) === name
+ ) {
+ locals.add(specifier.local.name);
+ }
+ }
+ }
+ if (locals.size === 0) return [];
+ /** @type {Array<{file: string, name: string} | null>} */
+ const origins = [];
+ for (const element of nodesOfType(ast.program, 'JSXOpeningElement')) {
+ if (
+ element.name?.type !== 'JSXIdentifier' ||
+ !locals.has(element.name.name)
+ ) {
+ continue;
+ }
+ const attribute = (element.attributes ?? []).find(
+ (/** @type {any} */ item) =>
+ item.type === 'JSXAttribute' && item.name?.name === prop,
+ );
+ if (!attribute) continue;
+ const value =
+ attribute.value?.type === 'JSXExpressionContainer'
+ ? withoutTypeWrappers(attribute.value.expression)
+ : null;
+ if (value?.type !== 'Identifier') {
+ origins.push(null);
+ continue;
+ }
+ const binding = bindingOrigin(ast, file, value.name, new Set());
+ origins.push(binding ? aliasedOrigin(binding, new Set(), unwrap) : null);
+ }
+ return origins;
+}
+
/**
* Where a top-level binding of a parsed module comes from: an import from a
* local module is followed to its origin; anything else is declared here.
diff --git a/packages/cli/foundation/discovery/module-exports.test.mjs b/packages/cli/foundation/discovery/module-exports.test.mjs
index 32577f53eb..c750b733b4 100644
--- a/packages/cli/foundation/discovery/module-exports.test.mjs
+++ b/packages/cli/foundation/discovery/module-exports.test.mjs
@@ -10,6 +10,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
+ elementPropOrigins,
moduleExportOrigin,
moduleExportSource,
staticExportObject,
@@ -207,3 +208,71 @@ describe('a library of thousands of icons', () => {
}
}, 60_000);
});
+
+describe('elementPropOrigins', () => {
+ const THEME = {
+ sources: new Set(['@acme/core']),
+ name: 'Theme',
+ prop: 'theme',
+ /** @param {any} init */
+ unwrap: init =>
+ init.type === 'CallExpression' && init.callee?.name === 'extend'
+ ? init.arguments[0]
+ : null,
+ };
+
+ it('follows each element value through aliases, re-exports, unwrap and an installed package', () => {
+ const pkg = path.join(dir, 'node_modules/@acme/themes');
+ fs.mkdirSync(path.join(pkg, 'dist'), {recursive: true});
+ fs.writeFileSync(
+ path.join(pkg, 'package.json'),
+ JSON.stringify({name: '@acme/themes', exports: {'.': './dist/index.js'}}),
+ );
+ fs.writeFileSync(
+ path.join(pkg, 'dist/index.js'),
+ "export {oceanTheme} from './ocean.js';\n",
+ );
+ const ocean = path.join(pkg, 'dist/ocean.js');
+ fs.writeFileSync(ocean, 'export const oceanTheme = {};\n');
+ write(
+ 'brand.ts',
+ "import {oceanTheme as base} from '@acme/themes';\nexport const brand = extend(base);\n",
+ );
+ const app = write(
+ 'App.tsx',
+ [
+ "import {Theme as T} from '@acme/core';",
+ "import {oceanTheme} from '@acme/themes';",
+ "import {brand} from './brand';",
+ 'const picked = oceanTheme;',
+ 'export const App = ({theme}: any) => (',
+ ' <T theme={picked}><T theme={brand as any} /><T theme={theme} /><T theme={themes.x} /><T /></T>',
+ ');',
+ '',
+ ].join('\n'),
+ );
+
+ expect(elementPropOrigins(app, THEME)).toEqual([
+ {file: ocean, name: 'oceanTheme'},
+ {file: ocean, name: 'oceanTheme'},
+ {file: app, name: 'theme'},
+ null,
+ ]);
+ });
+
+ it('gives nothing for a module that never imports the element', () => {
+ const app = write(
+ 'Other.tsx',
+ "import {Theme} from 'elsewhere';\nexport const A = () => <Theme theme={x} />;\n",
+ );
+ expect(elementPropOrigins(app, THEME)).toEqual([]);
+ });
+
+ it('gives null when the package a value comes from is not installed', () => {
+ const app = write(
+ 'Missing.tsx',
+ "import {Theme} from '@acme/core';\nimport {gone} from '@acme/missing';\nexport const A = () => <Theme theme={gone} />;\n",
+ );
+ expect(elementPropOrigins(app, THEME)).toEqual([null]);
+ });
+});
diff --git a/packages/cli/foundation/render/embedded-imports.mjs b/packages/cli/foundation/render/embedded-imports.mjs
index fec3486012..d93238133a 100644
--- a/packages/cli/foundation/render/embedded-imports.mjs
+++ b/packages/cli/foundation/render/embedded-imports.mjs
@@ -26,7 +26,7 @@ import {isAssetPath} from './assets.mjs';
* @param {string} css
* @returns {string[]}
*/
-function cssImports(css) {
+export function cssImports(css) {
/** @type {string[]} */
const out = [];
try {