@astryxdesign/cli 0.6.5-canary.a477e48 → 0.6.5-canary.a8b2251

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,8 +10,10 @@
10
10
  */
11
11
 
12
12
  import * as fs from 'node:fs';
13
+ import {isBuiltin} from 'node:module';
13
14
  import * as path from 'node:path';
14
15
  import {AstryxError} from '../error.mjs';
16
+ import {CLI_ROOT} from '../../foundation/fs/paths.mjs';
15
17
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
16
18
  import {
17
19
  assertWithin,
@@ -21,6 +23,7 @@ import {
21
23
  import {
22
24
  discoverBundledThemes,
23
25
  discoverThemeDirectory,
26
+ themeFileImports,
24
27
  } from '../../foundation/discovery/theme-discovery.mjs';
25
28
  import {
26
29
  findLocalIntegrationManifestOrNull,
@@ -214,6 +217,77 @@ function escapeRegExp(s) {
214
217
  return s.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
215
218
  }
216
219
 
220
+ /** What every app that uses Astryx already has: Core, and React through Core's peers. */
221
+ const APP_PROVIDED = new Set(['@astryxdesign/core', 'react', 'react-dom']);
222
+
223
+ /**
224
+ * The npm package a module specifier names, or null for a relative path, an
225
+ * absolute path, or a Node built-in.
226
+ * @param {string} specifier
227
+ * @returns {string | null}
228
+ */
229
+ function packageOfSpecifier(specifier) {
230
+ if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
231
+ if (isBuiltin(specifier)) return null;
232
+ const parts = specifier.split('/');
233
+ return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
234
+ }
235
+
236
+ /**
237
+ * The npm packages a fork's copied files import that its package does not
238
+ * declare yet, each at the range the bundled themes are built against (the
239
+ * CLI's own package.json). The fork depends on them at runtime, so an app that
240
+ * installs the package needs them too. Derived from the imports, not copied
241
+ * from a base's whole dependency list. Core and React are left out, since every
242
+ * Astryx app has them; so is a fork of the package's own theme, whose imports
243
+ * the package already resolves.
244
+ *
245
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} base
246
+ * @param {Record<string, any>} pkg - The package's package.json.
247
+ * @returns {Record<string, string>} package name to range
248
+ */
249
+ function forkDependencies(base, pkg) {
250
+ if (!base.bundled) return {};
251
+ /** @type {Record<string, any>} */
252
+ let cli;
253
+ try {
254
+ cli = JSON.parse(
255
+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf-8'),
256
+ );
257
+ } catch {
258
+ return {};
259
+ }
260
+ /** @type {Record<string, string>} */
261
+ const ranges = {
262
+ ...cli.devDependencies,
263
+ ...cli.peerDependencies,
264
+ ...cli.dependencies,
265
+ };
266
+ const declared = {
267
+ ...pkg.devDependencies,
268
+ ...pkg.peerDependencies,
269
+ ...pkg.dependencies,
270
+ };
271
+ /** @type {Record<string, string>} */
272
+ const needed = {};
273
+ for (const file of base.files) {
274
+ const code = /\.(?:[cm]?[jt]sx?)$/u.test(file);
275
+ if (!code || file.endsWith('.doc.mjs')) continue;
276
+ let specifiers;
277
+ try {
278
+ specifiers = themeFileImports(path.join(base.sourceDir, file));
279
+ } catch {
280
+ continue; // discovery already refuses a theme whose source does not parse
281
+ }
282
+ for (const specifier of specifiers) {
283
+ const name = packageOfSpecifier(specifier);
284
+ if (name == null || APP_PROVIDED.has(name) || name in declared) continue;
285
+ if (typeof ranges[name] === 'string') needed[name] = ranges[name];
286
+ }
287
+ }
288
+ return needed;
289
+ }
290
+
217
291
  /**
218
292
  * Build the write plans for a forked theme.
219
293
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} base
@@ -467,11 +541,27 @@ export async function integrationAddTheme(name, options = {}) {
467
541
  packageUpdate?.expectedOriginal ?? fs.readFileSync(packageFile);
468
542
  const text = packageUpdate?.contents ?? expectedOriginal.toString('utf-8');
469
543
  const current = JSON.parse(text);
470
- if (themesCliProblem(current) != null) {
544
+ let next =
545
+ themesCliProblem(current) != null
546
+ ? withCliPeer(current, THEMES_CLI)
547
+ : current;
548
+ // A fork runs the base's imports: declare the packages they come from.
549
+ const forked = baseTheme ? forkDependencies(baseTheme, next) : {};
550
+ if (Object.keys(forked).length > 0) {
551
+ const dependencies = {...next.dependencies, ...forked};
552
+ next = {
553
+ ...next,
554
+ dependencies: Object.fromEntries(
555
+ Object.keys(dependencies)
556
+ .sort()
557
+ .map(name => [name, dependencies[name]]),
558
+ ),
559
+ };
560
+ }
561
+ if (next !== current) {
471
562
  packageUpdate = {
472
563
  contents:
473
- JSON.stringify(withCliPeer(current, THEMES_CLI), null, 2) +
474
- (text.endsWith('\n') ? '\n' : ''),
564
+ JSON.stringify(next, null, 2) + (text.endsWith('\n') ? '\n' : ''),
475
565
  expectedOriginal,
476
566
  };
477
567
  }
@@ -1,8 +1,10 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  import {afterEach, beforeEach, describe, expect, it} from 'vitest';
4
+ import {execFileSync} from 'node:child_process';
4
5
  import * as fs from 'node:fs';
5
6
  import * as path from 'node:path';
7
+ import {CLI_ROOT, findInstalledPackage} from '../../foundation/fs/paths.mjs';
6
8
  import {integrationAddTheme} from './add-theme.mjs';
7
9
  import {validateLocalIntegration} from './validate-integration.mjs';
8
10
 
@@ -473,6 +475,104 @@ describe('integrationAddTheme --from', () => {
473
475
  ).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});
474
476
  });
475
477
 
478
+ it('declares the npm packages the forked files import, at the range the bundled themes use', async () => {
479
+ setup({includeFiles: false});
480
+ await integrationAddTheme('ocean', {cwd: tmpDir, from: 'neutral'});
481
+ const pkg = JSON.parse(
482
+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
483
+ );
484
+ const cli = JSON.parse(
485
+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf-8'),
486
+ );
487
+ // The copied icons.tsx imports lucide-react; Core and React are every
488
+ // app's own, so the fork does not declare them.
489
+ expect(pkg.dependencies).toEqual({
490
+ 'lucide-react': cli.devDependencies['lucide-react'],
491
+ });
492
+ expect(pkg.peerDependencies).toEqual({'@astryxdesign/cli': '>=0.6.4'});
493
+ });
494
+
495
+ it('keeps a dependency the package already declares', async () => {
496
+ setup({includeFiles: false});
497
+ const file = path.join(tmpDir, 'package.json');
498
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
499
+ fs.writeFileSync(
500
+ file,
501
+ `${JSON.stringify({...pkg, dependencies: {'lucide-react': '^1.0.0'}}, null, 2)}\n`,
502
+ );
503
+ await integrationAddTheme('ocean', {cwd: tmpDir, from: 'neutral'});
504
+ expect(JSON.parse(fs.readFileSync(file, 'utf-8')).dependencies).toEqual({
505
+ 'lucide-react': '^1.0.0',
506
+ });
507
+ });
508
+
509
+ it('declares nothing for a fork of a theme the package owns', async () => {
510
+ setup({includeFiles: false});
511
+ await integrationAddTheme('base', {cwd: tmpDir});
512
+ await integrationAddTheme('variant', {cwd: tmpDir, from: 'base'});
513
+ const pkg = JSON.parse(
514
+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
515
+ );
516
+ expect(pkg.dependencies).toBeUndefined();
517
+ });
518
+
519
+ it('builds a forked neutral theme once the package installs what --from declared', async () => {
520
+ setup({includeFiles: false});
521
+ await integrationAddTheme('ocean', {cwd: tmpDir, from: 'neutral'});
522
+ const pkg = JSON.parse(
523
+ fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'),
524
+ );
525
+ // Install exactly what the package declares, plus what every Astryx
526
+ // project has: Core and React.
527
+ for (const name of [
528
+ ...Object.keys(pkg.dependencies ?? {}),
529
+ '@astryxdesign/core',
530
+ 'react',
531
+ ]) {
532
+ const installed = findInstalledPackage(CLI_ROOT, name);
533
+ expect(installed, name).not.toBeNull();
534
+ const link = path.join(tmpDir, 'node_modules', ...name.split('/'));
535
+ fs.mkdirSync(path.dirname(link), {recursive: true});
536
+ fs.symlinkSync(
537
+ fs.realpathSync(/** @type {string} */ (installed)),
538
+ link,
539
+ 'dir',
540
+ );
541
+ }
542
+ // A separate process without NODE_PATH, so only what the package
543
+ // installed can resolve.
544
+ let status = 0;
545
+ let output = '';
546
+ try {
547
+ execFileSync(
548
+ process.execPath,
549
+ [
550
+ path.join(CLI_ROOT, 'clients/cli/bin/astryx.mjs'),
551
+ 'theme',
552
+ 'build',
553
+ 'themes/ocean/oceanTheme.ts',
554
+ ],
555
+ {
556
+ cwd: tmpDir,
557
+ env: {...process.env, NODE_PATH: ''},
558
+ encoding: 'utf-8',
559
+ stdio: 'pipe',
560
+ },
561
+ );
562
+ } catch (error) {
563
+ const failure = /** @type {any} */ (error);
564
+ status = failure.status ?? 1;
565
+ output = `${failure.stdout ?? ''}${failure.stderr ?? ''}`;
566
+ }
567
+ expect({status, output: status === 0 ? '' : output}).toEqual({
568
+ status: 0,
569
+ output: '',
570
+ });
571
+ expect(fs.existsSync(path.join(tmpDir, 'themes/ocean/ocean.css'))).toBe(
572
+ true,
573
+ );
574
+ });
575
+
476
576
  it('works with different bundled themes', async () => {
477
577
  setup();
478
578
  const result = await integrationAddTheme('dusk', {
@@ -37,7 +37,7 @@ export const doc = {
37
37
  name: 'options.from',
38
38
  type: 'string',
39
39
  description:
40
- 'Slug of an existing theme to fork as the starting point. The new theme copies the base and has no link back.',
40
+ 'Slug of an existing theme to fork as the starting point. The new theme copies the base and has no link back, and package.json `dependencies` gains the npm packages the copied files import (other than Core and React).',
41
41
  },
42
42
  ],
43
43
  returns: [
@@ -66,6 +66,7 @@ export function scoreQuery(term: string, tokens: string[], candidate: Candidate)
66
66
  * @param {string} term - Lowercased search term.
67
67
  * @param {object} candidate
68
68
  * @param {string} candidate.name - Primary identifier (component/hook name, topic, template name).
69
+ * @param {string[]} [candidate.aliases] - Other names, scored like the name (a theme's display name).
69
70
  * @param {string} [candidate.domain] - A component, hook, or template name
70
71
  * also matches typed as words: `command palette` is CommandPalette.
71
72
  * @param {string[]} [candidate.keywords] - Authored intent (componentsUsed, category words).
@@ -76,8 +77,9 @@ export function scoreQuery(term: string, tokens: string[], candidate: Candidate)
76
77
  * @param {{fuzzy?: boolean}} [opts] - `fuzzy`: allow edit-distance (typo) matches. Default true; multi-word queries pass false.
77
78
  * @returns {{score: number, reason: string} | null}
78
79
  */
79
- export function scoreCandidate(term: string, { name, domain, keywords, weakKeywords, description, prose, guidance, }: {
80
+ export function scoreCandidate(term: string, { name, aliases, domain, keywords, weakKeywords, description, prose, guidance, }: {
80
81
  name: string;
82
+ aliases?: string[] | undefined;
81
83
  domain?: string | undefined;
82
84
  keywords?: string[] | undefined;
83
85
  weakKeywords?: string[] | undefined;
@@ -161,6 +163,11 @@ export const STOPWORDS: Set<string>;
161
163
  export type Candidate = {
162
164
  domain: "component" | "hook" | "doc" | "template" | "theme";
163
165
  name: string;
166
+ /**
167
+ * - Other names the candidate answers to, scored
168
+ * with the same name signals: a theme's display name.
169
+ */
170
+ aliases?: string[] | undefined;
164
171
  keywords?: string[] | undefined;
165
172
  weakKeywords?: string[] | undefined;
166
173
  description?: string | undefined;
@@ -113,6 +113,8 @@ import {setResultCoverage} from './coverage.mjs';
113
113
  * @typedef {object} Candidate
114
114
  * @property {'component'|'hook'|'doc'|'template'|'theme'} domain
115
115
  * @property {string} name
116
+ * @property {string[]} [aliases] - Other names the candidate answers to, scored
117
+ * with the same name signals: a theme's display name.
116
118
  * @property {string[]} [keywords]
117
119
  * @property {string[]} [weakKeywords]
118
120
  * @property {string} [description]
@@ -717,6 +719,7 @@ export function scoreQuery(term, tokens, candidate) {
717
719
  * @param {string} term - Lowercased search term.
718
720
  * @param {object} candidate
719
721
  * @param {string} candidate.name - Primary identifier (component/hook name, topic, template name).
722
+ * @param {string[]} [candidate.aliases] - Other names, scored like the name (a theme's display name).
720
723
  * @param {string} [candidate.domain] - A component, hook, or template name
721
724
  * also matches typed as words: `command palette` is CommandPalette.
722
725
  * @param {string[]} [candidate.keywords] - Authored intent (componentsUsed, category words).
@@ -731,6 +734,7 @@ export function scoreCandidate(
731
734
  term,
732
735
  {
733
736
  name,
737
+ aliases = [],
734
738
  domain,
735
739
  keywords = [],
736
740
  weakKeywords = [],
@@ -753,40 +757,44 @@ export function scoreCandidate(
753
757
  }
754
758
  };
755
759
 
756
- const nameLower = name.toLowerCase();
757
- // A placed guide's name is its route, and the route's last segment is its
758
- // name too, as a flat topic's is: `codemods` is cli/integrations/codemods.
759
- const leafLower = nameLower.slice(nameLower.lastIndexOf('/') + 1);
760
-
761
760
  // ── Name signals ────────────────────────────────────────────────
762
- // A plural of the name is the name: `integration` is the `integrations`
763
- // guides, `tab` the `tabs` doc.
764
- // A component, hook, or template name typed as words is its name:
765
- // `command palette` is CommandPalette. A doc's name is a route or key,
766
- // matched as written.
767
- const spelled =
768
- domain !== 'doc' &&
769
- !/[\s_-]/.test(nameLower) &&
770
- nameLower === term.replace(/\s+/g, '');
771
- if (nameLower === term || leafLower === term || spelled) {
772
- consider(100, 'exact name');
773
- } else if (pluralOf(nameLower, term) || pluralOf(term, nameLower)) {
774
- // One point under the exact spelling, so the doc named `tokens` still
775
- // outranks the Token component for `tokens`.
776
- consider(99, 'plural of the name');
777
- } else {
778
- if (sameWord(term, nameLower)) consider(95, `name "${name}"`);
779
- // The term is a word of the name, or starts one: "input" in TextInput.
780
- else if (startsAWordOf(term, name)) {
781
- consider(60, `name contains "${term}"`);
782
- }
783
- if (fuzzy) {
784
- const dist = levenshteinDistance(term, nameLower);
785
- if (isTypo(term, nameLower, dist)) {
786
- consider(
787
- dist === 1 ? 80 : dist === 2 ? 40 : 20,
788
- `similar name (distance ${dist})`,
789
- );
761
+ // An alias is a name too: a theme answers to its display name as well as
762
+ // its slug.
763
+ for (const candidateName of [name, ...aliases.filter(Boolean)]) {
764
+ const nameLower = candidateName.toLowerCase();
765
+ // A placed guide's name is its route, and the route's last segment is its
766
+ // name too, as a flat topic's is: `codemods` is cli/integrations/codemods.
767
+ const leafLower = nameLower.slice(nameLower.lastIndexOf('/') + 1);
768
+
769
+ // A plural of the name is the name: `integration` is the `integrations`
770
+ // guides, `tab` the `tabs` doc.
771
+ // A component, hook, or template name typed as words is its name:
772
+ // `command palette` is CommandPalette. A doc's name is a route or key,
773
+ // matched as written.
774
+ const spelled =
775
+ domain !== 'doc' &&
776
+ !/[\s_-]/.test(nameLower) &&
777
+ nameLower === term.replace(/\s+/g, '');
778
+ if (nameLower === term || leafLower === term || spelled) {
779
+ consider(100, 'exact name');
780
+ } else if (pluralOf(nameLower, term) || pluralOf(term, nameLower)) {
781
+ // One point under the exact spelling, so the doc named `tokens` still
782
+ // outranks the Token component for `tokens`.
783
+ consider(99, 'plural of the name');
784
+ } else {
785
+ if (sameWord(term, nameLower)) consider(95, `name "${candidateName}"`);
786
+ // The term is a word of the name, or starts one: "input" in TextInput.
787
+ else if (startsAWordOf(term, candidateName)) {
788
+ consider(60, `name contains "${term}"`);
789
+ }
790
+ if (fuzzy) {
791
+ const dist = levenshteinDistance(term, nameLower);
792
+ if (isTypo(term, nameLower, dist)) {
793
+ consider(
794
+ dist === 1 ? 80 : dist === 2 ? 40 : 20,
795
+ `similar name (distance ${dist})`,
796
+ );
797
+ }
790
798
  }
791
799
  }
792
800
  }
@@ -1487,6 +1495,12 @@ async function gatherTemplates(cwd) {
1487
1495
  * Build theme candidates from bundled and integration-provided themes. Without
1488
1496
  * this, an integration's themes are invisible to `search` even though
1489
1497
  * `theme list` and `discover` already resolve them.
1498
+ *
1499
+ * A theme's slug and display name are its names, and its description is prose
1500
+ * (`spec:AST-050/FR14`). A theme declares no keywords, so a word it shares with
1501
+ * the query only through its description is a description mention: read as a
1502
+ * keyword, every word of the description would outrank the components and docs
1503
+ * that declare that word.
1490
1504
  * @param {string} cwd
1491
1505
  * @returns {Promise<Candidate[]>}
1492
1506
  */
@@ -1500,10 +1514,7 @@ async function gatherThemes(cwd) {
1500
1514
  return themes.map(t => ({
1501
1515
  domain: 'theme',
1502
1516
  name: t.slug,
1503
- keywords: [
1504
- t.displayName,
1505
- ...(t.description ? t.description.split(/[^A-Za-z0-9]+/).filter(w => w.length > 3) : []),
1506
- ],
1517
+ aliases: t.displayName ? [t.displayName] : [],
1507
1518
  description: t.description || '',
1508
1519
  _displayName: t.displayName,
1509
1520
  _package: t.package,
@@ -25,6 +25,8 @@ import * as os from 'node:os';
25
25
  import * as path from 'node:path';
26
26
  import {fileURLToPath} from 'node:url';
27
27
  import {docs} from '../docs/docs.mjs';
28
+ import {listAvailableThemes} from '../theme/_adapter.mjs';
29
+ import {doc as themeAddCommandDoc} from '../../clients/cli/commands/theme-add.doc.mjs';
28
30
  import {
29
31
  headingWithPhrase,
30
32
  titleInQuery,
@@ -76,7 +78,10 @@ describe('search leaf — envelope + ranking', () => {
76
78
 
77
79
  describe('search leaf — per-domain result fields', () => {
78
80
  it('carries import for components and hooks, title for docs, displayName and kind for templates, displayName for themes', async () => {
79
- const r = await search('theme', {cwd, limit: 60});
81
+ // `theme` reaches every domain, but a theme matches it only through its
82
+ // description, a prose mention below every name and keyword hit, so read
83
+ // the whole result list.
84
+ const r = await search('theme', {cwd, limit: 400});
80
85
  expect(new Set(r.data.results.map(res => res.domain))).toEqual(
81
86
  new Set(SEARCH_DOMAINS),
82
87
  );
@@ -499,6 +504,114 @@ describe('search leaf — limit validation (API matches the CLI contract)', () =
499
504
  }, SLOW);
500
505
  });
501
506
 
507
+ describe('search leaf — a theme is found by its names; its description is prose (AST-050 FR14)', () => {
508
+ /** A result that answers the query by a name or a declared keyword, not a typo or a mention. */
509
+ const matchesByNameOrKeyword = (/** @type {{reason: string}} */ result) =>
510
+ /^(exact name|plural of the name|name "|name contains ")/.test(result.reason) ||
511
+ /^keyword "[^"]*"$/.test(result.reason);
512
+
513
+ /**
514
+ * The `theme add` command AST-050 FR12 and FR13 name for the stage that
515
+ * `theme add` itself declares: no `--import` yet, a deprecated copy default
516
+ * beside `--import`, or the cleanup, which keeps `--import` and drops the
517
+ * copy's `--overwrite`.
518
+ * @param {string} slug
519
+ */
520
+ function themeAddCommandForStage(slug) {
521
+ const flags = themeAddCommandDoc.options.flatMap(option => option.flag.split(/[\s,]+/));
522
+ if (!flags.includes('--import')) return `astryx theme add ${slug}`;
523
+ if (flags.includes('--overwrite')) return `astryx theme add --import ${slug}`;
524
+ return `astryx theme add ${slug}`;
525
+ }
526
+
527
+ it(
528
+ 'ranks a theme found only through its description below every name and keyword match',
529
+ async () => {
530
+ for (const [query, slugs] of [
531
+ ['focus', ['neutral']],
532
+ ['content', ['matcha', 'neutral']],
533
+ ]) {
534
+ const {results} = (await search(query, {cwd, limit: 400})).data;
535
+ const strong = results.filter(
536
+ result => result.domain !== 'theme' && matchesByNameOrKeyword(result),
537
+ );
538
+ expect(strong.length).toBeGreaterThan(0);
539
+ const lastStrong = Math.max(...strong.map(result => results.indexOf(result)));
540
+ for (const slug of slugs) {
541
+ const at = results.findIndex(result => result.domain === 'theme' && result.name === slug);
542
+ expect(at).toBeGreaterThan(-1);
543
+ expect(results[at].reason).toMatch(/^description mentions /);
544
+ expect(at).toBeGreaterThan(lastStrong);
545
+ }
546
+ }
547
+ },
548
+ SLOW,
549
+ );
550
+
551
+ it(
552
+ 'scores a word in a theme description the same as a word in a component description',
553
+ async () => {
554
+ const {results} = (await search('minimal', {cwd, limit: 400})).data;
555
+ const neutral = results.find(result => result.domain === 'theme' && result.name === 'neutral');
556
+ const topNav = results.find(result => result.domain === 'component' && result.name === 'TopNav');
557
+ expect(neutral?.reason).toMatch(/^description mentions /);
558
+ expect(topNav?.reason).toMatch(/^description mentions /);
559
+ expect(neutral?.score).toBe(topNav?.score);
560
+ },
561
+ SLOW,
562
+ );
563
+
564
+ it(
565
+ 'keeps a theme that matches every word only in its description below results with a keyword hit',
566
+ async () => {
567
+ // Overlay and Dialog declare `focus` and mention `content`; neutral only
568
+ // mentions both, in "so the content stays the focus".
569
+ const {results} = (await search('content focus', {cwd, limit: 400})).data;
570
+ const neutral = results.findIndex(result => result.domain === 'theme' && result.name === 'neutral');
571
+ expect(neutral).toBeGreaterThan(-1);
572
+ for (const name of ['Overlay', 'Dialog']) {
573
+ const at = results.findIndex(result => result.domain === 'component' && result.name === name);
574
+ expect(at).toBeGreaterThan(-1);
575
+ expect(at).toBeLessThan(neutral);
576
+ }
577
+ },
578
+ SLOW,
579
+ );
580
+
581
+ it(
582
+ 'still finds a theme first by its slug or its display name',
583
+ async () => {
584
+ for (const query of ['neutral', 'Matcha', 'Y2K']) {
585
+ const [first] = (await search(query, {cwd})).data.results;
586
+ expect(first).toMatchObject({domain: 'theme', name: query.toLowerCase(), reason: 'exact name'});
587
+ }
588
+ },
589
+ SLOW,
590
+ );
591
+
592
+ it('scores a display name with the same name signals as the slug', () => {
593
+ const theme = {name: 'ocean', aliases: ['Ocean Blue'], description: 'Deep blues for calm reading.'};
594
+ expect(scoreCandidate('ocean blue', theme)).toEqual(scoreCandidate('ocean', theme));
595
+ expect(scoreCandidate('ocean blue', {...theme, aliases: []})?.score ?? 0).toBeLessThan(
596
+ scoreCandidate('ocean', theme).score,
597
+ );
598
+ });
599
+
600
+ it(
601
+ 'names the theme add command for the stage theme add declares',
602
+ async () => {
603
+ const themes = await listAvailableThemes(cwd);
604
+ expect(themes.length).toBeGreaterThan(0);
605
+ for (const {slug} of themes) {
606
+ const {results} = (await search(slug, {cwd, type: 'theme'})).data;
607
+ const result = results.find(entry => entry.name === slug);
608
+ expect(result?.command).toBe(themeAddCommandForStage(slug));
609
+ }
610
+ },
611
+ SLOW,
612
+ );
613
+ });
614
+
502
615
  describe('search leaf — integration components', () => {
503
616
  /**
504
617
  * A minimal consumer project: a stub `@astryxdesign/core` (so `findCoreDir`
@@ -65,6 +65,10 @@ Declare theme root ./themes in astryx.integration.mjs.
65
65
  lang: 'bash',
66
66
  code: 'npx astryx integration add theme ocean --from neutral',
67
67
  },
68
+ {
69
+ type: 'prose',
70
+ text: 'The copy keeps the packages the base theme uses, such as `lucide-react` for its icons: `--from` adds them to your `dependencies`, so an app that installs your package gets them too. Install your dependencies again before you build the theme.',
71
+ },
68
72
  {
69
73
  type: 'prose',
70
74
  text: 'Use `--from` when you want to change a lot. For a small change that should stay linked to a base theme, use `extends` instead ({@link generic:define-the-theme}).',
@@ -60,7 +60,7 @@ export const doc = {
60
60
  flag: '--from <theme>',
61
61
  param: 'options.from',
62
62
  description:
63
- 'Existing theme slug to fork as a starting point instead of a blank scaffold; the new theme copies the base and has no link back. Only valid for theme',
63
+ 'Existing theme slug to fork as a starting point instead of a blank scaffold; the new theme copies the base and has no link back, and package.json `dependencies` gains the npm packages the copied files import (other than Core and React). Only valid for theme',
64
64
  },
65
65
  {
66
66
  flag: '--to <version>',
@@ -288,22 +288,31 @@ describe('search CLI — exit codes + JSON contract', () => {
288
288
  });
289
289
 
290
290
  it('prints every result field under its JSON key (score and reason with --verbose)', async () => {
291
- // One query that reaches every domain, so every per-domain field shows.
292
- const args = ['search', 'theme', '--limit', '60'];
293
- const env = JSON.parse((await runCli(['--json', ...args], REPO_ROOT)).stdout);
294
- expect(new Set(env.data.results.map(r => r.domain))).toEqual(new Set(SEARCH_DOMAINS));
295
- const plain = (await runCli(args, REPO_ROOT)).stdout.split('\n');
296
- const verbose = (await runCli([...args, '--verbose'], REPO_ROOT)).stdout.split('\n');
297
- for (const result of env.data.results) {
298
- for (const [key, value] of Object.entries(result)) {
299
- if (value == null || value === '') continue;
300
- const label = `${result.domain} ${result.name}: ${key}`;
301
- expect(printsField(verbose, key, value), label).toBe(true);
302
- if (key !== 'score' && key !== 'reason') {
303
- expect(printsField(plain, key, value), label).toBe(true);
291
+ // Between them these reach every domain, so every per-domain field shows.
292
+ // A theme matches `theme` only through its description, a prose mention
293
+ // ranked below every name and keyword hit, so the theme domain comes from
294
+ // a theme's own name.
295
+ const domains = new Set();
296
+ for (const args of [
297
+ ['search', 'theme', '--limit', '60'],
298
+ ['search', 'neutral', '--type', 'theme'],
299
+ ]) {
300
+ const env = JSON.parse((await runCli(['--json', ...args], REPO_ROOT)).stdout);
301
+ const plain = (await runCli(args, REPO_ROOT)).stdout.split('\n');
302
+ const verbose = (await runCli([...args, '--verbose'], REPO_ROOT)).stdout.split('\n');
303
+ for (const result of env.data.results) {
304
+ domains.add(result.domain);
305
+ for (const [key, value] of Object.entries(result)) {
306
+ if (value == null || value === '') continue;
307
+ const label = `${result.domain} ${result.name}: ${key}`;
308
+ expect(printsField(verbose, key, value), label).toBe(true);
309
+ if (key !== 'score' && key !== 'reason') {
310
+ expect(printsField(plain, key, value), label).toBe(true);
311
+ }
304
312
  }
305
313
  }
306
314
  }
315
+ expect(domains).toEqual(new Set(SEARCH_DOMAINS));
307
316
  }, 90_000);
308
317
 
309
318
  it('--verbose exits 0 and prints import/match detail', async () => {
@@ -1,6 +1,12 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
+ /**
5
+ * Every module a theme source file imports or re-exports, as written.
6
+ * @param {string} file
7
+ * @returns {string[]}
8
+ */
9
+ export function themeFileImports(file: string): string[];
4
10
  /**
5
11
  * How messages about a theme descriptor name it.
6
12
  * @param {string} docPath
@@ -200,6 +200,15 @@ function moduleSpecifiers(file, jscodeshift) {
200
200
  return specifiers;
201
201
  }
202
202
 
203
+ /**
204
+ * Every module a theme source file imports or re-exports, as written.
205
+ * @param {string} file
206
+ * @returns {string[]}
207
+ */
208
+ export function themeFileImports(file) {
209
+ return moduleSpecifiers(file, sourceParser());
210
+ }
211
+
203
212
  /**
204
213
  * Validate that every local static dependency is copied with the theme.
205
214
  * @param {string} file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.6.5-canary.a477e48",
3
+ "version": "0.6.5-canary.a8b2251",
4
4
  "displayName": "CLI",
5
5
  "description": "Scaffold projects, browse templates, generate themes, and get agent-ready docs from the command line.",
6
6
  "author": "Meta Open Source",
@@ -101,10 +101,10 @@
101
101
  "zod": "^4.4.3"
102
102
  },
103
103
  "peerDependencies": {
104
- "@astryxdesign/charts": "0.6.5-canary.a477e48",
105
- "@astryxdesign/core": "0.6.5-canary.a477e48",
106
- "@astryxdesign/lab": "0.6.5-canary.a477e48",
107
- "@astryxdesign/theme-neutral": "0.6.5-canary.a477e48"
104
+ "@astryxdesign/charts": "0.6.5-canary.a8b2251",
105
+ "@astryxdesign/core": "0.6.5-canary.a8b2251",
106
+ "@astryxdesign/lab": "0.6.5-canary.a8b2251",
107
+ "@astryxdesign/theme-neutral": "0.6.5-canary.a8b2251"
108
108
  },
109
109
  "peerDependenciesMeta": {
110
110
  "@astryxdesign/charts": {
@@ -121,10 +121,10 @@
121
121
  }
122
122
  },
123
123
  "devDependencies": {
124
- "@astryxdesign/charts": "0.6.5-canary.a477e48",
125
- "@astryxdesign/core": "0.6.5-canary.a477e48",
126
- "@astryxdesign/lab": "0.6.5-canary.a477e48",
127
- "@astryxdesign/theme-neutral": "0.6.5-canary.a477e48",
124
+ "@astryxdesign/charts": "0.6.5-canary.a8b2251",
125
+ "@astryxdesign/core": "0.6.5-canary.a8b2251",
126
+ "@astryxdesign/lab": "0.6.5-canary.a8b2251",
127
+ "@astryxdesign/theme-neutral": "0.6.5-canary.a8b2251",
128
128
  "@heroicons/react": "^2.2.0",
129
129
  "@stylexjs/stylex": "^0.19.0",
130
130
  "@types/babel__core": "^7.20.5",