An open source design system that's fully customizable and agent ready
TypeScript
[CLI] Name the theme package on import and teach import in the theme list (#7154)
Joeyf2f43e1c7b9b
diff --git a/.changeset/theme-import-names-package.md b/.changeset/theme-import-names-package.mdnew file mode 100644index 0000000000..b4589ce432--- /dev/null+++ b/.changeset/theme-import-names-package.md@@ -0,0 +1,11 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx theme add <slug> --import` names the npm package that owns the added theme, in its JSON envelope (`package`, directly after `type`) and in its text output, the same way other results about one artifact do. A local theme has no package, so its result has no `package`, and `theme remove` and `theme use` are unchanged.++`astryx theme add --list` keeps its JSON. Its text now names `theme add <slug> --import` to use a theme and `theme eject <slug>` to fork one, instead of the deprecated copy form.++`astryx doctor`'s `themes` check is now `theme-management`, with focused `theme-*` checks beside it once a project has a generated theme module.++@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 8727647c2d..e6d0749bc6 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -463,7 +463,7 @@ Every response has a `type` discriminant. The full set is below (generated from| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. || `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. || `theme.add` | The released source-copy receipt: slug, displayName, maintained flag, owner package, outputDir, source entry, exportName, and files. Its additive meta.deprecations entry names DEP-0005 and the source-fork/import replacements. |-| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. |+| `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. || `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. || `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. || `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states, deprecatedFor?}, where props and states are its legal override keys and deprecatedFor names the canonical replacement key. |diff --git a/packages/cli/api/doctor/theme-checks.test.mjs b/packages/cli/api/doctor/theme-checks.test.mjsindex 5322ba8083..a03dc7e4b8 100644--- a/packages/cli/api/doctor/theme-checks.test.mjs+++ b/packages/cli/api/doctor/theme-checks.test.mjs@@ -456,6 +456,49 @@ describe('app-theme doctor checks', () => {]);});+ it('reads astryx.theme from the app package when node_modules is hoisted to a workspace root', async () => {+ const root = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-doctor-monorepo-'),+ );+ dirs.push(root);+ write(+ path.join(root, 'package.json'),+ JSON.stringify({name: 'mono', private: true, workspaces: ['packages/*']}),+ );+ for (const name of ['@astryxdesign/core', '@astryxdesign/theme-neutral']) {+ write(+ path.join(root, 'node_modules', name, 'package.json'),+ JSON.stringify({name, version: '1.0.0'}),+ );+ }+ const app = path.join(root, 'packages/app');+ write(+ path.join(app, 'package.json'),+ JSON.stringify({+ name: 'app',+ private: true,+ dependencies: {+ '@astryxdesign/core': '1.0.0',+ '@astryxdesign/theme-neutral': '1.0.0',+ },+ astryx: {theme: '@astryxdesign/theme-neutral'},+ }),+ );++ expect(await checkAppThemes(app)).toEqual([+ expect.objectContaining({+ id: 'theme-management',+ status: 'info',+ message: expect.stringContaining(+ 'astryx.theme value "@astryxdesign/theme-neutral" remains active',+ ),+ }),+ ]);+ const doctor = runDoctor(app);+ expect(doctor.stdout).toContain('remains active');+ expect(doctor.stdout).not.toContain('no theme appears wired');+ });+it('names an unmigrated copy without failing a project that has no module', async () => {const dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-unmigrated-'),diff --git a/packages/cli/api/theme/_adapter.mjs b/packages/cli/api/theme/_adapter.mjsindex 6872af5d28..e194bda199 100644--- a/packages/cli/api/theme/_adapter.mjs+++ b/packages/cli/api/theme/_adapter.mjs@@ -633,8 +633,16 @@ async function writeThemeApp(ERROR_CODES.ERR_WRITE_FAILED,);}+ // A result about the one theme `theme add` just added names the npm package+ // that owns it (cli-surface INV28). A local theme has no package to name, and+ // remove and use report the whole record rather than one added theme.+ const added =+ action === 'add'+ ? prepared.entries.find(theme => theme.slug === slug)+ : undefined;return {type: 'theme.app',+ ...(added && added.source !== 'local' ? {package: added.owner} : {}),data: {themes: prepared.entries.map(theme => ({slug: theme.slug,diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjsindex 65acc57d44..7ac9464053 100644--- a/packages/cli/api/theme/theme.type.mjs+++ b/packages/cli/api/theme/theme.type.mjs@@ -106,6 +106,8 @@* astryx --json theme add <slug> --import / remove / use* @typedef {object} ThemeAppResponse* @property {'theme.app'} type+ * @property {string} [package] npm package that owns the theme `theme add`+ * added. Omitted for a local theme, and for remove and use.* @property {{themes: ThemeAppEntry[], default: string, modulePath: string, change: {action: 'add'|'remove'|'use', slug: string, changed: boolean, firstAdd: boolean}}} data*/diff --git a/packages/cli/api/theme/themeAdd.doc.mjs b/packages/cli/api/theme/themeAdd.doc.mjsindex 7f7fa11921..b21603dd63 100644--- a/packages/cli/api/theme/themeAdd.doc.mjs+++ b/packages/cli/api/theme/themeAdd.doc.mjs@@ -66,7 +66,7 @@ export const doc = {{type: 'theme.app',description:- 'The complete generated-module state and add change when import is true.',+ 'The complete generated-module state and add change when import is true. Its envelope package names the npm package that owns the added theme, except for a local theme.',},],throws: [diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex c433ac99b2..506cf70552 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -37,6 +37,7 @@ import {emit,section,text,+ record,records,code,list,@@ -222,7 +223,8 @@ async function warnOnThemeIntegrationIssues(json) {}/**- * Preserve the released human projection of `theme add --list`.+ * Print `theme add --list`. Its JSON stays the released `theme.list`; its text+ * names the commands of the current lifecycle stage (AST-050 FR12).* @param {import('../../../api/theme/theme.type.mjs').ThemeListEntry[]} themes*/function printThemeAddList(themes) {@@ -246,7 +248,8 @@ function printThemeAddList(themes) {}),),text(- `Usage:\n ${run} theme add <slug> [target-path] Scaffold a theme file you own`,+ `Import one: ${run} theme add <slug> --import [--package <package>]\n` ++ `Fork source: ${run} theme eject <slug> [target-path]`,),more,);@@ -315,6 +318,7 @@ function printThemeList(themes, unmigratedCopies = []) {*/function printThemeApp(result) {const {themes, default: defaultSlug, modulePath, change} = result.data;+ if (result.package !== undefined) emit(record({package: result.package}));emit(section('App themes', `${themes.length} added`),records(themes, {diff --git a/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjsindex 5886680a2b..e3d90885a2 100644--- a/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs+++ b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs@@ -68,7 +68,7 @@ describe('theme add compatibility lifecycle', () => {});});- it('keeps the list path unchanged and warning-free', async () => {+ it('keeps the list JSON unchanged and names the stage commands in text', async () => {fs.mkdirSync(path.join(tmpDir, 'src/themes/broken'), {recursive: true});fs.writeFileSync(path.join(tmpDir, 'src/themes/broken/brokenTheme.ts'),@@ -78,9 +78,12 @@ describe('theme add compatibility lifecycle', () => {const textResult = await runCli(['theme', 'add', '--list'], tmpDir);expect(textResult.status, textResult.stderr).toBe(0);expect(textResult.stdout).toContain(- 'theme add <slug> [target-path] Scaffold a theme file you own',+ 'Import one: pnpm exec astryx theme add <slug> --import [--package <package>]',);- expect(textResult.stdout).not.toContain('theme add <slug> --import');+ expect(textResult.stdout).toContain(+ 'Fork source: pnpm exec astryx theme eject <slug> [target-path]',+ );+ expect(textResult.stdout).not.toContain('theme add <slug> [target-path]');expect(textResult.stderr).not.toContain('deprecated');const result = await runCli(['theme', 'add', '--list', '--json'], tmpDir);diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex bd1e797d4d..ff9063da47 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -249,7 +249,7 @@ export const doc = {{value: 'theme.app',description:- 'The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change.',+ 'The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none.',},{value: 'theme.eject',diff --git a/packages/cli/test/inv28-package-provenance.test.mjs b/packages/cli/test/inv28-package-provenance.test.mjsindex 4ea96bfc6a..4c48314fe7 100644--- a/packages/cli/test/inv28-package-provenance.test.mjs+++ b/packages/cli/test/inv28-package-provenance.test.mjs@@ -45,6 +45,9 @@ vi.mock('../foundation/config/project.mjs', async importOriginal => {});const {component} = await import('../api/component/component.mjs');const {search} = await import('../api/search/search.mjs');+const {themeAdd} = await import('../api/theme/add/add.mjs');+const {themeEject} = await import('../api/theme/eject/eject.mjs');+const {themeBuild} = await import('../api/theme/build/build.mjs');// Each case scans the whole Core library; size the budget to the work.vi.setConfig({testTimeout: 60_000, hookTimeout: 60_000});@@ -214,6 +217,146 @@ describe('INV28: text names the same package', () => {});});+describe('INV28: theme add --import names the package that owns the added theme', () => {+ const THEMES = '@acme/themes';+ /** @type {string[]} */+ const dirs = [];++ /**+ * An app with one installed theme package that exports two built themes. It+ * lives under the working directory so the real Project.load can import the+ * package's integration entry.+ */+ function appWithThemePackage() {+ const dir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-inv28-theme-'),+ );+ dirs.push(dir);+ /** @param {string} rel @param {string} content */+ const write = (rel, content) => {+ fs.mkdirSync(path.dirname(path.join(dir, rel)), {recursive: true});+ fs.writeFileSync(path.join(dir, rel), content);+ };+ write('tsconfig.json', '{}\n');+ write(+ 'package.json',+ JSON.stringify({+ name: 'inv28-app',+ private: true,+ dependencies: {[THEMES]: '1.0.0', [CORE]: '1.0.0'},+ }),+ );+ write(+ 'node_modules/@astryxdesign/core/package.json',+ JSON.stringify({name: CORE, version: '1.0.0'}),+ );+ const pkg = 'node_modules/@acme/themes';+ write(+ `${pkg}/package.json`,+ JSON.stringify({+ name: THEMES,+ version: '1.0.0',+ type: 'module',+ peerDependencies: {[CORE]: '^1.0.0'},+ exports: {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ './themes/reef': './dist/reef.js',+ './themes/reef.css': './dist/reef.css',+ },+ }),+ );+ write(+ `${pkg}/astryx.integration.mjs`,+ "export default {themes: './themes'};\n",+ );+ for (const slug of ['ocean', 'reef']) {+ const source = `export const ${slug}Theme = {name: '${slug}', tokens: {}};\n`;+ write(+ `${pkg}/themes/${slug}/${slug}Theme.doc.mjs`,+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\n" ++ `export default {type: 'theme', name: '${slug}', displayName: '${slug}', description: '${slug} theme.', maintained: true};\n`,+ );+ write(`${pkg}/themes/${slug}/${slug}Theme.ts`, source);+ write(`${pkg}/dist/${slug}.js`, source);+ write(+ `${pkg}/dist/${slug}.css`,+ `[data-astryx-theme="${slug}"] { --color-text: black; }\n`,+ );+ }+ return dir;+ }++ afterEach(() => {+ while (dirs.length > 0) {+ fs.rmSync(/** @type {string} */ (dirs.pop()), {+ recursive: true,+ force: true,+ });+ }+ });++ it('theme.app names the package directly after type, and text names it', async () => {+ const dir = appWithThemePackage();+ const {status, stdout, stderr} = await runCli(+ ['--json', 'theme', 'add', 'ocean', '--import', '--package', THEMES],+ dir,+ );+ expect(status, stderr).toBe(0);+ const res = JSON.parse(stdout);+ expect(res.type).toBe('theme.app');+ expect(res.package).toBe(THEMES);+ expect(Object.keys(res).slice(0, 4)).toEqual([+ 'apiVersion',+ 'type',+ 'package',+ 'data',+ ]);++ const textRun = await runCli(+ ['theme', 'add', 'ocean', '--import', '--package', THEMES],+ appWithThemePackage(),+ );+ expect(textRun.status, textRun.stderr).toBe(0);+ expect(textRun.stdout).toContain(`package: ${THEMES}`);+ });++ it('use and remove report the record without a package', async () => {+ const dir = appWithThemePackage();+ await themeAdd('ocean', {cwd: dir, import: true, package: THEMES});+ const reef = /** @type {any} */ (+ await themeAdd('reef', {cwd: dir, import: true, package: THEMES})+ );+ expect(reef.package).toBe(THEMES);+ for (const args of [+ ['theme', 'use', 'reef'],+ ['theme', 'use', 'ocean'],+ ['theme', 'remove', 'reef'],+ ]) {+ const run = await runCli(['--json', ...args], dir);+ expect(run.status, run.stderr).toBe(0);+ const res = JSON.parse(run.stdout);+ expect(res.type, args.join(' ')).toBe('theme.app');+ expect(res, args.join(' ')).not.toHaveProperty('package');+ }+ });++ it('a local theme has no package to name', async () => {+ const dir = appWithThemePackage();+ await themeEject('ocean', {cwd: dir, package: THEMES});+ const sourceFile = path.join(dir, 'src/themes/ocean/oceanTheme.ts');+ await themeBuild(sourceFile, {}, {cwd: dir});+ const local = /** @type {any} */ (+ await themeAdd('ocean', {cwd: dir, import: true})+ );+ expect(local.type).toBe('theme.app');+ expect(local.data.themes).toContainEqual(+ expect.objectContaining({slug: 'ocean', source: 'local'}),+ );+ expect(local).not.toHaveProperty('package');+ });+});+describe('INV28: an integration names its own package, with nothing written for it', () => {/** @type {string} */let tmp;@@ -258,6 +401,8 @@ describe('INV28: an integration names its own package, with nothing written forafterEach(() => {fs.rmSync(tmp, {recursive: true, force: true});+ // A case added after this block must not inherit the mocked project.+ projectLoadMock.mockReset();});it('component detail, props, and source name the integration', async () => {diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjsindex 57f1895b6a..4ef9072ae5 100644--- a/scripts/check-cli-structure.mjs+++ b/scripts/check-cli-structure.mjs@@ -38,6 +38,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {fileURLToPath} from 'node:url';+import {runtimeStarExports} from './lib/api-index-star-exports.mjs';const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)),@@ -577,6 +578,11 @@ if (/\bresolveRecordedTheme\b/u.test(apiIndexSrc)) {'theme boundary: resolveRecordedTheme is internal and must not be exported from api/index.mjs',);}+for (const specifier of runtimeStarExports(apiIndexSrc)) {+ errors.push(+ `api boundary: api/index.mjs star exports or namespace imports ${specifier} — export each runtime function by name so FR1 and FR2 check it and internal helpers such as resolveRecordedTheme stay out of the public API`,+ );+}/** Extract named function exports from api/index.mjs (skip type re-exports). */const apiExports = new Set();diff --git a/scripts/lib/api-index-star-exports.mjs b/scripts/lib/api-index-star-exports.mjsnew file mode 100644index 0000000000..8859b3f201--- /dev/null+++ b/scripts/lib/api-index-star-exports.mjs@@ -0,0 +1,34 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Star re-exports in the CLI's public API entry.+ *+ * `packages/cli/api/index.mjs` names every runtime export, so the structure+ * guard can check each one against its CommandDoc and FunctionDoc and keep+ * internal helpers out of the public API. A star re-export of a runtime module,+ * or a namespace import of one that the entry can re-export by name, would+ * publish everything that module exports past both checks, so only type modules+ * (`*.type.mjs`) may be star exported or namespace imported.+ */++/**+ * The module specifiers of every `export * from`, `export * as name from`, and+ * `import * as name from` in `source` whose target is not a `*.type.mjs`+ * module, in source order. Comments are ignored.+ * @param {string} source contents of packages/cli/api/index.mjs+ * @returns {string[]}+ */+export function runtimeStarExports(source) {+ const code = source+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/^\s*\/\/.*$/gm, '');+ /** @type {string[]} */+ const offenders = [];+ for (const match of code.matchAll(+ /(?:export\s*\*\s*(?:as\s+[\w$]+\s+)?|import\s*\*\s*as\s+[\w$]+\s+)from\s*['"]([^'"]+)['"]/g,+ )) {+ const modulePath = match[1].split(/[?#]/)[0];+ if (!modulePath.endsWith('.type.mjs')) offenders.push(match[1]);+ }+ return offenders;+}diff --git a/scripts/lib/api-index-star-exports.test.mjs b/scripts/lib/api-index-star-exports.test.mjsnew file mode 100644index 0000000000..b7f15f457d--- /dev/null+++ b/scripts/lib/api-index-star-exports.test.mjs@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Mutation coverage for the api/index.mjs star re-export rule. */++import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';+import {runtimeStarExports} from './api-index-star-exports.mjs';++const API_INDEX = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../packages/cli/api/index.mjs',+);+const NAMED = "export {themeAdd} from './theme/add/add.mjs';\n";++describe('runtimeStarExports', () => {+ it('accepts the current public API entry', () => {+ expect(runtimeStarExports(fs.readFileSync(API_INDEX, 'utf8'))).toEqual([]);+ });++ it('accepts star re-exports and namespace imports of type modules', () => {+ expect(+ runtimeStarExports(+ `${NAMED}export * from './theme/theme.type.mjs';\nimport * as types from './theme/theme.type.mjs';\n`,+ ),+ ).toEqual([]);+ });++ it.each([+ ["export * from './theme/theme.mjs';", './theme/theme.mjs'],+ ['export * as theme from "./theme/theme.mjs";', './theme/theme.mjs'],+ ["export*from'./theme/_adapter.mjs'", './theme/_adapter.mjs'],+ [+ "import * as theme from './theme/theme.mjs';\nexport {theme};",+ './theme/theme.mjs',+ ],+ [+ "export * from './theme/theme.mjs?x.type.mjs';",+ './theme/theme.mjs?x.type.mjs',+ ],+ ])('rejects %s', (line, specifier) => {+ expect(runtimeStarExports(`${NAMED}${line}\n`)).toEqual([specifier]);+ });++ it('ignores commented-out lines', () => {+ expect(+ runtimeStarExports(+ "// export * from './theme/theme.mjs';\n/* export * from './theme/_adapter.mjs'; */\n",+ ),+ ).toEqual([]);+ });+});