An open source design system that's fully customizable and agent ready
TypeScript
[CLI] Make theme add import by default (#7138)
Joey58bb63895177
diff --git a/.changeset/app-theme-add-import-default.md b/.changeset/app-theme-add-import-default.mdnew file mode 100644index 0000000000..e66a2a3a33--- /dev/null+++ b/.changeset/app-theme-add-import-default.md@@ -0,0 +1,11 @@+---+'@astryxdesign/cli': minor+---++[breaking] CLN-0005 removes the deprecated `DEP-0005` copy default from `theme add`.++The old contract copied theme source with `theme add <slug> [path] [--overwrite] [--package <package>]` and returned `theme.add` JSON. The `ThemeAddResponse` type and the `theme.add` response type are removed, with their `ThemeAddResponse.type`, `ThemeAddResponse.data`, and `ThemeAddResponse.meta` fields. The replacement imports the built theme with `theme add <slug> [--package <package>]` and returns `theme.app`; `--import` remains an accepted no-op. Plain `theme add` now returns `theme.app` with the owner `package` directly after `type`. Local themes carry no package.++A path after `theme add` now exits 1 with `ERR_INVALID_ARGUMENT`, and `--overwrite` exits 1 with `ERR_INVALID_OPTION`; neither writes files. To migrate a script that copied source, run `theme eject` with the same slug, path, `--overwrite`, and `--package` arguments. A script that already runs `theme add --import` keeps the same meaning and needs no change.++@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 30fd688a0e..de6708210d 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -462,7 +462,6 @@ 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.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. 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. |diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjsindex 37934371aa..3c9eb55fce 100644--- a/packages/cli/api/doctor/doctor.doc.mjs+++ b/packages/cli/api/doctor/doctor.doc.mjs@@ -23,7 +23,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 --import. 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.',+ '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.',importPath: '@astryxdesign/cli/api',signature: 'doctor(options?: DoctorOptions): Promise<DoctorResponse>',keywords: ['doctor', 'diagnose', 'health', 'check', 'verify', 'environment'],diff --git a/packages/cli/api/doctor/theme-checks.mjs b/packages/cli/api/doctor/theme-checks.mjsindex 72220d3feb..f5a0bd7d67 100644--- a/packages/cli/api/doctor/theme-checks.mjs+++ b/packages/cli/api/doctor/theme-checks.mjs@@ -69,7 +69,7 @@ function unavailableChecks(message, moduleError = null) {moduleError && id === 'theme-module' ? moduleError.message : message,...(moduleError && id === 'theme-module'? {- fix: 'Keep one CLI-generated astryx-themes.ts or astryx-themes.js file, then run `astryx theme add <slug> --import`.',+ fix: 'Keep one CLI-generated astryx-themes.ts or astryx-themes.js file, then run `astryx theme add <slug>`.',}: {}),}));@@ -101,12 +101,12 @@ function refreshThemeCommand(projectDir, run, available, slug, owner) {);if (!isLocalThemeOwner(owner)) {const selector = theme?.package ?? owner;- return `npm install ${owner}@latest; ${run} theme add ${slug} --import --package ${selector}`;+ return `npm install ${owner}@latest; ${run} theme add ${slug} --package ${selector}`;}const source = theme? relative(projectDir, path.join(theme.sourceDir, theme.entry)): projectPath(path.join(owner, slug, `${slug}Theme.ts`));- return `${run} theme build ${source}; ${run} theme add ${slug} --import`;+ return `${run} theme build ${source}; ${run} theme add ${slug}`;}/** @param {string} source */@@ -478,7 +478,7 @@ export function checkThemes(cwd, appChecks) {label,status: 'warn',message: 'No @astryxdesign/theme-* packages are installed.',- fix: `Install a theme, e.g. \`npm install @astryxdesign/theme-neutral\`, then add it to the app with \`${run} theme add neutral --import\`.`,+ fix: `Install a theme, e.g. \`npm install @astryxdesign/theme-neutral\`, then add it to the app with \`${run} theme add neutral\`.`,};}const names = packages.join(', ');@@ -488,7 +488,7 @@ export function checkThemes(cwd, appChecks) {label,status: 'warn',message: `Theme package(s) installed (${names}) but no theme appears wired.`,- fix: `Add one to the app with \`${run} theme add <slug> --import\`.`,+ fix: `Add one to the app with \`${run} theme add <slug>\`.`,};}return {@@ -538,7 +538,7 @@ export async function checkAppThemes(cwd) {message: state.legacyTheme? `The CLI manages no themes. The released package.json astryx.theme value ${JSON.stringify(state.legacyTheme)} remains active.`: 'The CLI manages no themes because this project has no generated theme module.',- fix: `Start managing app themes with \`${run} theme add <slug> --import\`.`,+ fix: `Start managing app themes with \`${run} theme add <slug>\`.`,},];const migration = unmigratedCopyCheck(state.projectDir);@@ -656,7 +656,7 @@ export async function checkAppThemes(cwd) {label: 'Theme owners and built imports',status: 'fail',message: 'The generated record has no added themes.',- fix: `${run} theme add <slug> --import`,+ fix: `${run} theme add <slug>`,});} else if (discoveryError) {checks.push({@@ -664,7 +664,7 @@ export async function checkAppThemes(cwd) {label: 'Theme owners and built imports',status: 'fail',message: discoveryError.message,- fix: `${run} theme add <slug> --import`,+ fix: `${run} theme add <slug>`,});} else if (resolutionProblems.length > 0) {checks.push({@@ -1003,7 +1003,7 @@ export async function checkAppThemes(cwd) {fix:ownerEntries.length > 0? `${run} theme use ${ownerEntries[0][0]}`- : `${run} theme add <slug> --import`,+ : `${run} theme add <slug>`,},);@@ -1083,7 +1083,7 @@ export async function checkAppThemes(cwd) {if (localWarnings.length > 0) {fontWarningFixes.push(`Add <slug>.fonts.css beside each built local theme output, then ${localWarnings- .map(problem => `${run} theme add ${problem.theme.slug} --import`)+ .map(problem => `${run} theme add ${problem.theme.slug}`).join('; ')}.`,);}diff --git a/packages/cli/api/doctor/theme-checks.test.mjs b/packages/cli/api/doctor/theme-checks.test.mjsindex 4034f3ae4d..f15305fb5c 100644--- a/packages/cli/api/doctor/theme-checks.test.mjs+++ b/packages/cli/api/doctor/theme-checks.test.mjs@@ -172,7 +172,7 @@ describe('the released themes check', () => {label: 'Theme packages',status: 'warn',message: 'No @astryxdesign/theme-* packages are installed.',- fix: expect.stringContaining('theme add neutral --import'),+ fix: expect.stringContaining('theme add neutral`.'),});installThemePackage(dir, 'neutral');@@ -183,7 +183,7 @@ describe('the released themes check', () => {status: 'warn',message:'Theme package(s) installed (@astryxdesign/theme-neutral) but no theme appears wired.',- fix: expect.stringContaining('theme add <slug> --import'),+ fix: expect.stringContaining('theme add <slug>`.'),});expect(unwired.fix).not.toContain('ASTRYX_THEME');@@ -390,7 +390,7 @@ describe('app-theme doctor checks', () => {expect(check(await checkAppThemes(dir), 'theme-owners')).toMatchObject({status: 'fail',- fix: expect.stringContaining('theme add ocean --import'),+ fix: expect.stringContaining('theme add ocean'),});});@@ -592,9 +592,10 @@ describe('app-theme doctor checks', () => {id: 'theme-management',status: 'info',message: expect.stringContaining('manages no themes'),- fix: expect.stringContaining('theme add <slug> --import'),+ fix: expect.stringContaining('theme add <slug>'),}),]);+ expect(checks[0]?.fix).not.toContain('--import');});it('reads astryx.theme from the app package when node_modules is hoisted to a workspace root', async () => {diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjsindex e9f30b56cd..6aaf318886 100644--- a/packages/cli/api/init/run/run.mjs+++ b/packages/cli/api/init/run/run.mjs@@ -35,7 +35,7 @@ const VALID_AGENTS = ['claude', 'cursor', 'codex', 'hermes', 'muse', 'all'];/*** Build the "Next steps" lines printed at the end of `astryx init`.*- * Theme guidance follows the generated app-module workflow. `theme add --import` records+ * Theme guidance follows the generated app-module workflow. `theme add` records* installed built themes and imports their production and font stylesheets. The* app imports that module once and passes its default to <Theme>.*@@ -53,7 +53,7 @@ export function getNextSteps(invocation) {" 3. Import components: import { Button } from '@astryxdesign/core'",' 4. Add and wire a theme:',' npm install @astryxdesign/theme-neutral',- ` ${invocation} theme add neutral --import`,+ ` ${invocation} theme add neutral`," import { Theme } from '@astryxdesign/core'"," import { themes, defaultThemeSlug } from './astryx-themes'",' <Theme theme={themes[defaultThemeSlug]}>...</Theme>',@@ -141,7 +141,7 @@ function applyTheme(cwd, invocation, data) {logger.error('Could not write the theme template.');}logger.log(- ` Edit the blank template for a new theme, or run \`${invocation} theme add <slug> --import\` to import an installed built theme (\`${invocation} theme list\` to browse). Extend an imported theme for ordinary customization; use \`${invocation} theme eject <slug>\` only to fork source.`,+ ` Edit the blank template for a new theme, or run \`${invocation} theme add <slug>\` to import an installed built theme (\`${invocation} theme list\` to browse). Extend an imported theme for ordinary customization; use \`${invocation} theme eject <slug>\` only to fork source.`,);}diff --git a/packages/cli/api/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjsindex 8f587cd940..04b57d6df3 100644--- a/packages/cli/api/search/search.doc.mjs+++ b/packages/cli/api/search/search.doc.mjs@@ -55,7 +55,7 @@ export const doc = {{type: 'search',description:- 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, `displayName` and `kind` for templates, and `displayName` for themes. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from). A theme result is one theme you can import: `name` is its slug, its command is `astryx theme add --import <slug>`, and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes).',+ 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, `displayName` and `kind` for templates, and `displayName` for themes. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from). A theme result is one theme you can import: `name` is its slug, its command is `astryx theme add <slug>`, and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes).',},],throws: [diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex d764eb51c0..a6077e5d7a 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -1749,7 +1749,7 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {result = {...base,displayName: c._displayName,- command: `astryx theme add --import ${c.name}`,+ command: `astryx theme add ${c.name}`,};break;default:diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjsindex d4b75daa70..f7b85c503d 100644--- a/packages/cli/api/search/search.test.mjs+++ b/packages/cli/api/search/search.test.mjs@@ -99,7 +99,7 @@ describe('search leaf — per-domain result fields', () => {expect(['page', 'block']).toContain(res.kind);} else if (res.domain === 'theme') {expect(res.displayName).toMatch(/\S/);- expect(res.command).toMatch(/^astryx theme add /);+ expect(res.command).toBe(`astryx theme add ${res.name}`);}}}, SLOW);diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjsindex 4518f98706..481723e13d 100644--- a/packages/cli/api/search/search.type.mjs+++ b/packages/cli/api/search/search.type.mjs@@ -20,7 +20,7 @@* @property {number} score - Relevance score (higher is better).* @property {string} reason - Human-readable reason the candidate matched (e.g. `keyword "button"`).* @property {string} description - One-line description, when available.- * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add --import neutral` for a theme).+ * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add neutral` for a theme).* @property {string} [import] - Import path — present for component and hook results.* @property {string} [title] - Doc title — present for doc results.* @property {string} [section] - Section key — present when a doc result is one section of a topic; `command` reads only that section.diff --git a/packages/cli/api/theme/_adapter.mjs b/packages/cli/api/theme/_adapter.mjsindex e194bda199..ef79b8d2b1 100644--- a/packages/cli/api/theme/_adapter.mjs+++ b/packages/cli/api/theme/_adapter.mjs@@ -565,7 +565,7 @@ export function resolveRecordedThemes(state, available) {);if (!theme) {throw new AstryxError(- `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, then run \`astryx theme add ${slug} --import --package ${owner}\`.`,+ `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, then run \`astryx theme add ${slug} --package ${owner}\`.`,undefined,ERROR_CODES.ERR_UNKNOWN_THEME,);@@ -732,7 +732,7 @@ export async function removeThemeFromApp(slug, options = {}) {const recordedSlug = recordedThemeSlug(state, slug);if (!state.configured || recordedSlug == null) {throw new AstryxError(- `Theme "${slug}" is not added. Run \`astryx theme add ${slug} --import\` first.`,+ `Theme "${slug}" is not added. Run \`astryx theme add ${slug}\` first.`,undefined,ERROR_CODES.ERR_UNKNOWN_THEME,);@@ -776,7 +776,7 @@ export async function useThemeInApp(slug, options = {}) {const recordedSlug = recordedThemeSlug(state, slug);if (!state.configured || recordedSlug == null) {throw new AstryxError(- `Theme "${slug}" is not added. Run \`astryx theme add ${slug} --import\` first.`,+ `Theme "${slug}" is not added. Run \`astryx theme add ${slug}\` first.`,undefined,ERROR_CODES.ERR_UNKNOWN_THEME,);diff --git a/packages/cli/api/theme/add/add.binary.test.mjs b/packages/cli/api/theme/add/add.binary.test.mjsdeleted file mode 100644index a692d0da3c..0000000000--- a/packages/cli/api/theme/add/add.binary.test.mjs+++ /dev/null@@ -1,157 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import {afterEach, beforeEach, describe, expect, it} from 'vitest';-import * as fs from 'node:fs';-import * as os from 'node:os';-import * as path from 'node:path';-import {themeAdd} from './add.mjs';-import {themeEject} from '../eject/eject.mjs';-import {runCli} from '../../../test-utils/run-cli.mjs';--const HEADER = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n';--let tmpDir;--/** Every byte value, so any lossy text decoding shows up as a changed file. */-const FONT_BYTES = Buffer.concat([- Buffer.from('wOF2'),- Buffer.from(Array.from({length: 256}, (_, byte) => byte)),-]);--beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-binary-'));- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({- name: 'consumer',- dependencies: {'@acme/themes': '^1.0.0'},- }),- );- const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');- const themeDir = path.join(packageDir, 'themes', 'ocean');- fs.mkdirSync(path.join(themeDir, 'fonts'), {recursive: true});- fs.mkdirSync(path.join(themeDir, 'tokens'), {recursive: true});- fs.writeFileSync(- path.join(packageDir, 'package.json'),- JSON.stringify({name: '@acme/themes', version: '1.0.0'}),- );- fs.writeFileSync(- path.join(packageDir, 'astryx.integration.mjs'),- "export default {themes: './themes'};\n",- );- fs.writeFileSync(- path.join(themeDir, 'oceanTheme.doc.mjs'),- `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */-export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Integration theme that ships a font.', maintained: true};-`,- );- fs.writeFileSync(- path.join(themeDir, 'oceanTheme.ts'),- `${HEADER}export const oceanTheme = {};\n`,- );- fs.writeFileSync(- path.join(themeDir, 'icons.tsx'),- 'export const oceanIcons = {};\n',- );- fs.writeFileSync(path.join(themeDir, 'fonts', 'ocean.woff2'), FONT_BYTES);- fs.writeFileSync(- path.join(themeDir, 'tokens', 'colors.ts'),- "export const oceanBlue = '#0064e0';\n",- );-});--afterEach(() => {- fs.rmSync(tmpDir, {recursive: true, force: true});-});--describe('themeAdd keeps the released source-copy inventory', () => {- it('copies binary bytes and the integration authoring descriptor', async () => {- const result = await themeAdd('ocean', {- cwd: tmpDir,- package: '@acme/themes',- });-- expect(result.data.files).toEqual([- 'oceanTheme.ts',- 'fonts/ocean.woff2',- 'icons.tsx',- 'oceanTheme.doc.mjs',- 'tokens/colors.ts',- ]);- const copied = fs.readFileSync(- path.join(tmpDir, 'src', 'themes', 'ocean', 'fonts', 'ocean.woff2'),- );- expect(copied.equals(FONT_BYTES)).toBe(true);- expect(- fs.readFileSync(- path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.doc.mjs'),- 'utf-8',- ),- ).toContain("name: 'ocean'");- });-- it('keeps the released nested order in CLI JSON, text, and copied files', async () => {- const expected = [- 'oceanTheme.ts',- 'fonts/ocean.woff2',- 'icons.tsx',- 'oceanTheme.doc.mjs',- 'tokens/colors.ts',- ];- const json = await runCli(- ['theme', 'add', 'ocean', '--package', '@acme/themes', '--json'],- tmpDir,- );- expect(json.status, json.stderr).toBe(0);- expect(JSON.parse(json.stdout).data.files).toEqual(expected);- for (const file of expected) {- expect(- fs.existsSync(path.join(tmpDir, 'src', 'themes', 'ocean', file)),- ).toBe(true);- }-- fs.rmSync(path.join(tmpDir, 'src'), {recursive: true, force: true});- const text = await runCli(- ['theme', 'add', 'ocean', '--package', '@acme/themes'],- tmpDir,- );- expect(text.status, text.stderr).toBe(0);- const positions = expected.map(file =>- text.stdout.indexOf(`src/themes/ocean/${file}`),- );- expect(positions.every(position => position >= 0)).toBe(true);- expect(positions).toEqual([...positions].sort((a, b) => a - b));- });-});--describe('themeEject copies every file of the theme', () => {- it('copies a binary file byte for byte', async () => {- const result = await themeEject('ocean', {- cwd: tmpDir,- package: '@acme/themes',- });-- expect(result.data.files).toEqual([- 'oceanTheme.ts',- 'oceanTheme.doc.mjs',- 'fonts/ocean.woff2',- 'icons.tsx',- 'tokens/colors.ts',- ]);- const copied = fs.readFileSync(- path.join(tmpDir, 'src', 'themes', 'ocean', 'fonts', 'ocean.woff2'),- );- expect(copied.equals(FONT_BYTES)).toBe(true);- });-- it('still strips the repo header from a text source', async () => {- await themeEject('ocean', {cwd: tmpDir, package: '@acme/themes'});-- expect(- fs.readFileSync(- path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.ts'),- 'utf-8',- ),- ).toBe('export const oceanTheme = {};\n');- });-});diff --git a/packages/cli/api/theme/add/add.mjs b/packages/cli/api/theme/add/add.mjsindex 1159e325e5..6b6d6cac2b 100644--- a/packages/cli/api/theme/add/add.mjs+++ b/packages/cli/api/theme/add/add.mjs@@ -1,210 +1,37 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `astryx theme add` — copy by default; import built output by opt-in.+ * @file `astryx theme add` — add built theme output to the app.*- * The released command copies source and returns `theme.add`. `--import` adds- * the built theme to the generated app module and returns `theme.app`.+ * Plain `theme add` and the compatibility `--import` spelling both record the+ * built theme in the generated app module. Source copying belongs only to+ * `theme eject`.*/-import * as fs from 'node:fs';-import * as path from 'node:path';-import {addThemeToApp, findTheme, listAvailableThemes} from '../_adapter.mjs';-import {- assertWithin,- PathSafetyError,-} from '../../../foundation/fs/path-safety.mjs';+import {addThemeToApp} from '../_adapter.mjs';import {AstryxError} from '../../error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';-import {applyWrites} from '../../integration/add-helpers.mjs';-import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';--const COPY_DEPRECATION = Object.freeze({- id: 'DEP-0005',- replacements: ['theme eject', 'theme add --import'],-});--/** @param {string} slug */-function defaultTargetDir(slug) {- return path.join('src', 'themes', slug);-}--/**- * Strip repository boilerplate from UTF-8 text while preserving binary bytes.- * @param {Buffer} bytes- * @returns {Buffer|string}- */-function scaffoldContents(bytes) {- const text = bytes.toString('utf-8');- return Buffer.from(text, 'utf-8').equals(bytes)- ? stripCopyrightHeader(text)- : bytes;-}/**- * Bundled and package themes preserve their released copy inventories. Bundled- * themes keep their authoring descriptor behind; integration themes copy the- * complete directory, including the descriptor. Local themes are deliberately- * excluded: copying `theme add` resolves only bundled and package themes, while- * `--import` can select a built local theme.+ * Add one available built theme to the generated app module. `import` remains+ * accepted as a no-op so callers that opted in before the cleanup keep working.+ *+ * Removed source-copy options are rejected before discovery or any write, and+ * name the function that now owns them. `overwrite: false` remains an accepted+ * compatibility no-op.** @param {string} slug- * @param {{targetPath?: string, overwrite?: boolean, cwd?: string, package?: string}} options- * @returns {Promise<import('../theme.type.mjs').ThemeAddResponse>}- */-async function copyThemeSource(slug, options) {- const {- targetPath,- overwrite = false,- cwd = process.cwd(),- package: packageName,- } = options;-- const match = await findTheme(slug, {- cwd,- package: packageName,- includeLocal: false,- });- if (!match) {- const available = await listAvailableThemes(cwd, {includeLocal: false});- throw new AstryxError(- `Unknown theme "${slug}"${packageName ? ` in package "${packageName}"` : ''}`,- available.map(theme => ({- name: `${theme.slug} --package ${theme.package}`,- reason:- theme.source === 'bundled'- ? 'bundled theme'- : `provided by ${theme.package}`,- })),- ERROR_CODES.ERR_UNKNOWN_THEME,- );- }-- const rawTarget = targetPath || defaultTargetDir(match.slug);- let resolvedDir;- try {- resolvedDir = assertWithin(rawTarget, cwd, {label: 'theme target path'});- } catch (error) {- if (error instanceof PathSafetyError) {- throw new AstryxError(- error.message,- undefined,- ERROR_CODES.ERR_PATH_TRAVERSAL,- );- }- throw error;- }-- const descriptor = path- .relative(match.sourceDir, match.docPath)- .split(path.sep)- .join('/');- const copyFiles = match.bundled- ? match.files.filter(name => name !== descriptor)- : [match.entry, ...match.files.filter(name => name !== match.entry).sort()];- let writes;- try {- writes = copyFiles.map(name => ({- name,- src: path.join(match.sourceDir, name),- dest: assertWithin(name, resolvedDir, {- label: `theme destination for ${name}`,- }),- }));- } catch (error) {- if (error instanceof PathSafetyError) {- throw new AstryxError(- error.message,- undefined,- ERROR_CODES.ERR_PATH_TRAVERSAL,- );- }- throw error;- }-- for (const write of writes) {- if (!fs.existsSync(write.src)) {- throw new AstryxError(- `Theme "${match.slug}" is missing bundled file "${write.name}". ` +- 'Re-run `node scripts/generate-cli-themes.mjs` to rebuild the bundle.',- undefined,- ERROR_CODES.ERR_NO_SOURCE,- );- }- }-- if (!overwrite) {- const existing = writes.find(write => fs.existsSync(write.dest));- if (existing) {- const rel = path.relative(cwd, existing.dest) || existing.dest;- throw new AstryxError(- `Refusing to overwrite existing file ${rel}. ` +- 'Re-run with --overwrite (or -f) to replace it.',- undefined,- ERROR_CODES.ERR_FILE_EXISTS,- );- }- }-- try {- fs.mkdirSync(resolvedDir, {recursive: true});- const plans = writes.map(write => {- fs.mkdirSync(path.dirname(write.dest), {recursive: true});- const dest = assertWithin(write.name, resolvedDir, {- label: `theme destination for ${write.name}`,- });- return {- path: dest,- contents: scaffoldContents(fs.readFileSync(write.src)),- createOnly: !overwrite,- };- });- applyWrites(plans);- } catch (error) {- if (error instanceof AstryxError) throw error;- if (error instanceof PathSafetyError) {- throw new AstryxError(- error.message,- undefined,- ERROR_CODES.ERR_PATH_TRAVERSAL,- );- }- const message = error instanceof Error ? error.message : String(error);- throw new AstryxError(- `Failed to write theme files: ${message}`,- undefined,- ERROR_CODES.ERR_WRITE_FAILED,- );- }-- return {- type: 'theme.add',- data: {- slug: match.slug,- displayName: match.displayName,- maintained: match.maintained,- package: match.package,- outputDir: path.relative(cwd, resolvedDir) || '.',- entry: match.entry,- exportName: match.exportName,- files: copyFiles,- },- meta: {deprecations: [COPY_DEPRECATION]},- };-}--/**- * Copy one available source theme, or import its built output with `import`.- * @param {string} slug- * @param {{targetPath?: string, overwrite?: boolean, cwd?: string, package?: string, import?: boolean}} [options]- * @returns {Promise<import('../theme.type.mjs').ThemeAddResponse | import('../theme.type.mjs').ThemeAppResponse>}+ * @param {{targetPath?: string, overwrite?: boolean, import?: boolean, cwd?: string, package?: string}} [options]+ * @returns {Promise<import('../theme.type.mjs').ThemeAppResponse>}*/export async function themeAdd(slug, options = {}) {- if (!options.import) return copyThemeSource(slug, options);-- if (options.targetPath != null || options.overwrite === true) {+ const legacy = /** @type {{targetPath?: unknown, overwrite?: unknown}} */ (+ options+ );+ if (legacy.targetPath != null || legacy.overwrite === true) {throw new AstryxError(- '`theme add --import` cannot be combined with a target path or --overwrite.',+ '`themeAdd` no longer copies source or accepts targetPath or overwrite: true. ' ++ 'Call `themeEject` with the same slug and copy options to fork source.',undefined,ERROR_CODES.ERR_THEME_INVALID,);diff --git a/packages/cli/api/theme/add/add.rollback.test.mjs b/packages/cli/api/theme/add/add.rollback.test.mjsdeleted file mode 100644index 08729b0230..0000000000--- a/packages/cli/api/theme/add/add.rollback.test.mjs+++ /dev/null@@ -1,158 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * `theme eject` writes a theme as one transaction: when a later file fails to- * publish, every file it already replaced gets its previous bytes back and- * every file it created is removed. Publishing is forced to fail by wrapping- * the two calls that publish a staged file: `linkSync` for a new file and- * `renameSync` for a replacement.- *- * Separate file because vi.mock is hoisted and affects the whole module.- */--import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';-import * as os from 'node:os';-import * as path from 'node:path';--const failures = vi.hoisted(() => ({- /** Fail the Nth staged-file publish (1-based); 0 disables. */- publish: 0,- /** Also fail every rollback restore. */- restore: false,- count: 0,-}));--vi.mock('node:fs', async importOriginal => {- const actual = /** @type {typeof import('node:fs')} */ (- await importOriginal()- );- /** @param {string} source */- const isStaged = source => path.basename(String(source)).includes('.tmp');- /** @param {string} source */- const isRestore = source =>- path.basename(String(source)).includes('.restore-');- /** @param {string} source @param {string} op */- const maybeFail = (source, op) => {- if (isStaged(source) && failures.publish > 0) {- failures.count++;- if (failures.count === failures.publish) {- throw Object.assign(new Error(`EIO: forced ${op} failure`), {- code: 'EIO',- });- }- }- if (isRestore(source) && failures.restore) {- throw Object.assign(new Error(`EIO: forced restore failure`), {- code: 'EIO',- });- }- };- return {- ...actual,- linkSync: vi.fn((source, destination) => {- maybeFail(source, 'link');- return actual.linkSync(source, destination);- }),- renameSync: vi.fn((source, destination) => {- maybeFail(source, 'rename');- return actual.renameSync(source, destination);- }),- };-});--const fs = await import('node:fs');-const {themeEject} = await import('../eject/eject.mjs');-const {listThemes} = await import('../_adapter.mjs');--let tmpDir;--beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-rollback-'));- failures.publish = 0;- failures.restore = false;- failures.count = 0;-});--afterEach(() => {- failures.publish = 0;- failures.restore = false;- fs.rmSync(tmpDir, {recursive: true, force: true});-});--function stoneFiles() {- const theme = listThemes().find(entry => entry.slug === 'stone');- if (!theme) throw new Error('missing bundled theme stone');- expect(theme.files.length).toBeGreaterThanOrEqual(2);- return theme.files.map(name =>- path.join(tmpDir, 'src', 'themes', 'stone', name),- );-}--/** Entries staging or rollback left behind in the theme directory. */-function strays() {- const dir = path.join(tmpDir, 'src', 'themes', 'stone');- if (!fs.existsSync(dir)) return [];- return fs- .readdirSync(dir, {recursive: true})- .map(String)- .filter(name => name.includes('.tmp') || name.includes('.restore-'));-}--describe('themeEject rolls back a partial write', () => {- it('removes every created file when the second publish fails', async () => {- const files = stoneFiles();- failures.publish = 2;-- await expect(themeEject('stone', {cwd: tmpDir})).rejects.toMatchObject({- code: 'ERR_WRITE_FAILED',- });-- for (const file of files) expect(fs.existsSync(file)).toBe(false);- expect(strays()).toEqual([]);- });-- it('restores every replaced byte when the second publish fails', async () => {- const files = stoneFiles();- fs.mkdirSync(path.dirname(files[0]), {recursive: true});- const before = Buffer.from([0x00, 0xff, 0x0a, 0x62, 0x65, 0x66]);- fs.writeFileSync(files[0], before);- failures.publish = 2;-- await expect(- themeEject('stone', {cwd: tmpDir, overwrite: true}),- ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});-- expect(fs.readFileSync(files[0]).equals(before)).toBe(true);- for (const file of files.slice(1)) expect(fs.existsSync(file)).toBe(false);- expect(strays()).toEqual([]);- });-- it('names a file it could not restore', async () => {- const files = stoneFiles();- fs.mkdirSync(path.dirname(files[0]), {recursive: true});- fs.writeFileSync(files[0], 'before\n');- failures.publish = 2;- failures.restore = true;-- let error;- try {- await themeEject('stone', {cwd: tmpDir, overwrite: true});- } catch (caught) {- error = caught;- }-- expect(error?.code).toBe('ERR_WRITE_FAILED');- expect(error?.message).toContain('Could not restore');- expect(error?.message).toContain(files[0]);- });-- it('writes every file when nothing fails', async () => {- const files = stoneFiles();-- const result = await themeEject('stone', {cwd: tmpDir});-- expect(result.type).toBe('theme.eject');- for (const file of files) expect(fs.existsSync(file)).toBe(true);- expect(strays()).toEqual([]);- });-});diff --git a/packages/cli/api/theme/add/add.staging.test.mjs b/packages/cli/api/theme/add/add.staging.test.mjsdeleted file mode 100644index c4e4840299..0000000000--- a/packages/cli/api/theme/add/add.staging.test.mjs+++ /dev/null@@ -1,83 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import {afterEach, beforeEach, describe, expect, it} from 'vitest';-import * as fs from 'node:fs';-import * as os from 'node:os';-import * as path from 'node:path';-import {themeEject} from '../eject/eject.mjs';-import {listThemes} from '../_adapter.mjs';--let tmpDir;-let outsideDir;--beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-staging-'));- outsideDir = fs.mkdtempSync(- path.join(os.tmpdir(), 'astryx-themeeject-outside-'),- );-});--afterEach(() => {- fs.rmSync(tmpDir, {recursive: true, force: true});- fs.rmSync(outsideDir, {recursive: true, force: true});-});--/**- * Where `theme eject` writes the first file of `slug`.- * @param {string} slug- */-function firstDestination(slug) {- const theme = listThemes().find(entry => entry.slug === slug);- if (!theme) throw new Error(`missing bundled theme ${slug}`);- const dest = path.join(tmpDir, 'src', 'themes', slug, theme.files[0]);- fs.mkdirSync(path.dirname(dest), {recursive: true});- return dest;-}--// Staging names are unpredictable and created exclusively, so an entry planted-// at a predictable name beside the destination is never written through.-describe('themeEject staging writes stay inside the project', () => {- it('never writes through a link planted at a predictable staging name', async () => {- const victim = path.join(outsideDir, 'victim.txt');- fs.writeFileSync(victim, 'outside\n');- const dest = firstDestination('stone');- fs.symlinkSync(victim, `${dest}.${process.pid}.tmp`);-- await themeEject('stone', {cwd: tmpDir});-- expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');- expect(fs.lstatSync(dest).isFile()).toBe(true);- });-- it('never creates a file through a dangling link at a predictable staging name', async () => {- const victim = path.join(outsideDir, 'created.txt');- fs.symlinkSync(victim, `${firstDestination('stone')}.${process.pid}.tmp`);-- await themeEject('stone', {cwd: tmpDir});-- expect(fs.existsSync(victim)).toBe(false);- });-- it('refuses to replace a destination that links outside the project', async () => {- const victim = path.join(outsideDir, 'victim.txt');- fs.writeFileSync(victim, 'outside\n');- const dest = firstDestination('stone');- fs.symlinkSync(victim, dest);-- await expect(- themeEject('stone', {cwd: tmpDir, overwrite: true}),- ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});- expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');- expect(fs.lstatSync(dest).isSymbolicLink()).toBe(true);- });-- it('never creates a file through a dangling destination link', async () => {- const victim = path.join(outsideDir, 'created.txt');- fs.symlinkSync(victim, firstDestination('stone'));-- await expect(themeEject('stone', {cwd: tmpDir})).rejects.toMatchObject({- code: 'ERR_PATH_TRAVERSAL',- });- expect(fs.existsSync(victim)).toBe(false);- });-});diff --git a/packages/cli/api/theme/add/add.test.mjs b/packages/cli/api/theme/add/add.test.mjsindex 857daa603f..5449e75e73 100644--- a/packages/cli/api/theme/add/add.test.mjs+++ b/packages/cli/api/theme/add/add.test.mjs@@ -124,224 +124,7 @@ afterEach(() => {});describe('themeAdd', () => {- it('keeps the released source-copy response and works without built exports', async () => {- installTheme('ocean', '@acme/themes', {missingBuilt: true});-- const result = await themeAdd('ocean', {- cwd: tmpDir,- package: '@acme/themes',- });-- expect(result).toMatchObject({- type: 'theme.add',- data: {- slug: 'ocean',- displayName: 'ocean',- maintained: true,- package: '@acme/themes',- outputDir: 'src/themes/ocean',- entry: 'oceanTheme.ts',- exportName: 'oceanTheme',- files: ['oceanTheme.ts', 'oceanTheme.doc.mjs'],- },- meta: {- deprecations: [- {- id: 'DEP-0005',- replacements: ['theme eject', 'theme add --import'],- },- ],- },- });- expect(- fs.readFileSync(- path.join(tmpDir, 'src/themes/ocean/oceanTheme.ts'),- 'utf-8',- ),- ).toContain('export const oceanTheme');- expect(- fs.readFileSync(- path.join(tmpDir, 'src/themes/ocean/oceanTheme.doc.mjs'),- 'utf-8',- ),- ).toContain("name: 'ocean'");- expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(- false,- );- });-- it('keeps every released bundled copy receipt field and file', async () => {- const result = await themeAdd('neutral', {cwd: tmpDir});-- expect(result.data).toEqual({- slug: 'neutral',- displayName: 'Neutral',- maintained: true,- package: '@astryxdesign/cli',- outputDir: path.join('src', 'themes', 'neutral'),- entry: 'neutralTheme.ts',- exportName: 'neutralTheme',- files: [- 'neutralTheme.ts',- 'icons.tsx',- 'neutralPalettes.ts',- 'neutralPalettes.generated.ts',- 'neutralPaletteRefs.generated.ts',- 'neutralPalettes.generated.receipt.json',- 'palette.config.json',- ],- });- expect(- fs.readdirSync(path.join(tmpDir, 'src/themes/neutral')).sort(),- ).toEqual([...result.data.files].sort());- });-- it('keeps every relative import required by a copied theme', async () => {- const result = await themeAdd('neutral', {cwd: tmpDir});- const outputDir = path.join(tmpDir, result.data.outputDir);- const relativeImports = /from\s+['"](\.\.?\/[^'"]+)['"]/gu;-- for (const file of result.data.files) {- if (!/\.(?:ts|tsx|mjs)$/u.test(file)) continue;- const source = fs.readFileSync(path.join(outputDir, file), 'utf-8');- for (const [, specifier] of source.matchAll(relativeImports)) {- const imported = path.resolve(outputDir, path.dirname(file), specifier);- expect(- fs.existsSync(imported) ||- fs.existsSync(`${imported}.ts`) ||- fs.existsSync(`${imported}.tsx`) ||- fs.existsSync(`${imported}.mjs`),- ).toBe(true);- }- }- });-- it('strips the repository copyright header from copied text', async () => {- const result = await themeAdd('neutral', {cwd: tmpDir});- const first = path.join(- tmpDir,- result.data.outputDir,- result.data.files[0],- );- expect(fs.readFileSync(first, 'utf-8')).not.toMatch(- /Copyright \(c\) Meta Platforms/u,- );- });-- it('keeps case-insensitive copy lookup', async () => {- const result = await themeAdd('Neutral', {cwd: tmpDir});- expect(result.data.slug).toBe('neutral');- });-- it('keeps an explicit copy target path', async () => {- const result = await themeAdd('neutral', {- cwd: tmpDir,- targetPath: 'themes/mine',- });- expect(result.data.outputDir).toBe(path.join('themes', 'mine'));- expect(- fs.existsSync(path.join(tmpDir, 'themes', 'mine', result.data.files[0])),- ).toBe(true);- });-- it('keeps unknown-theme errors on the copy path', async () => {- await expect(- themeAdd('does-not-exist', {cwd: tmpDir}),- ).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME'});- });-- it('keeps the copy overwrite guard and explicit replacement', async () => {- await themeAdd('neutral', {cwd: tmpDir});- await expect(themeAdd('neutral', {cwd: tmpDir})).rejects.toMatchObject({- code: 'ERR_FILE_EXISTS',- });- await expect(- themeAdd('neutral', {cwd: tmpDir, overwrite: true}),- ).resolves.toMatchObject({type: 'theme.add'});- });-- it('keeps copy path traversal protection', async () => {- await expect(- themeAdd('neutral', {cwd: tmpDir, targetPath: '../escape'}),- ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});- });-- it('keeps stable write errors when a copy target is a file', async () => {- fs.writeFileSync(path.join(tmpDir, 'blocker'), 'x');- await expect(- themeAdd('neutral', {cwd: tmpDir, targetPath: 'blocker'}),- ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});- });-- it('keeps stable write errors when the default copy ancestor is a file', async () => {- fs.rmSync(path.join(tmpDir, 'src'), {recursive: true, force: true});- fs.writeFileSync(path.join(tmpDir, 'src'), 'x');- await expect(themeAdd('neutral', {cwd: tmpDir})).rejects.toMatchObject({- code: 'ERR_WRITE_FAILED',- });- });-- it('keeps copying into an existing empty target directory', async () => {- fs.mkdirSync(path.join(tmpDir, 'mydir'));- const result = await themeAdd('neutral', {- cwd: tmpDir,- targetPath: 'mydir',- });- expect(result.data.outputDir).toBe('mydir');- });-- it('excludes local themes from the copying lookup', async () => {- installTheme();- const localDir = path.join(tmpDir, 'src', 'themes', 'ocean');- fs.mkdirSync(localDir, {recursive: true});- fs.writeFileSync(- path.join(localDir, 'oceanTheme.doc.mjs'),- "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Local ocean', description: 'Local.', maintained: false};\n",- );- fs.writeFileSync(- path.join(localDir, 'oceanTheme.ts'),- 'export const oceanTheme = {source: "local"};\n',- );-- const result = await themeAdd('ocean', {- cwd: tmpDir,- targetPath: 'src/copied-ocean',- });-- expect(result.type).toBe('theme.add');- expect(result.data.package).toBe('@acme/themes');- expect(- fs.readFileSync(- path.join(tmpDir, 'src', 'copied-ocean', 'oceanTheme.ts'),- 'utf-8',- ),- ).not.toContain('source: "local"');- });-- it.each([- ['a target path', {targetPath: 'src/brand'}],- ['overwrite', {overwrite: true}],- ])('rejects --import with %s before writing', async (_label, copyOption) => {- installTheme();-- await expect(- themeAdd('ocean', {- cwd: tmpDir,- import: true,- package: '@acme/themes',- ...copyOption,- }),- ).rejects.toMatchObject({- code: 'ERR_THEME_INVALID',- message: expect.stringContaining('cannot be combined'),- });- expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(- false,- );- expect(fs.existsSync(path.join(tmpDir, 'src/brand'))).toBe(false);- });-- it('records and imports a built package theme without copying source', async () => {+ it('records and imports a built package theme by default without copying source', async () => {installTheme();const packageBefore = fs.readFileSync(path.join(tmpDir, 'package.json'),@@ -350,7 +133,6 @@ describe('themeAdd', () => {const result = await themeAdd('ocean', {cwd: tmpDir,- import: true,package: '@acme/themes',});@@ -388,11 +170,73 @@ describe('themeAdd', () => {});});+ it('accepts import as a no-op and preserves the same theme.app behavior', async () => {+ installTheme();++ const first = await themeAdd('ocean', {+ cwd: tmpDir,+ import: true,+ package: '@acme/themes',+ });+ expect(first.type).toBe('theme.app');+ expect(first.data.change).toMatchObject({action: 'add', changed: true});++ const moduleFile = path.join(tmpDir, 'src/astryx-themes.ts');+ fs.appendFileSync(moduleFile, '\n// hand edit\n');+ const repeated = await themeAdd('ocean', {+ cwd: tmpDir,+ package: '@acme/themes',+ });++ expect(repeated.type).toBe('theme.app');+ expect(repeated.data.change.changed).toBe(false);+ expect(fs.readFileSync(moduleFile, 'utf-8')).not.toContain('hand edit');+ });++ it.each([+ ['a target path', {targetPath: 'src/brand'}],+ ['overwrite true', {overwrite: true}],+ ])(+ 'rejects removed copy option %s before writing',+ async (_label, copyOption) => {+ installTheme();++ await expect(+ themeAdd('ocean', {+ cwd: tmpDir,+ package: '@acme/themes',+ ...copyOption,+ }),+ ).rejects.toMatchObject({+ code: 'ERR_THEME_INVALID',+ message: expect.stringContaining('themeEject'),+ });+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(+ false,+ );+ expect(fs.existsSync(path.join(tmpDir, 'src/brand'))).toBe(false);+ },+ );++ it('accepts overwrite false as a compatibility no-op', async () => {+ installTheme();++ const result = await themeAdd('ocean', {+ cwd: tmpDir,+ package: '@acme/themes',+ overwrite: false,+ });++ expect(result.type).toBe('theme.app');+ expect(result.data.change).toMatchObject({action: 'add', changed: true});+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, 'src/themes/ocean'))).toBe(false);+ });+it('keeps the released CLI selector while recording the import package', async () => {installBuiltThemePackage('neutral');const result = await themeAdd('neutral', {cwd: tmpDir,- import: true,package: '@astryxdesign/cli',});@@ -415,37 +259,13 @@ describe('themeAdd', () => {});});- it('regenerates an already-added theme and reports no state change', async () => {- installTheme();- await themeAdd('ocean', {- cwd: tmpDir,- import: true,- package: '@acme/themes',- });- const moduleFile = path.join(tmpDir, 'src/astryx-themes.ts');- fs.appendFileSync(moduleFile, '\n// hand edit\n');-- const result = await themeAdd('ocean', {- cwd: tmpDir,- import: true,- package: '@acme/themes',- });-- expect(result.data.change.changed).toBe(false);- expect(fs.readFileSync(moduleFile, 'utf-8')).not.toContain('hand edit');- });-it('fails before writing when the selected module path is authored', async () => {installTheme();const moduleFile = path.join(tmpDir, 'src/astryx-themes.ts');fs.writeFileSync(moduleFile, 'export const mine = true;\n');await expect(- themeAdd('ocean', {- cwd: tmpDir,- import: true,- package: '@acme/themes',- }),+ themeAdd('ocean', {cwd: tmpDir, package: '@acme/themes'}),).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});expect(fs.readFileSync(moduleFile, 'utf-8')).toBe('export const mine = true;\n',@@ -459,7 +279,6 @@ describe('themeAdd', () => {const result = await themeAdd('ocean', {cwd: tmpDir,- import: true,package: '@acme/themes',});@@ -469,11 +288,7 @@ describe('themeAdd', () => {it('prefers a built local theme and switches the recorded owner', async () => {installTheme();- await themeAdd('ocean', {- cwd: tmpDir,- import: true,- package: '@acme/themes',- });+ await themeAdd('ocean', {cwd: tmpDir, package: '@acme/themes'});await themeEject('ocean', {cwd: tmpDir, package: '@acme/themes'});const localDir = path.join(tmpDir, 'src', 'themes', 'ocean');fs.writeFileSync(@@ -482,7 +297,7 @@ describe('themeAdd', () => {);fs.writeFileSync(path.join(localDir, 'ocean.css'), '/* local css */\n');- const result = await themeAdd('ocean', {cwd: tmpDir, import: true});+ const result = await themeAdd('ocean', {cwd: tmpDir});expect(result).toMatchObject({type: 'theme.app',@@ -518,7 +333,6 @@ describe('themeAdd', () => {const result = await themeAdd('ocean', {cwd: tmpDir,- import: true,package: '@acme/themes',});@@ -535,11 +349,7 @@ describe('themeAdd', () => {installTheme('ocean', '@acme/themes', {missingBuilt: true});await expect(- themeAdd('ocean', {- cwd: tmpDir,- import: true,- package: '@acme/themes',- }),+ themeAdd('ocean', {cwd: tmpDir, package: '@acme/themes'}),).rejects.toMatchObject({code: 'ERR_THEME_INVALID',message: expect.stringMatching(diff --git a/packages/cli/api/theme/add/add.types.test.mjs b/packages/cli/api/theme/add/add.types.test.mjsindex 7865592527..8ffac90453 100644--- a/packages/cli/api/theme/add/add.types.test.mjs+++ b/packages/cli/api/theme/add/add.types.test.mjs@@ -124,7 +124,6 @@ describe('generated app-theme module types', () => {await themeAdd('ocean', {cwd: project,- import: true,package: '@acme/themes',});await themeAdd('stone', {cwd: project, import: true});diff --git a/packages/cli/api/theme/eject/eject.copy-compat.test.mjs b/packages/cli/api/theme/eject/eject.copy-compat.test.mjsnew file mode 100644index 0000000000..f8048e2c55--- /dev/null+++ b/packages/cli/api/theme/eject/eject.copy-compat.test.mjs@@ -0,0 +1,168 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Cleanup-stage compatibility: `theme eject` keeps the released copying+ * `theme add` receipt fields, file set, and copied bytes. Its one intentional+ * file-list change moves the unmaintained local descriptor directly behind the+ * entry.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {themeEject} from './eject.mjs';+import {runCli} from '../../../test-utils/run-cli.mjs';++const HEADER = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n';+const RELEASED_COPY_FILES = [+ 'oceanTheme.ts',+ 'fonts/ocean.woff2',+ 'icons.tsx',+ 'oceanTheme.doc.mjs',+ 'tokens/colors.ts',+];+const EJECT_FILES = [+ RELEASED_COPY_FILES[0],+ 'oceanTheme.doc.mjs',+ ...RELEASED_COPY_FILES.slice(1).filter(file => file !== 'oceanTheme.doc.mjs'),+];+const FONT_BYTES = Buffer.concat([+ Buffer.from('wOF2'),+ Buffer.from(Array.from({length: 256}, (_, byte) => byte)),+]);++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeeject-compat-'));+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ dependencies: {'@acme/themes': '^1.0.0'},+ }),+ );+ const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');+ const themeDir = path.join(packageDir, 'themes', 'ocean');+ fs.mkdirSync(path.join(themeDir, 'fonts'), {recursive: true});+ fs.mkdirSync(path.join(themeDir, 'tokens'), {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({name: '@acme/themes', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.doc.mjs'),+ `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */+export default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Integration theme that ships a font.', maintained: true};+`,+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ `${HEADER}export const oceanTheme = {};\n`,+ );+ fs.writeFileSync(+ path.join(themeDir, 'icons.tsx'),+ 'export const oceanIcons = {};\n',+ );+ fs.writeFileSync(path.join(themeDir, 'fonts', 'ocean.woff2'), FONT_BYTES);+ fs.writeFileSync(+ path.join(themeDir, 'tokens', 'colors.ts'),+ "export const oceanBlue = '#0064e0';\n",+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('themeEject released-copy compatibility', () => {+ it('keeps the old copy receipt fields and moves the descriptor to second', async () => {+ const result = await themeEject('ocean', {+ cwd: tmpDir,+ package: '@acme/themes',+ });++ expect(result).toEqual({+ type: 'theme.eject',+ data: {+ slug: 'ocean',+ displayName: 'Ocean',+ maintained: true,+ package: '@acme/themes',+ outputDir: 'src/themes/ocean',+ entry: 'oceanTheme.ts',+ exportName: 'oceanTheme',+ files: EJECT_FILES,+ },+ });+ expect(new Set(result.data.files)).toEqual(new Set(RELEASED_COPY_FILES));+ expect(result.data.files).toEqual(EJECT_FILES);+ expect(Object.keys(result.data)).toEqual([+ 'slug',+ 'displayName',+ 'maintained',+ 'package',+ 'outputDir',+ 'entry',+ 'exportName',+ 'files',+ ]);+ });++ it('keeps copied source and binary bytes, with only the local descriptor change', async () => {+ await themeEject('ocean', {cwd: tmpDir, package: '@acme/themes'});+ const output = path.join(tmpDir, 'src', 'themes', 'ocean');++ expect(fs.readFileSync(path.join(output, 'oceanTheme.ts'), 'utf-8')).toBe(+ 'export const oceanTheme = {};\n',+ );+ expect(+ fs+ .readFileSync(path.join(output, 'fonts/ocean.woff2'))+ .equals(FONT_BYTES),+ ).toBe(true);+ expect(fs.readFileSync(path.join(output, 'icons.tsx'), 'utf-8')).toBe(+ 'export const oceanIcons = {};\n',+ );+ expect(+ fs.readFileSync(path.join(output, 'tokens/colors.ts'), 'utf-8'),+ ).toBe("export const oceanBlue = '#0064e0';\n");+ expect(+ fs.readFileSync(path.join(output, 'oceanTheme.doc.mjs'), 'utf-8'),+ ).toContain('maintained: false');+ });++ it('keeps the same fields and file order in CLI JSON and text', async () => {+ const json = await runCli(+ [+ 'theme',+ 'eject',+ 'ocean',+ 'json-fork',+ '--package',+ '@acme/themes',+ '--json',+ ],+ tmpDir,+ );+ expect(json.status, json.stderr).toBe(0);+ expect(JSON.parse(json.stdout)).toMatchObject({+ type: 'theme.eject',+ data: {outputDir: 'json-fork', files: EJECT_FILES},+ });++ const text = await runCli(+ ['theme', 'eject', 'ocean', 'text-fork', '--package', '@acme/themes'],+ tmpDir,+ );+ expect(text.status, text.stderr).toBe(0);+ const positions = EJECT_FILES.map(file => text.stdout.indexOf(file));+ expect(positions.every(position => position >= 0)).toBe(true);+ expect(positions).toEqual([...positions].sort((a, b) => a - b));+ });+});diff --git a/packages/cli/api/theme/integration-themes.test.mjs b/packages/cli/api/theme/integration-themes.test.mjsindex 42ce0870cb..d7e6fe557f 100644--- a/packages/cli/api/theme/integration-themes.test.mjs+++ b/packages/cli/api/theme/integration-themes.test.mjs@@ -93,7 +93,7 @@ describe('package and integration themes', () => {).toContain('oceanTheme');});- it('copies the complete nested integration theme directory', async () => {+ it('ejects the complete nested integration theme directory', async () => {installThemeIntegration('@acme/themes','ocean',@@ -104,7 +104,7 @@ describe('package and integration themes', () => {},);- const result = await themeAdd('ocean', {cwd: tmpDir});+ const result = await themeEject('ocean', {cwd: tmpDir});expect(result.data.files).toEqual(['oceanTheme.ts',@@ -123,7 +123,7 @@ describe('package and integration themes', () => {path.join(tmpDir, 'src', 'themes', 'ocean', 'oceanTheme.doc.mjs'),'utf-8',),- ).toContain('maintained: true');+ ).toContain('maintained: false');expect(fs.readFileSync(path.join(tmpDir, 'src', 'themes', 'ocean', 'tokens', 'colors.ts'),diff --git a/packages/cli/api/theme/remove/remove.test.mjs b/packages/cli/api/theme/remove/remove.test.mjsindex e00cb005d8..ac348dba47 100644--- a/packages/cli/api/theme/remove/remove.test.mjs+++ b/packages/cli/api/theme/remove/remove.test.mjs@@ -88,7 +88,7 @@ describe('themeRemove', () => {it('names theme add when the slug is not added', async () => {await expect(themeRemove('missing', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME',- message: expect.stringContaining('astryx theme add missing --import'),+ message: expect.stringContaining('astryx theme add missing'),});});});diff --git a/packages/cli/api/theme/template/template.mjs b/packages/cli/api/theme/template/template.mjsindex d11f17294d..9d6bb6b3e1 100644--- a/packages/cli/api/theme/template/template.mjs+++ b/packages/cli/api/theme/template/template.mjs@@ -4,7 +4,7 @@* @file `astryx theme template` leaf — writes the annotated theme template into the* consumer's project.*- * `theme add --import` uses an installed built theme without copying source. This command+ * `theme add` uses an installed built theme without copying source. This command* writes the blank annotated reference for a new theme. `theme eject` is the* separate path for starting from a complete source fork of an existing theme.*diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjsindex b7f2e373e8..b5c91e29f5 100644--- a/packages/cli/api/theme/theme.type.mjs+++ b/packages/cli/api/theme/theme.type.mjs@@ -13,9 +13,8 @@* astryx --json theme build <a> <b> … -> theme.build.batch* astryx --json theme list -> theme.list* astryx --json theme add --list -> theme.list- * astryx --json theme add <slug> -> theme.add- * astryx --json theme add <slug> --import -> theme.app- * astryx --json theme remove/use <slug> -> theme.app+ * astryx --json theme add <slug> [--import] -> theme.app+ * astryx --json theme remove/use <slug> -> theme.app* astryx --json theme eject <slug> -> theme.eject* astryx --json theme template -> theme.template* astryx --json theme targets [filter] -> theme.targets@@ -83,14 +82,6 @@* @property {{unmigratedCopies: ThemeUnmigratedCopy[]}} [meta] descriptor-less released copies that are not listed as themes*/-/**- * astryx --json theme add <slug> [path]- * @typedef {object} ThemeAddResponse- * @property {'theme.add'} type- * @property {{slug: string, displayName: string, maintained: boolean, package: string, outputDir: string, entry: string, exportName: string, files: string[]}} data- * @property {{deprecations: Array<{id: 'DEP-0005', replacements: string[]}>}} meta additive lifecycle guidance; every released data field is unchanged- */-/*** One built theme imported by the generated app module.* @typedef {object} ThemeAppEntry@@ -103,7 +94,7 @@*//**- * astryx --json theme add <slug> --import / remove / use+ * 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`diff --git a/packages/cli/api/theme/themeAdd.doc.mjs b/packages/cli/api/theme/themeAdd.doc.mjsindex b21603dd63..7556e499dc 100644--- a/packages/cli/api/theme/themeAdd.doc.mjs+++ b/packages/cli/api/theme/themeAdd.doc.mjs@@ -9,13 +9,13 @@ export const doc = {name: 'themeAdd',namespace: 'cli/api',displayName: 'themeAdd()',- summary: 'Copy theme source, or import its built output into the app.',+ summary: 'Add a built theme to the app.',description:- 'Copies a bundled or package theme into the project by default, preserving the released theme.add response while that path is deprecated. With options.import, records a package or built local theme and regenerates the app theme module with its built module and stylesheets. Import refuses targetPath and overwrite before writing.',+ 'Records a package or built local theme and regenerates the app theme module with its built module and stylesheets. options.import is an accepted compatibility no-op, as is options.overwrite set to false. Passing targetPath or options.overwrite set to true fails before writing and names themeEject, which owns source copying.',importPath: '@astryxdesign/cli/api',signature:- 'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, import?: boolean, cwd?: string, package?: string}): Promise<ThemeAddResponse | ThemeAppResponse>',- keywords: ['theme', 'add', 'import', 'copy', 'app', 'default', 'local'],+ 'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, import?: boolean, cwd?: string, package?: string}): Promise<ThemeAppResponse>',+ keywords: ['theme', 'add', 'import', 'app', 'default', 'local'],params: [{name: 'slug',@@ -27,28 +27,26 @@ export const doc = {name: 'options.targetPath',type: 'string',description:- 'Destination for the deprecated source-copy path. Cannot be combined with import.',- default: "'src/themes/<slug>'",+ 'Removed copy destination. Passing it throws ERR_THEME_INVALID. Call themeEject instead.',},{name: 'options.overwrite',type: 'boolean',description:- 'Replace copied files instead of refusing. Cannot be combined with import.',+ 'False is a compatibility no-op. True throws ERR_THEME_INVALID. Call themeEject instead.',default: 'false',},{name: 'options.import',type: 'boolean',description:- 'Import the built theme through the generated app module instead of copying source.',+ 'Compatibility no-op; the built theme is added with or without this option.',default: 'false',},{name: 'options.cwd',type: 'string',- description:- 'Project directory used for discovery, state, and target paths.',+ description: 'Project directory used for discovery and app-theme state.',default: 'process.cwd()',},{@@ -58,15 +56,10 @@ export const doc = {},],returns: [- {- type: 'theme.add',- description:- 'The released copy receipt plus additive meta.deprecations with DEP-0005 and its replacement commands when import is false.',- },{type: 'theme.app',description:- '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.',+ 'The complete generated-module state and add change. Its envelope package names the npm package that owns the added theme, except for a local theme.',},],throws: [@@ -77,27 +70,26 @@ export const doc = {{code: 'ERR_AMBIGUOUS_THEME', when: 'more than one package owns the slug'},{code: 'ERR_THEME_INVALID',- when: 'the selected theme is invalid, or import is combined with a copy option',- },- {code: 'ERR_PATH_TRAVERSAL', when: 'a copy target escapes cwd'},- {- code: 'ERR_NO_SOURCE',- when: 'a copied source file is missing',+ when: 'the selected theme is invalid, targetPath is passed, or overwrite is true',},{code: 'ERR_FILE_EXISTS',- when: 'a destination or generated module path conflicts',+ when: 'the generated module path conflicts with an authored file',},- {code: 'ERR_WRITE_FAILED', when: 'copying or module generation fails'},+ {code: 'ERR_WRITE_FAILED', when: 'module generation fails'},],examples: [{- label: 'Import a built theme',- code: "await themeAdd('butter', {import: true});",+ label: 'Add a built theme',+ code: "await themeAdd('butter');",},{label: 'Select a package theme over a local theme',- code: "await themeAdd('ocean', {import: true, package: '@acme/themes'});",+ code: "await themeAdd('ocean', {package: '@acme/themes'});",+ },+ {+ label: 'Keep the earlier opt-in spelling',+ code: "await themeAdd('butter', {import: true});",},],command: 'theme add',diff --git a/packages/cli/api/theme/themeTemplate.doc.mjs b/packages/cli/api/theme/themeTemplate.doc.mjsindex eeccd28313..de19c4852e 100644--- a/packages/cli/api/theme/themeTemplate.doc.mjs+++ b/packages/cli/api/theme/themeTemplate.doc.mjs@@ -19,7 +19,7 @@ export const doc = {'Writes theme.template.ts: the annotated reference for the whole theme surface, covering 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. Use `theme add --import` to ' ++ 'Read it, copy what you need into your own theme file, delete it. Use `theme add` to ' +'use an installed built theme, extend that theme for ordinary customization, or use ' +'`theme eject` for a complete source fork. This command starts a new blank theme. Refuses to overwrite without ' +'`overwrite`, so it is safe to re-run.',diff --git a/packages/cli/api/theme/use/use.test.mjs b/packages/cli/api/theme/use/use.test.mjsindex ce97e73404..c27af6fa7b 100644--- a/packages/cli/api/theme/use/use.test.mjs+++ b/packages/cli/api/theme/use/use.test.mjs@@ -92,7 +92,7 @@ describe('themeUse', () => {it('names theme add when the slug is not added', async () => {await expect(themeUse('missing', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME',- message: expect.stringContaining('astryx theme add missing --import'),+ message: expect.stringContaining('astryx theme add missing'),});});});diff --git a/packages/cli/assets/docs/author-a-theme.doc.mjs b/packages/cli/assets/docs/author-a-theme.doc.mjsindex 0892910afa..808488e1a3 100644--- a/packages/cli/assets/docs/author-a-theme.doc.mjs+++ b/packages/cli/assets/docs/author-a-theme.doc.mjs@@ -15,7 +15,7 @@ export const docs = {title: 'Custom themes',content: [{type: 'prose', text: "Use an installed built theme as the base for ordinary customization. Import it into your source and pass it as `extends` to `defineTheme({extends: importedTheme, ...})`. Build the result, then add the local slug. Only eject when you need to own and maintain a full source fork."},- {type: 'code', lang: 'bash', label: 'Add to use, eject to fork', code: 'astryx theme list\nastryx theme add stone --import\nastryx theme eject stone\nastryx theme build src/themes/stone/stoneTheme.ts\nastryx theme add stone --import'},+ {type: 'code', lang: 'bash', label: 'Add to use, eject to fork', code: 'astryx theme list\nastryx theme add stone\nastryx theme eject stone\nastryx theme build src/themes/stone/stoneTheme.ts\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)."},{type: 'prose', text: 'To apply a theme you created, see {@link generic:use-a-theme}. To generate colors from seed values, see the Palette section below. Use `theme eject` only when you want an independent source fork that no longer receives the package owner\u2019s updates.'},],diff --git a/packages/cli/assets/docs/getting-started.doc.mjs b/packages/cli/assets/docs/getting-started.doc.mjsindex 2721e10795..9f6fd4021d 100644--- a/packages/cli/assets/docs/getting-started.doc.mjs+++ b/packages/cli/assets/docs/getting-started.doc.mjs@@ -31,7 +31,7 @@ export const docs = {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`, install the closest theme package, and run `theme add <slug> --import`; use `--package` when owners share a slug. Import `themes` and `defaultThemeSlug` from the generated module once and pass `themes[defaultThemeSlug]` to `<Theme>`. Customize with `defineTheme({extends: importedTheme, ...})`. Use `theme eject` only when I ask for an independent source fork. Default to neutral if I have no preference, and show me the result before moving on.',+ code: 'Ask me what look and feel this app should have. Run `npx @astryxdesign/cli theme list`, install the closest theme package, and run `theme add <slug>`; use `--package` when owners share a slug. Import `themes` and `defaultThemeSlug` from the generated module once and pass `themes[defaultThemeSlug]` to `<Theme>`. Customize with `defineTheme({extends: importedTheme, ...})`. Use `theme eject` only when I ask for an independent source fork. Default to neutral if I have no preference, and show me the result before moving on.',},],},@@ -69,7 +69,7 @@ export const docs = {content: [{type: 'prose',- text: 'Import the reset and base styles in your global CSS. Then run `astryx theme add neutral --import`; the generated app module imports the theme’s production CSS and font CSS.',+ text: 'Import the reset and base styles in your global CSS. Then run `astryx theme add neutral`; the generated app module imports the theme’s production CSS and font CSS.',},{type: 'code',diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjsindex d85f57bda9..5f48c1491d 100644--- a/packages/cli/assets/docs/theme.doc.dense.mjs+++ b/packages/cli/assets/docs/theme.doc.dense.mjs@@ -32,7 +32,7 @@ export const docsDense = {section: 'Integration themes',title: 'Integration themes',content: [- {type: 'prose', text: 'Install integration, `astryx theme add`. {@link generic:use-a-theme} for full guide.'},+ {type: 'prose', text: 'Install integration. `astryx theme add` imports, and `theme eject` forks source. {@link generic:use-a-theme} for full guide.'},],},],diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjsindex a0825465c2..00b18617f0 100644--- a/packages/cli/assets/docs/theme.doc.mjs+++ b/packages/cli/assets/docs/theme.doc.mjs@@ -39,7 +39,7 @@ export const docs = {type: 'code',lang: 'bash',label: 'Quick start',- code: 'astryx theme add stone --import # use an existing theme\nastryx theme eject stone # fork its source to customize\nastryx theme build src/themes/stone/stoneTheme.ts',+ code: 'astryx theme add stone # use an existing theme\nastryx theme eject stone # fork its source to customize\nastryx theme build src/themes/stone/stoneTheme.ts',},{type: 'prose',@@ -74,7 +74,7 @@ export const docs = {content: [{type: 'prose',- text: 'Install an integration and Astryx discovers its themes automatically. Import one with `astryx theme add <name> --import --package <integration>`. Use `theme eject` only for an independent source fork. For the full walkthrough, see {@link generic:use-a-theme}.',+ text: 'Install an integration and Astryx discovers its themes automatically. Import one with `astryx theme add <name> --package <integration>`. Use `theme eject` only for an independent source fork. For the full walkthrough, see {@link generic:use-a-theme}.',},],},diff --git a/packages/cli/assets/docs/tree/add-a-theme.doc.mjs b/packages/cli/assets/docs/tree/add-a-theme.doc.mjsindex 8e967d02f2..b4c4c0e0cf 100644--- a/packages/cli/assets/docs/tree/add-a-theme.doc.mjs+++ b/packages/cli/assets/docs/tree/add-a-theme.doc.mjs@@ -48,7 +48,7 @@ Declare theme root ./themes in astryx.integration.mjs.},{type: 'prose',- text: 'The source and built outputs ship in your package. Build the source with `theme build`, then run `integration verify` before publishing. An app runs `theme add --import` to record and import the built module and stylesheets; plain `theme add` still copies source while that default is deprecated. See {@link generic:use-a-theme-in-an-app}.',+ text: 'The source and built outputs ship in your package. Build the source with `theme build`, then run `integration verify` before publishing. An app runs `theme add` to record and import the built module and stylesheets; `theme eject` creates an independent source fork. See {@link generic:use-a-theme-in-an-app}.',},],},diff --git a/packages/cli/assets/docs/tree/document-the-theme.doc.mjs b/packages/cli/assets/docs/tree/document-the-theme.doc.mjsindex bbdeac8308..509ba4c1bd 100644--- a/packages/cli/assets/docs/tree/document-the-theme.doc.mjs+++ b/packages/cli/assets/docs/tree/document-the-theme.doc.mjs@@ -41,7 +41,7 @@ export default {content: [{type: 'prose',- text: 'Install @acme/astryx-widgets, then run astryx theme add ocean --import --package @acme/astryx-widgets and apply it from the generated app theme module.',+ text: 'Install @acme/astryx-widgets, then run astryx theme add ocean --package @acme/astryx-widgets and apply it from the generated app theme module.',},],},@@ -50,7 +50,7 @@ export default {},{type: 'prose',- text: 'Keep the section short: how to install the package, run `theme add --import`, apply the generated module ({@link generic:use-a-theme-in-an-app}), and customize with `extends`. When the theme uses a custom font, name the families and the optional exported font stylesheet that `theme add --import` imports ({@link generic:fonts-and-assets}). Extend `theme` rather than a topic another package replaces, or an app that lists that package first drops your section.',+ text: 'Keep the section short: how to install the package, run `theme add`, apply the generated module ({@link generic:use-a-theme-in-an-app}), and customize with `extends`. When the theme uses a custom font, name the families and the optional exported font stylesheet that `theme add` imports ({@link generic:fonts-and-assets}). Extend `theme` rather than a topic another package replaces, or an app that lists that package first drops your section.',},],},diff --git a/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjs b/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjsindex b7d9acbfdb..5c2449b9ae 100644--- a/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjs+++ b/packages/cli/assets/docs/tree/fonts-and-assets.doc.mjs@@ -13,7 +13,7 @@ export const docs = {title: 'Fonts and assets',category: 'guide',description:- 'Name the fonts in the theme, then export an optional font stylesheet that `theme add --import` imports with the built theme.',+ 'Name the fonts in the theme, then export an optional font stylesheet that `theme add` imports with the built theme.',sections: [{id: 'name-the-font',@@ -48,7 +48,7 @@ export const oceanTheme = defineTheme({content: [{type: 'prose',- text: 'Naming a family does not load it. When the theme uses non-system fonts, add `<slug>.fonts.css` beside the built module and production CSS, then export it as `./themes/<slug>.fonts.css`. `theme add --import` imports that stylesheet with the built theme.',+ text: 'Naming a family does not load it. When the theme uses non-system fonts, add `<slug>.fonts.css` beside the built module and production CSS, then export it as `./themes/<slug>.fonts.css`. `theme add` imports that stylesheet with the built theme.',},{type: 'code',@@ -94,7 +94,7 @@ export const oceanTheme = defineTheme({content: [{type: 'prose',- text: 'Before publishing, run `integration verify`. Then install the package in a clean app, run `theme add --import`, apply the generated theme, and open it in a browser. The source, packed exports, and applied result form one chain; check the last step too.',+ text: 'Before publishing, run `integration verify`. Then install the package in a clean app, run `theme add`, apply the generated theme, and open it in a browser. The source, packed exports, and applied result form one chain; check the last step too.',},{type: 'list',diff --git a/packages/cli/assets/docs/tree/themes.doc.mjs b/packages/cli/assets/docs/tree/themes.doc.mjsindex 47e89fa91d..e301f85e69 100644--- a/packages/cli/assets/docs/tree/themes.doc.mjs+++ b/packages/cli/assets/docs/tree/themes.doc.mjs@@ -23,7 +23,7 @@ export const docs = {blocks: [{type: 'prose',- text: 'A theme contribution has editable `defineTheme` source plus a built module and production CSS. `integration add theme` scaffolds the source and declares the package exports; `theme build` writes the built outputs. An app installs the package, runs `theme add --import`, applies the theme from its generated app module, and customizes it with `extends` instead of copying source.',+ text: 'A theme contribution has editable `defineTheme` source plus a built module and production CSS. `integration add theme` scaffolds the source and declares the package exports; `theme build` writes the built outputs. An app installs the package, runs `theme add`, applies the theme from its generated app module, and customizes it with `extends` instead of copying source.',},{type: 'prose',diff --git a/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs b/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjsindex 35b0b69c4c..3fc0e88ecb 100644--- a/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs+++ b/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs@@ -21,12 +21,12 @@ export const docs = {content: [{type: 'prose',- text: 'Install the integration, then run `theme add --import` with its slug and package. The command records the package owner and regenerates one app theme module that imports the built theme, production CSS, and optional font CSS. Plain `theme add` still copies source while that default is deprecated.',+ text: 'Install the integration, then run `theme add` with its slug and package. The command records the package owner and regenerates one app theme module that imports the built theme, production CSS, and optional font CSS. Use `theme eject` only to copy source into an independent local fork.',},{type: 'code',lang: 'bash',- code: 'npm install @acme/astryx-widgets\nnpx astryx theme add ocean --import --package @acme/astryx-widgets',+ code: 'npm install @acme/astryx-widgets\nnpx astryx theme add ocean --package @acme/astryx-widgets',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/versioning.doc.mjs b/packages/cli/assets/docs/tree/versioning.doc.mjsindex 253f72c00d..3513a9c341 100644--- a/packages/cli/assets/docs/tree/versioning.doc.mjs+++ b/packages/cli/assets/docs/tree/versioning.doc.mjs@@ -60,10 +60,7 @@ export const docs = {'A template id, such as `acme-dashboard`','`npx astryx template acme-dashboard`',],- [- 'A theme slug, such as `ocean`',- '`npx astryx theme add ocean --import`',- ],+ ['A theme slug, such as `ocean`', '`npx astryx theme add ocean`'],['A topic name or route, such as `acme/deploying`','Reads of the old name, and links to it from other docs',diff --git a/packages/cli/assets/docs/use-a-theme.doc.mjs b/packages/cli/assets/docs/use-a-theme.doc.mjsindex 6563319448..6d5d48e583 100644--- a/packages/cli/assets/docs/use-a-theme.doc.mjs+++ b/packages/cli/assets/docs/use-a-theme.doc.mjs@@ -19,7 +19,7 @@ export const docs = {type: 'code',lang: 'bash',label: 'Install and add a theme',- code: 'npm install @astryxdesign/theme-neutral\nastryx theme add neutral --import',+ code: 'npm install @astryxdesign/theme-neutral\nastryx theme add neutral',},{type: 'code',@@ -35,7 +35,7 @@ export const docs = {},{type: 'prose',- text: '`theme add --import` records an installed package theme and regenerates `src/astryx-themes.ts` or `.js` with its built module, production CSS, and optional font CSS. In a project without `src`, the module is at the project root. The first imported theme becomes the default. `theme use <slug>` changes that default, and `theme remove <slug>` removes a non-default theme.',+ text: '`theme add` records an installed package theme and regenerates `src/astryx-themes.ts` or `.js` with its built module, production CSS, and optional font CSS. In a project without `src`, the module is at the project root. The first imported theme becomes the default. `theme use <slug>` changes that default, and `theme remove <slug>` removes a non-default theme.',},{type: 'prose',@@ -58,11 +58,11 @@ export const docs = {},{type: 'prose',- text: 'Before the upgrade runs, theme commands skip a descriptor-less copy in `src/themes`. `theme list` and doctor name it as unmigrated and show the upgrade command. A script that meant to copy source now runs `theme eject` with the same arguments. A script that meant to make the app use a theme runs `theme add --import`.',+ text: 'Before the upgrade runs, theme commands skip a descriptor-less copy in `src/themes`. `theme list` and doctor name it as unmigrated and show the upgrade command. A script that meant to copy source now runs `theme eject` with the same arguments. A script that meant to make the app use a theme runs `theme add`.',},{type: 'prose',- text: '`ASTRYX_THEME` is no longer read. Run `theme add <slug> --import` and `theme use <slug>` to choose the default in a generated app theme module. When that module exists, component metadata reads its recorded default theme. Without the module, the released `package.json#astryx.theme` lookup keeps its meaning.',+ text: '`ASTRYX_THEME` is no longer read. Run `theme add <slug>` and `theme use <slug>` to choose the default in a generated app theme module. When that module exists, component metadata reads its recorded default theme. Without the module, the released `package.json#astryx.theme` lookup keeps its meaning.',},],},@@ -71,24 +71,24 @@ export const docs = {content: [{type: 'prose',- text: 'Install the theme package you want with `npm install @astryxdesign/theme-{name}`, then import its slug with `theme add <slug> --import`. The CLI imports the package\'s built outputs for you.',+ text: 'Install the theme package you want with `npm install @astryxdesign/theme-{name}`, then import its slug with `theme add <slug>`. The CLI imports the package\'s built outputs for you.',},{type: 'table',headers: ['Theme', 'Add command', 'Description'],rows: [- ['Neutral', 'astryx theme add neutral --import', 'Muted, minimal aesthetic with Figtree typography. A good starting point.'],- ['Butter', 'astryx theme add butter --import', 'Golden, buttery surfaces with blue accents; Sarina + Outfit type.'],- ['Chocolate', 'astryx theme add chocolate --import', 'Warm brown tones and cozy beige; Fraunces + Albert Sans type.'],- ['Gothic', 'astryx theme add gothic --import', 'Dark-only atmospheric theme; deep blue-gray surfaces, distressed display type.'],- ['Matcha', 'astryx theme add matcha --import', 'Earthy greens; DM Sans + Playwrite US Trad type.'],- ['Stone', 'astryx theme add stone --import', 'Warm stone and slate tones; Montserrat + Figtree type.'],- ['Y2K', 'astryx theme add y2k --import', 'Playful Y2K pop; periwinkle body, holographic accents, Poppins + Crimson Text.'],+ ['Neutral', 'astryx theme add neutral', 'Muted, minimal aesthetic with Figtree typography. A good starting point.'],+ ['Butter', 'astryx theme add butter', 'Golden, buttery surfaces with blue accents; Sarina + Outfit type.'],+ ['Chocolate', 'astryx theme add chocolate', 'Warm brown tones and cozy beige; Fraunces + Albert Sans type.'],+ ['Gothic', 'astryx theme add gothic', 'Dark-only atmospheric theme; deep blue-gray surfaces, distressed display type.'],+ ['Matcha', 'astryx theme add matcha', 'Earthy greens; DM Sans + Playwrite US Trad type.'],+ ['Stone', 'astryx theme add stone', 'Warm stone and slate tones; Montserrat + Figtree type.'],+ ['Y2K', 'astryx theme add y2k', 'Playful Y2K pop; periwinkle body, holographic accents, Poppins + Crimson Text.'],],},{type: 'prose',- text: 'Every first-party package exports its built theme at `@astryxdesign/theme-{name}/built`, production CSS at `/theme.css`, and font loading CSS at `/fonts.css`. `theme add --import` writes those imports into the generated app module.',+ text: 'Every first-party package exports its built theme at `@astryxdesign/theme-{name}/built`, production CSS at `/theme.css`, and font loading CSS at `/fonts.css`. `theme add` writes those imports into the generated app module.',},],},@@ -113,11 +113,11 @@ export const docs = {type: 'code',lang: 'bash',label: 'Install, inspect, and add',- code: 'npm install @astryxdesign/core @acme/brand-integration\nastryx theme list --package @acme/brand-integration\nastryx docs brand-theme\nastryx theme add ocean --import --package @acme/brand-integration',+ code: 'npm install @astryxdesign/core @acme/brand-integration\nastryx theme list --package @acme/brand-integration\nastryx docs brand-theme\nastryx theme add ocean --package @acme/brand-integration',},{type: 'prose',- text: '`theme add --import` keeps the owner package in the app record and imports its built module, stylesheet, and optional font stylesheet. Package updates continue to reach the app. Run `theme eject ocean --package @acme/brand-integration` only to copy the source and descriptor into `src/themes/ocean` as an independent local fork.',+ text: '`theme add` keeps the owner package in the app record and imports its built module, stylesheet, and optional font stylesheet. Package updates continue to reach the app. Run `theme eject ocean --package @acme/brand-integration` only to copy the source and descriptor into `src/themes/ocean` as an independent local fork.',},],},@@ -186,7 +186,7 @@ export const docs = {type: 'list',style: 'do',items: [- 'Use `theme add --import` for production apps; it wires the built module and CSS.',+ 'Use `theme add` for production apps; it wires the built module and CSS.','Import `themes` and `defaultThemeSlug` from the generated module once, and keep that wiring in development too.','While you edit a local theme, run `astryx theme build --watch` so its built files stay current.','Run `astryx theme build` for custom themes to get the built artifacts.',diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex 232b257a84..daeab211d4 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -58,7 +58,7 @@ export const doc = {name: 'themes',type: 'string',description:- 'The folder that holds your themes, relative to package.json, with one folder per theme. Each theme folder has the theme source and a matching .doc.mjs file with the same name. Installed themes show up in `astryx theme list`; `theme add --import` imports their built package exports, and `theme eject` creates an editable local fork.',+ 'The folder that holds your themes, relative to package.json, with one folder per theme. Each theme folder has the theme source and a matching .doc.mjs file with the same name. Installed themes show up in `astryx theme list`; `theme add` imports their built package exports, and `theme eject` creates an editable local fork.',example: "'./themes'",},{diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex 8ee87bb24d..85ca478235 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -62,7 +62,6 @@ import {themePaletteGenerate,} from '../../../api/theme/palette/generate/generate.mjs';import {- importSpecifier,printBatchTrailer,printCompactTrailer,themeBuild,@@ -230,8 +229,8 @@ async function warnOnThemeIntegrationIssues(json) {}/**- * Print `theme add --list`. Its JSON stays the released `theme.list`; its text- * names the commands of the current lifecycle stage (AST-050 FR12).+ * Print cleanup-stage `theme add --list`. Its JSON stays the released+ * `theme.list`; its text names the cleanup commands (AST-050 FR12).* @param {import('../../../api/theme/theme.type.mjs').ThemeListEntry[]} themes*/function printThemeAddList(themes) {@@ -255,7 +254,7 @@ function printThemeAddList(themes) {}),),text(- `Import one: ${run} theme add <slug> --import [--package <package>]\n` ++ `Import one: ${run} theme add <slug> [--package <package>]\n` +`Fork source: ${run} theme eject <slug> [target-path]`,),more,@@ -297,7 +296,7 @@ function printThemeList(themes, unmigratedCopies = []) {},}),text(- `Import one: ${run} theme add <slug> --import [--package <package>]\n` ++ `Import one: ${run} theme add <slug> [--package <package>]\n` +`Fork source: ${run} theme eject <slug> [target-path]`,),more,@@ -801,15 +800,14 @@ export function registerTheme(program) {},});- defineCommand(theme, themeAddCommand, {+ const themeAddCli = defineCommand(theme, themeAddCommand, {fn: themeAddFn,action: async (/** @type {string | undefined} */ slug,- /** @type {string | undefined} */ targetPath,- /** @type {{list?: boolean, overwrite?: boolean, import?: boolean, package?: string}} */ options,+ /** @type {{list?: boolean, import?: boolean, package?: string}} */ options,) => {const json = program.opts().json || false;- /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAddResponse | import('../../../api/theme/theme.type.mjs').ThemeAppResponse} */+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAppResponse} */let result;try {result =@@ -819,8 +817,6 @@ export function registerTheme(program) {package: options.package,}): await themeAdd(slug, {- targetPath,- overwrite: options.overwrite,import: options.import,cwd: process.cwd(),package: options.package,@@ -848,44 +844,12 @@ export function registerTheme(program) {printThemeAddList(result.data);return answered;}- if (result.type === 'theme.app') {- printThemeApp(result);- return answered;- }-- const {- displayName,- outputDir,- entry,- exportName,- files,- package: owner,- } = result.data;- const entryModule = importSpecifier(- outputDir,- entry.replace(/\.tsx?$/, ''),- );- emit(- text(`[ok] Added ${displayName} theme from ${owner} to ${outputDir}/`),- list(files.map(file => `${outputDir}/${file}`)),- text(- 'Use it in your app (import path is relative to a file in src/ — adjust if yours lives elsewhere):',- ),- code(- "import { Theme } from '@astryxdesign/core';\n" +- `import { ${exportName} } from '${entryModule}';\n\n` +- `<Theme theme={${exportName}}>\n <App />\n</Theme>`,- ),- text(- `This is your copy of the ${displayName} theme — edit ${entry} to make it your own.`,- ),- );- console.error(- `Warning: \`theme add\` source copying is deprecated (DEP-0005). Run \`${getCliInvocation()} theme eject ${result.data.slug}\` to fork source or \`${getCliInvocation()} theme add ${result.data.slug} --import\` to use the built theme.`,- );+ printThemeApp(result);return answered;},});+ // Reject the removed target-path argument in Commander's standard parse path.+ themeAddCli.allowExcessArguments(false);defineCommand(theme, themeRemoveCommand, {fn: themeRemoveFn,diff --git a/packages/cli/clients/cli/commands/init.next-steps.test.mjs b/packages/cli/clients/cli/commands/init.next-steps.test.mjsindex 4f91541d1c..52fda243fd 100644--- a/packages/cli/clients/cli/commands/init.next-steps.test.mjs+++ b/packages/cli/clients/cli/commands/init.next-steps.test.mjs@@ -21,7 +21,7 @@ describe('init Next steps theme guidance', () => {it('adds an installed theme through the CLI', () => {expect(text).toContain('npm install @astryxdesign/theme-neutral');- expect(text).toContain('npx astryx theme add neutral --import');+ expect(text).toContain('npx astryx theme add neutral');});it('wires the generated theme record once', () => {diff --git a/packages/cli/clients/cli/commands/search.test.mjs b/packages/cli/clients/cli/commands/search.test.mjsindex e411ad3095..2818537062 100644--- a/packages/cli/clients/cli/commands/search.test.mjs+++ b/packages/cli/clients/cli/commands/search.test.mjs@@ -127,7 +127,7 @@ describe('search() API — filters', () => {expect(data.results.map(r => r.name)).toContain('neutral');for (const r of data.results) {expect(r.domain).toBe('theme');- expect(r.command).toBe(`astryx theme add --import ${r.name}`);+ expect(r.command).toBe(`astryx theme add ${r.name}`);}});diff --git a/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjsindex 7717beab97..5ef5697adf 100644--- a/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs+++ b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/** @file Compatibility and deprecation coverage for the two-step theme-add lifecycle. */+/** @file Compatibility coverage for the cleanup stage of the theme-add lifecycle. */import {afterEach, beforeEach, describe, expect, it} from 'vitest';import * as fs from 'node:fs';@@ -14,9 +14,50 @@ let tmpDir;beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-add-cli-'));fs.mkdirSync(path.join(tmpDir, 'src'));+ fs.writeFileSync(path.join(tmpDir, 'tsconfig.json'), '{}\n');fs.writeFileSync(path.join(tmpDir, 'package.json'),- JSON.stringify({name: 'app', private: true}),+ JSON.stringify({+ name: 'app',+ private: true,+ dependencies: {'@acme/themes': '^1.0.0'},+ }),+ );+ const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');+ const themeDir = path.join(packageDir, 'themes', 'ocean');+ fs.mkdirSync(themeDir, {recursive: true});+ fs.mkdirSync(path.join(packageDir, 'dist'), {recursive: true});+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({+ name: '@acme/themes',+ version: '1.0.0',+ type: 'module',+ exports: {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ },+ }),+ );+ fs.writeFileSync(+ path.join(packageDir, 'astryx.integration.mjs'),+ "export default {themes: './themes'};\n",+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.doc.mjs'),+ "/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {type: 'theme', name: 'ocean', displayName: 'Ocean', description: 'Ocean theme.', maintained: true};\n",+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ 'export const oceanTheme = {};\n',+ );+ fs.writeFileSync(+ path.join(packageDir, 'dist/ocean.js'),+ "export const oceanTheme = {name: 'ocean', __built: true};\n",+ );+ fs.writeFileSync(+ path.join(packageDir, 'dist/ocean.css'),+ '[data-astryx-theme="ocean"] {}\n',);});@@ -24,53 +65,66 @@ afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});-describe('theme add compatibility lifecycle', () => {- it('keeps copy stdout and emits one text-only deprecation warning', async () => {- const result = await runCli(['theme', 'add', 'neutral'], tmpDir);+describe('theme add cleanup lifecycle', () => {+ it('plain theme add imports built output and prints no deprecation warning', async () => {+ const result = await runCli(+ ['theme', 'add', 'ocean', '--package', '@acme/themes'],+ tmpDir,+ );expect(result.status, result.stderr).toBe(0);- expect(result.stdout).toContain(- '[ok] Added Neutral theme from @astryxdesign/cli to src/themes/neutral/',- );- expect(result.stdout).toContain('This is your copy of the Neutral theme');- expect(result.stderr.match(/source copying is deprecated/g)).toHaveLength(- 1,- );- // The app has no CLI installed, so the commands name the scoped package.- const run = getCliInvocation(tmpDir);- expect(run).toMatch(/ @astryxdesign\/cli$/);- expect(result.stderr).toContain(`${run} theme eject neutral`);- expect(result.stderr).toContain(`${run} theme add neutral --import`);- expect(fs.existsSync(path.join(tmpDir, 'src/themes/neutral'))).toBe(true);- expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(- false,- );+ expect(result.stdout).toMatch(/^owner:\s+@acme\/themes$/m);+ expect(result.stdout).toMatch(/^module:\s+@acme\/themes\/themes\/ocean$/m);+ expect(result.stdout).toMatch(/^action:\s+add$/m);+ expect(result.stderr).not.toContain('DEP-0005');+ expect(result.stderr).not.toContain('deprecated');+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, 'src/themes/ocean'))).toBe(false);});- it('keeps theme.add data and adds machine-readable deprecation metadata', async () => {- const result = await runCli(['theme', 'add', 'neutral', '--json'], tmpDir);+ it('plain theme add returns theme.app with no deprecation metadata', async () => {+ const result = await runCli(+ ['theme', 'add', 'ocean', '--package', '@acme/themes', '--json'],+ tmpDir,+ );expect(result.status, result.stderr).toBe(0);- expect(result.stderr).not.toContain('source copying is deprecated');- expect(JSON.parse(result.stdout)).toMatchObject({- type: 'theme.add',+ expect(result.stderr).toBe('');+ const payload = JSON.parse(result.stdout);+ expect(payload).toMatchObject({+ type: 'theme.app',data: {- slug: 'neutral',- package: '@astryxdesign/cli',- outputDir: 'src/themes/neutral',- },- meta: {- deprecations: [- {- id: 'DEP-0005',- replacements: ['theme eject', 'theme add --import'],- },- ],+ default: 'ocean',+ modulePath: 'src/astryx-themes.ts',+ change: {action: 'add', slug: 'ocean', changed: true},},});+ expect(payload.meta).toBeUndefined();+ });++ it('keeps --import as an accepted no-op with the same response', async () => {+ const result = await runCli(+ [+ 'theme',+ 'add',+ 'ocean',+ '--import',+ '--package',+ '@acme/themes',+ '--json',+ ],+ tmpDir,+ );++ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toMatchObject({+ type: 'theme.app',+ data: {default: 'ocean', change: {action: 'add', slug: 'ocean'}},+ });+ expect(fs.existsSync(path.join(tmpDir, 'src/themes/ocean'))).toBe(false);});- it('keeps the list JSON unchanged and names the stage commands in text', async () => {+ it('keeps list JSON byte-compatible and names cleanup commands in text', async () => {fs.mkdirSync(path.join(tmpDir, 'src/themes/broken'), {recursive: true});fs.writeFileSync(path.join(tmpDir, 'src/themes/broken/brokenTheme.ts'),@@ -81,16 +135,19 @@ describe('theme add compatibility lifecycle', () => {expect(textResult.status, textResult.stderr).toBe(0);const run = getCliInvocation(tmpDir);expect(textResult.stdout).toContain(- `Import one: ${run} theme add <slug> --import [--package <package>]`,+ `Import one: ${run} theme add <slug> [--package <package>]`,);expect(textResult.stdout).toContain(`Fork source: ${run} theme eject <slug> [target-path]`,);+ expect(textResult.stdout).toMatch(+ /More themes in packages you could add: .*discover theme$/m,+ );expect(textResult.stdout).not.toContain('theme add <slug> [target-path]');+ expect(textResult.stdout).not.toContain('theme add <slug> --import');expect(textResult.stderr).not.toContain('deprecated');const result = await runCli(['theme', 'add', '--list', '--json'], tmpDir);-expect(result.status, result.stderr).toBe(0);const payload = JSON.parse(result.stdout);expect(payload).toMatchObject({type: 'theme.list'});@@ -107,29 +164,65 @@ describe('theme add compatibility lifecycle', () => {});it.each([- ['target path', ['src/brand']],- ['overwrite', ['--overwrite']],- ])('rejects --import with a %s before writing', async (_label, extra) => {+ ['target path', ['src/brand'], 'ERR_INVALID_ARGUMENT'],+ ['overwrite', ['--overwrite'], 'ERR_INVALID_OPTION'],+ [+ 'target path with --import',+ ['--import', 'src/brand'],+ 'ERR_INVALID_ARGUMENT',+ ],+ [+ 'overwrite with --import',+ ['--import', '--overwrite'],+ 'ERR_INVALID_OPTION',+ ],+ ])(+ 'rejects removed %s before writing with the standard parser code',+ async (_label, extra, code) => {+ const result = await runCli(+ [+ 'theme',+ 'add',+ 'ocean',+ ...extra,+ '--package',+ '@acme/themes',+ '--json',+ ],+ tmpDir,+ );++ expect(result.status).toBe(1);+ expect(JSON.parse(result.stdout)).toMatchObject({code});+ expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(+ false,+ );+ expect(fs.existsSync(path.join(tmpDir, 'src/brand'))).toBe(false);+ },+ );++ it('rejects --overwrite without a slug as an invalid option', async () => {const result = await runCli(- ['theme', 'add', 'neutral', '--import', ...extra, '--json'],+ ['theme', 'add', '--overwrite', '--json'],tmpDir,);- expect(result.status).not.toBe(0);+ expect(result.status).toBe(1);expect(JSON.parse(result.stdout)).toMatchObject({- code: 'ERR_THEME_INVALID',- error: expect.stringContaining('cannot be combined'),+ code: 'ERR_INVALID_OPTION',});expect(fs.existsSync(path.join(tmpDir, 'src/astryx-themes.ts'))).toBe(false,);- expect(fs.existsSync(path.join(tmpDir, 'src/brand'))).toBe(false);});- it('lists --import in help', async () => {+ it('shows --import and the visible eject replacement without a hidden option', async () => {const result = await runCli(['theme', 'add', '--help'], tmpDir);expect(result.status, result.stderr).toBe(0);expect(result.stdout).toContain('--import');+ expect(result.stdout).toMatch(/compatibility no-op/i);+ expect(result.stdout).toContain('theme eject <slug> [path] [--overwrite]');+ expect(result.stdout).not.toMatch(/^\s+-f, --overwrite/m);});});diff --git a/packages/cli/clients/cli/commands/theme-add.doc.mjs b/packages/cli/clients/cli/commands/theme-add.doc.mjsindex 97ddeb30cc..0477a77b59 100644--- a/packages/cli/clients/cli/commands/theme-add.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-add.doc.mjs@@ -8,26 +8,19 @@ export const doc = {name: 'theme add',displayName: 'astryx theme add',namespace: 'cli/commands',- summary: 'Copy a theme, or import its built output into the app',+ summary:+ "Add a built theme to the app. To copy a theme's source as an editable fork, run `theme eject <slug> [path] [--overwrite]`.",description:- 'With --import, records the theme in the generated app module and imports its built module and stylesheets. Without --import, keeps the released source-copy behavior, emits one text warning, and adds meta.deprecations with DEP-0005 and the theme eject/theme add --import replacements to JSON. A bare command or --list delegates to themeListCopySources() so the released list fields stay unchanged; use --package when owners share a slug.',+ "Records the theme in the generated app module and imports its built module and stylesheets. --import remains accepted as a compatibility no-op. To copy a theme's source as an editable fork, run `theme eject <slug> [path] [--overwrite]`. A bare command or --list delegates to themeListCopySources(), whose released JSON bytes stay unchanged while its text names the current add and eject commands; use --package when owners share a slug.",fn: 'themeAdd',- args: [- {name: 'slug', param: 'slug', required: false},- {name: 'path', param: 'options.targetPath', required: false},- ],+ args: [{name: 'slug', param: 'slug', required: false}],options: [- {- flag: '-f, --overwrite',- param: 'options.overwrite',- description: 'Replace copied files. Cannot be combined with --import',- },{flag: '--list', description: 'List available themes'},{flag: '--import',param: 'options.import',description:- 'Use the built theme through the generated app module instead of copying source',+ 'Compatibility no-op; the built theme is added with or without this flag',},{flag: '--package <package>',@@ -37,19 +30,19 @@ export const doc = {],examples: [{- label: 'Import a built theme into the app',- cli: 'astryx theme add ocean --import',+ label: 'Add a built theme to the app',+ cli: 'astryx theme add ocean',},{label: 'Select a package theme over a local theme',- cli: 'astryx theme add ocean --import --package @acme/themes',+ cli: 'astryx theme add ocean --package @acme/themes',},],exitCodes: [- {code: 0, when: 'the theme is listed, copied, or imported'},+ {code: 0, when: 'the theme is listed or added'},{code: 1,- when: 'the theme, its source or built imports, its record, the target path, or the option combination is invalid',+ when: 'the theme, its built imports, its record, or the option combination is invalid',},],related: ['theme list', 'theme remove', 'theme use', 'theme eject'],diff --git a/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjsindex 1815b72cfd..7d2550970e 100644--- a/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs+++ b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs@@ -29,7 +29,8 @@ describe('astryx theme list', () => {expect(status).toBe(0);expect(stdout).toMatch(/^slug:\s+neutral$/m);expect(stdout).toMatch(/^package:\s+@astryxdesign\/cli$/m);- expect(stdout).toMatch(/Import one: .*theme add <slug> --import/m);+ expect(stdout).toMatch(/Import one: .*theme add <slug>/m);+ expect(stdout).not.toContain('theme add <slug> --import');expect(stdout).toMatch(/Fork source: .*theme eject <slug>/m);expect(stdout).toMatch(/More themes in packages you could add: .*discover theme$/m);});diff --git a/packages/cli/clients/cli/commands/theme-template.doc.mjs b/packages/cli/clients/cli/commands/theme-template.doc.mjsindex 8e9a39877c..1db55f23cb 100644--- a/packages/cli/clients/cli/commands/theme-template.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-template.doc.mjs@@ -19,7 +19,7 @@ export const doc = {'Writes theme.template.ts: the annotated reference for the whole theme surface, covering 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> --import` to ' ++ 'it, copy what you need into your own theme file, delete it. Use `theme add <slug>` to ' +'use an installed built theme, extend that theme for ordinary customization, or use ' +'`theme eject <slug>` for a complete source fork. Leaves an existing file untouched unless --overwrite.',fn: 'themeTemplate',diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjsindex 833c1f035c..29f7197359 100644--- a/packages/cli/clients/cli/commands/theme.doc.mjs+++ b/packages/cli/clients/cli/commands/theme.doc.mjs@@ -13,7 +13,7 @@ export const doc = {namespace: 'cli/commands',summary: 'Add, switch, build, and author themes',description:- 'The theme command group. Import built themes into an app, choose its default, remove them, list available and added themes, or eject source to make a local fork. Plain theme add still copies source while that default is deprecated. The authoring commands build themes, generate palettes, write the annotated template, and list component theme targets.',+ 'The theme command group. Add built themes to an app, choose its default, remove them, list available and added themes, or eject source to make a local fork. The authoring commands build themes, generate palettes, write the annotated template, and list component theme targets.',subcommands: ['build','list',@@ -27,7 +27,7 @@ export const doc = {],examples: [{label: 'List available and added themes', cli: 'astryx theme list'},- {label: 'Import a theme into the app', cli: 'astryx theme add ocean --import'},+ {label: 'Import a theme into the app', cli: 'astryx theme add ocean'},{label: 'Choose the default', cli: 'astryx theme use ocean'},{label: 'Fork source to customize', cli: 'astryx theme eject ocean'},{diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex 5ca6f4fbe4..52a889fcb7 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -458,7 +458,7 @@ export function generateCompressedIndex(} else {lines.push("- Style with component props first, then tokens (var(--color-*|--spacing-*|--radius-*)). No raw hex/px. No StyleX/Tailwind compiler here — don't use xstyle/utility classes directly. Some templates use StyleX and need a compiler plugin; see `astryx docs styling-overview`.");}- lines.push('- Palettes and custom colors go through the theme, never :root overrides. See `astryx docs theme`.');+ lines.push('- Palettes and custom colors go through the theme, never :root overrides. Run `astryx theme add <slug>` to import; `theme eject <slug>` only forks source. See `astryx docs theme`.');// 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/agent-docs/app-theme-workflow.test.mjs b/packages/cli/foundation/agent-docs/app-theme-workflow.test.mjsindex 610cbc1090..94802560f5 100644--- a/packages/cli/foundation/agent-docs/app-theme-workflow.test.mjs+++ b/packages/cli/foundation/agent-docs/app-theme-workflow.test.mjs@@ -9,5 +9,8 @@ describe('generated agent docs app-theme workflow', () => {expect(result).toContain('astryx docs theme');expect(result).toContain('never :root overrides');+ expect(result).toContain('theme add <slug>');+ expect(result).toContain('theme eject <slug>');+ expect(result).not.toContain('theme add <slug> --import');});});diff --git a/packages/cli/foundation/config/theme-state.mjs b/packages/cli/foundation/config/theme-state.mjsindex 75d19eea5c..b8125165ff 100644--- a/packages/cli/foundation/config/theme-state.mjs+++ b/packages/cli/foundation/config/theme-state.mjs@@ -106,7 +106,7 @@ export function themeModuleCandidates(projectDir) {function validThemeRecord(value, label) {if (!isRecord(value) || !isRecord(value.themes)) {throw new ThemeStateError(- `${label} must carry a static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug> --import\`.`,+ `${label} must carry a static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug>\`.`,);}const keys = Object.keys(value);@@ -159,7 +159,7 @@ export function parseThemeModuleRecord(source, label = 'theme module') {.filter(line => /^\s*\*\s*@astryx-theme-record\s+/u.test(line));if (recordLines.length !== 1) {throw new ThemeStateError(- `${label} must carry exactly one static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug> --import\`.`,+ `${label} must carry exactly one static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug>\`.`,);}const payload = recordLines[0].replace(@@ -318,7 +318,7 @@ export function readThemeState(cwd = process.cwd()) {export function renderThemeModule(themes, defaultSlug, typescript) {if (!themes.some(theme => theme.slug === defaultSlug)) {throw new ThemeStateError(- `Default theme "${defaultSlug}" is not added. Run \`astryx theme add ${defaultSlug} --import\` first.`,+ `Default theme "${defaultSlug}" is not added. Run \`astryx theme add ${defaultSlug}\` first.`,);}/** @type {string[]} */diff --git a/packages/cli/foundation/discovery/theme-imports.mjs b/packages/cli/foundation/discovery/theme-imports.mjsindex 6bdada88ea..607cab958d 100644--- a/packages/cli/foundation/discovery/theme-imports.mjs+++ b/packages/cli/foundation/discovery/theme-imports.mjs@@ -130,7 +130,7 @@ function resolvePackageTheme(theme, cwd, ownerThemeCount) {findInstalledPackage(cwd, importPackage);if (!packageDir) {throw new ThemeImportError(- `Theme package "${importPackage}" is not installed. Run \`npm install ${importPackage}\` (or yarn/pnpm/bun), then run \`astryx theme add ${theme.slug} --import\`.`,+ `Theme package "${importPackage}" is not installed. Run \`npm install ${importPackage}\` (or yarn/pnpm/bun), then run \`astryx theme add ${theme.slug}\`.`,);}const pkg = readPackage(path.join(packageDir, 'package.json'));diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex e8d9edf76d..5e8740c766 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -243,11 +243,6 @@ export const doc = {description:'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.',},- {- value: 'theme.add',- description:- '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.',- },{value: 'theme.app',description:diff --git a/packages/cli/test/__golden__/search.json b/packages/cli/test/__golden__/search.jsonindex 674f246bdd..4dda24f4ce 100644--- a/packages/cli/test/__golden__/search.json+++ b/packages/cli/test/__golden__/search.json@@ -45,7 +45,7 @@"reason": "description mentions \"zorblax\"","description": "A zorblax blue.","displayName": "Ocean",- "command": "astryx theme add --import ocean"+ "command": "astryx theme add ocean"}]}diff --git a/packages/cli/test/__golden__/theme-add-list.json b/packages/cli/test/__golden__/theme-add-list.jsonnew file mode 100644index 0000000000..7fc58a5c39--- /dev/null+++ b/packages/cli/test/__golden__/theme-add-list.json@@ -0,0 +1,62 @@+{+ "apiVersion": 1,+ "type": "theme.list",+ "data": [+ {+ "slug": "butter",+ "displayName": "Butter",+ "description": "Warm, creamy yellows with a friendly blue accent. Playful enough for consumer surfaces, soft enough to stay readable.",+ "maintained": false,+ "package": "@astryxdesign/cli"+ },+ {+ "slug": "chocolate",+ "displayName": "Chocolate",+ "description": "Warm chocolate theme for Astryx — rich brown palette with Fraunces headings, Albert Sans body, and Lucide icons",+ "maintained": false,+ "package": "@astryxdesign/cli"+ },+ {+ "slug": "gothic",+ "displayName": "Gothic",+ "description": "Deep blue-grays and a signature display serif. Dramatic and editorial, for surfaces that want to be remembered.",+ "maintained": false,+ "package": "@astryxdesign/cli"+ },+ {+ "slug": "matcha",+ "displayName": "Matcha",+ "description": "Earthy greens with a calm, organic feel. Naturalistic and grounded, great for wellness or content-first apps.",+ "maintained": false,+ "package": "@astryxdesign/cli"+ },+ {+ "slug": "neutral",+ "displayName": "Neutral",+ "description": "Restrained warm grays. Minimal and quiet, so the content stays the focus.",+ "maintained": true,+ "package": "@astryxdesign/cli"+ },+ {+ "slug": "stone",+ "displayName": "Stone",+ "description": "Warm stone and slate, earthy and understated, with just enough character to feel handcrafted.",+ "maintained": false,+ "package": "@astryxdesign/cli"+ },+ {+ "slug": "y2k",+ "displayName": "Y2K",+ "description": "Hot pinks, lime greens, and Poppins. Bubbly, playful, and unmistakably retro.",+ "maintained": false,+ "package": "@astryxdesign/cli"+ },+ {+ "slug": "ocean",+ "displayName": "Ocean",+ "description": "A zorblax blue.",+ "maintained": true,+ "package": "@acme/kit"+ }+ ]+}diff --git a/packages/cli/test/golden-reads.test.mjs b/packages/cli/test/golden-reads.test.mjsindex 023467ddb5..8fb762c52e 100644--- a/packages/cli/test/golden-reads.test.mjs+++ b/packages/cli/test/golden-reads.test.mjs@@ -169,6 +169,7 @@ describe('golden reads of integration docs', () => {['docs-index.txt', ['docs', 'acme-guide', '--index']],['docs-section.json', ['docs', 'acme-guide', 'colors', '--json']],['search.json', ['search', 'zorblax', '--json']],+ ['theme-add-list.json', ['theme', 'add', '--list', '--json']],])('%s', async (name, args) => {await expect(astryx(args)).toMatchFileSnapshot(path.join(GOLDEN, name));});diff --git a/packages/cli/test/inv28-package-provenance.test.mjs b/packages/cli/test/inv28-package-provenance.test.mjsindex 4c48314fe7..d920bdd021 100644--- a/packages/cli/test/inv28-package-provenance.test.mjs+++ b/packages/cli/test/inv28-package-provenance.test.mjs@@ -217,7 +217,7 @@ describe('INV28: text names the same package', () => {});});-describe('INV28: theme add --import names the package that owns the added theme', () => {+describe('INV28: theme add names the package that owns the added theme', () => {const THEMES = '@acme/themes';/** @type {string[]} */const dirs = [];@@ -296,6 +296,24 @@ describe('INV28: theme add --import names the package that owns the added theme'}});+ it('plain theme add names the package directly after type', async () => {+ const dir = appWithThemePackage();+ const {status, stdout, stderr} = await runCli(+ ['theme', 'add', 'ocean', '--package', THEMES, '--json'],+ 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',+ ]);+ });+it('theme.app names the package directly after type, and text names it', async () => {const dir = appWithThemePackage();const {status, stdout, stderr} = await runCli(diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjsindex 4ef9072ae5..6be5d9ae76 100644--- a/scripts/check-cli-structure.mjs+++ b/scripts/check-cli-structure.mjs@@ -461,7 +461,6 @@ const INV21_KNOWN_GAPS = new Map([['template/show/show.mjs', new Set(['fs', 'discovery'])],['template/skeleton/skeleton.mjs', new Set(['fs', 'discovery'])],['template/template.mjs', new Set(['discovery'])],- ['theme/add/add.mjs', new Set(['fs'])],['theme/build/build.mjs', new Set(['fs', 'discovery'])],['theme/palette/generate/generate.mjs', new Set(['fs'])],['theme/targets/targets.mjs', new Set(['discovery'])],