@astryxdesign/cli 0.6.5-canary.8701623 → 0.6.5-canary.8d216bb

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.
Files changed (37) hide show
  1. package/README.md +2 -2
  2. package/api/gap-report/gap-report.d.mts +3 -1
  3. package/api/gap-report/gap-report.mjs +12 -2
  4. package/api/gap-report/gap-report.test.mjs +106 -0
  5. package/api/search/search.d.mts +4 -4
  6. package/api/search/search.doc.mjs +4 -4
  7. package/api/search/search.mjs +79 -20
  8. package/api/search/search.test.mjs +9 -7
  9. package/api/search/search.type.d.mts +5 -5
  10. package/api/search/search.type.mjs +5 -5
  11. package/api/theme/build/build.icon-lineage.test.mjs +117 -0
  12. package/api/theme/build/build.icon-preservation.test.mjs +639 -0
  13. package/api/theme/build/build.mjs +146 -69
  14. package/api/theme/build/build.test.mjs +190 -1
  15. package/api/theme/build/icon-imports.d.mts +47 -0
  16. package/api/theme/build/icon-imports.mjs +691 -0
  17. package/api/theme/themeBuild.doc.d.mts +4 -1
  18. package/api/theme/themeBuild.doc.mjs +14 -3
  19. package/assets/docs/theme.doc.mjs +2 -1
  20. package/assets/docs/tree/debug-and-gap-reports.doc.mjs +1 -1
  21. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupShowcase.doc.mjs +15 -0
  22. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupShowcase.tsx +38 -0
  23. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupWithSelectable.doc.mjs +20 -0
  24. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupWithSelectable.tsx +48 -0
  25. package/clients/cli/commands/build-theme.mjs +8 -2
  26. package/clients/cli/commands/discover.mjs +29 -1
  27. package/clients/cli/commands/discover.no-source.test.mjs +75 -0
  28. package/clients/cli/commands/gap-report.mjs +12 -0
  29. package/clients/cli/commands/gap-report.test.mjs +63 -0
  30. package/clients/cli/commands/search.doc.mjs +5 -4
  31. package/clients/cli/commands/search.mjs +30 -6
  32. package/clients/cli/commands/search.test.mjs +39 -4
  33. package/clients/cli/commands/theme-list.behavior.test.mjs +41 -0
  34. package/foundation/agent-docs/agent-docs.mjs +2 -1
  35. package/foundation/agent-docs/agent-docs.test.mjs +8 -0
  36. package/foundation/doc-compiler/doc-loads.test.mjs +1 -1
  37. package/package.json +9 -9
package/README.md CHANGED
@@ -69,7 +69,7 @@ Results for "button" (20 of 239):
69
69
 
70
70
  Options:
71
71
 
72
- - `--type <component|hook|doc|template>`: restrict to a single domain
72
+ - `--type <component|hook|doc|template|theme>`: restrict to a single domain (`doc` and `theme` work outside an app too)
73
73
  - `--limit <n>`: cap the number of results (default 20)
74
74
  - `--verbose`: also print each result's match score and reason
75
75
  - `--json`: typed `{ apiVersion, type: 'search', data: { query, matchCount, results } }` envelope — `matchCount` is how many candidates matched in total, `results` the slice `--limit` allowed
@@ -91,7 +91,7 @@ Options:
91
91
  | `init` | Initialize the design system in your project |
92
92
  | `integration` | Author and verify an Astryx integration package |
93
93
  | `layout` | Generate XDS layouts from compressed expressions (XLE/XLO) |
94
- | `search` | Search components, hooks, docs, and templates in one ranked list |
94
+ | `search` | Search components, hooks, docs, templates, and themes in one ranked list |
95
95
  | `swizzle` | Copy component source for customization |
96
96
  | `template` | List, show, or scaffold page and block templates |
97
97
  | `theme` | Create and build themes: add a shipped one, compile to CSS, or list what a theme can override |
@@ -4,7 +4,9 @@
4
4
  /**
5
5
  * Collect the effective handler set in delivery order: project config first,
6
6
  * then integrations in config order. Valid handlers dedupe by handle identity;
7
- * malformed integration exports retain their position as failed deliveries.
7
+ * malformed integration exports and integrations that failed to load retain
8
+ * their position as failed deliveries. An unloadable integration may export a
9
+ * handler, so it never counts as an empty set that enables the fallback.
8
10
  *
9
11
  * @param {Project} project
10
12
  * @returns {HandlerEntry[]}
@@ -189,7 +189,9 @@ async function selectTarget(project, component, packageName) {
189
189
  /**
190
190
  * Collect the effective handler set in delivery order: project config first,
191
191
  * then integrations in config order. Valid handlers dedupe by handle identity;
192
- * malformed integration exports retain their position as failed deliveries.
192
+ * malformed integration exports and integrations that failed to load retain
193
+ * their position as failed deliveries. An unloadable integration may export a
194
+ * handler, so it never counts as an empty set that enables the fallback.
193
195
  *
194
196
  * @param {Project} project
195
197
  * @returns {HandlerEntry[]}
@@ -214,7 +216,15 @@ export function collectGapReportHandlers(project) {
214
216
  }
215
217
 
216
218
  for (const integration of project.loadedIntegrations) {
217
- if (integration.__loadError) continue;
219
+ if (integration.__loadError) {
220
+ entries.push({
221
+ kind: 'malformed',
222
+ handlerType: 'integration',
223
+ handlerName: integration.name,
224
+ error: `Integration failed to load, so it could not receive this report: ${integration.__loadError}. Fix the package or remove it from integrations in astryx.config, then rerun.`,
225
+ });
226
+ continue;
227
+ }
218
228
  if (integration.__gapReportError) {
219
229
  entries.push({
220
230
  kind: 'malformed',
@@ -105,6 +105,45 @@ function addIntegration({
105
105
  return {dir};
106
106
  }
107
107
 
108
+ /**
109
+ * Add an integration whose module throws on import, so it never loads.
110
+ * @param {string} name
111
+ */
112
+ function addBrokenIntegration(name) {
113
+ const dir = packageDir(name);
114
+ fs.mkdirSync(dir, {recursive: true});
115
+ fs.writeFileSync(
116
+ path.join(dir, 'package.json'),
117
+ JSON.stringify({name, version: '1.0.0', type: 'module'}),
118
+ );
119
+ fs.writeFileSync(
120
+ path.join(dir, 'astryx.integration.mjs'),
121
+ "throw new Error('intentional integration load failure');\n",
122
+ );
123
+ }
124
+
125
+ /**
126
+ * Put a fake `gh` first on PATH that records its arguments if it is called.
127
+ * @returns {string} the file the fake writes when invoked
128
+ */
129
+ function stubGh() {
130
+ const binDir = path.join(projectDir, 'bin');
131
+ const argsFile = path.join(projectDir, 'gh-args.json');
132
+ fs.mkdirSync(binDir, {recursive: true});
133
+ fs.writeFileSync(
134
+ path.join(binDir, 'gh'),
135
+ `#!/usr/bin/env node
136
+ import fs from 'node:fs';
137
+ fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));
138
+ console.log('https://github.com/acme/core/issues/42');
139
+ `,
140
+ {mode: 0o755},
141
+ );
142
+ fs.chmodSync(path.join(binDir, 'gh'), 0o755);
143
+ vi.stubEnv('PATH', `${binDir}${path.delimiter}${process.env.PATH ?? ''}`);
144
+ return argsFile;
145
+ }
146
+
108
147
  const reportOptions = {
109
148
  category: 'missing_variant',
110
149
  reason: 'Need a compact size',
@@ -681,6 +720,73 @@ describe('gapReport handler isolation', () => {
681
720
  });
682
721
  });
683
722
 
723
+ it('an integration that fails to load is a failed delivery, not a missing handler', async () => {
724
+ addBrokenIntegration('@test/broken');
725
+ configure(['@test/broken'], {
726
+ issuesUrl: 'https://github.com/acme/core/issues/new',
727
+ });
728
+
729
+ const result = await gapReport('General', {
730
+ ...reportOptions,
731
+ cwd: projectDir,
732
+ });
733
+
734
+ expect(result.data.status).toBe('failed');
735
+ expect(result.data.deliveries).toEqual([
736
+ {
737
+ handlerType: 'integration',
738
+ handler: '@test/broken',
739
+ audience: null,
740
+ status: 'failed',
741
+ url: null,
742
+ message: expect.stringContaining(
743
+ 'intentional integration load failure',
744
+ ),
745
+ },
746
+ ]);
747
+ });
748
+
749
+ it('an integration that fails to load keeps the public fallback off, even with consent', async () => {
750
+ addBrokenIntegration('@test/broken');
751
+ configure(['@test/broken'], {
752
+ issuesUrl: 'https://github.com/acme/core/issues/new',
753
+ });
754
+ const argsFile = stubGh();
755
+
756
+ const result = await gapReport('General', {
757
+ ...reportOptions,
758
+ confirmPublic: true,
759
+ cwd: projectDir,
760
+ });
761
+
762
+ expect(result.data.status).toBe('failed');
763
+ expect(result.data.deliveries.map(d => d.handlerType)).toEqual([
764
+ 'integration',
765
+ ]);
766
+ expect(fs.existsSync(argsFile)).toBe(false);
767
+ });
768
+
769
+ it('an integration that fails to load keeps its place beside working handlers', async () => {
770
+ addBrokenIntegration('@test/broken');
771
+ addIntegration({
772
+ name: '@test/valid',
773
+ audience: 'internal',
774
+ handleBody: "return {status: 'filed', message: 'ok'};",
775
+ });
776
+ configure(['@test/broken', '@test/valid']);
777
+
778
+ const result = await gapReport('General', {
779
+ ...reportOptions,
780
+ cwd: projectDir,
781
+ });
782
+
783
+ expect(result.data.status).toBe('partial');
784
+ expect(result.data.deliveries.map(d => [d.handler, d.status])).toEqual([
785
+ ['@test/broken', 'failed'],
786
+ ['@test/valid', 'filed'],
787
+ ]);
788
+ });
789
+
684
790
  it('invalid handler receipt is recorded as failed delivery', async () => {
685
791
  addIntegration({
686
792
  name: '@test/bad-receipt',
@@ -115,18 +115,18 @@ export function componentKeywords(coreDir: string, cwd: string): Promise<{
115
115
  keywords: string[];
116
116
  }[]>;
117
117
  /**
118
- * Unified ranked search across components, hooks, docs, and templates.
118
+ * Unified ranked search across components, hooks, docs, templates, and themes.
119
119
  *
120
120
  * @param {string} query - Free-text search term.
121
121
  * @param {object} [options]
122
122
  * @param {string} [options.cwd]
123
- * @param {'component'|'hook'|'doc'|'template'} [options.type] - Restrict to one domain.
123
+ * @param {'component'|'hook'|'doc'|'template'|'theme'} [options.type] - Restrict to one domain.
124
124
  * @param {number} [options.limit] - Max results (default 20).
125
125
  * @returns {Promise<import('./search.type.mjs').SearchResponse>}
126
126
  */
127
127
  export function search(query: string, options?: {
128
128
  cwd?: string | undefined;
129
- type?: "component" | "hook" | "template" | "doc" | undefined;
129
+ type?: "theme" | "component" | "hook" | "template" | "doc" | undefined;
130
130
  limit?: number | undefined;
131
131
  }): Promise<import("./search.type.mjs").SearchResponse>;
132
132
  export namespace SYNONYMS {
@@ -159,7 +159,7 @@ export const STOPWORDS: Set<string>;
159
159
  * prefixed fields carry domain-specific payload used only by {@link toResult}.
160
160
  */
161
161
  export type Candidate = {
162
- domain: "component" | "hook" | "doc" | "template";
162
+ domain: "component" | "hook" | "doc" | "template" | "theme";
163
163
  name: string;
164
164
  keywords?: string[] | undefined;
165
165
  weakKeywords?: string[] | undefined;
@@ -14,7 +14,7 @@ export const doc = {
14
14
  namespace: 'cli/api',
15
15
  displayName: 'search()',
16
16
  summary:
17
- 'Unified ranked search across components, hooks, docs, and templates.',
17
+ 'Unified ranked search across components, hooks, docs, templates, and themes.',
18
18
  description:
19
19
  'The single "I\'m looking for X" entry point across every content domain. ' +
20
20
  'Ranking is keyword + fuzzy (not embeddings); name and keyword signals outrank ' +
@@ -35,7 +35,7 @@ export const doc = {
35
35
  },
36
36
  {
37
37
  name: 'options.type',
38
- type: "'component' | 'hook' | 'doc' | 'template'",
38
+ type: "'component' | 'hook' | 'doc' | 'template' | 'theme'",
39
39
  description: 'Restrict results to a single domain.',
40
40
  },
41
41
  {
@@ -48,14 +48,14 @@ export const doc = {
48
48
  name: 'options.cwd',
49
49
  type: 'string',
50
50
  description:
51
- "Directory to resolve @astryxdesign/core from. A docs-only search (`type: 'doc'`) does not need it, and a search with no `type` covers the docs alone when core is missing.",
51
+ "Directory to resolve @astryxdesign/core from. A docs-only or themes-only search (`type: 'doc'` or `type: 'theme'`) does not need it, and a search with no `type` covers the docs and themes alone when core is missing.",
52
52
  },
53
53
  ],
54
54
  returns: [
55
55
  {
56
56
  type: 'search',
57
57
  description:
58
- '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, and `displayName` and `kind` for templates. 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).',
58
+ '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 add: `name` is its slug, its command is the `astryx theme add` that copies it into the app, and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes).',
59
59
  },
60
60
  ],
61
61
  throws: [
@@ -7,10 +7,10 @@
7
7
  * outputs. The CLI command handler is a thin wrapper around this function.
8
8
  *
9
9
  * `search(query)` is the single "I'm looking for X" entry point across ALL
10
- * content domains — components, hooks, docs topics, and templates (page +
11
- * block). Today, finding the right thing requires four separate list calls
12
- * (`component --list`, `hook --list`, `docs`, `template --list`) plus manual
13
- * scanning; this collapses them into one ranked, typed result set.
10
+ * content domains — components, hooks, docs topics, templates (page + block),
11
+ * and themes. Finding the right thing otherwise takes separate list calls
12
+ * (`component --list`, `hook --list`, `docs`, `template --list`, `theme list`)
13
+ * plus manual scanning; this collapses them into one ranked, typed result set.
14
14
  *
15
15
  * Scoring is keyword + fuzzy ranking (NOT semantic / embeddings — that is a
16
16
  * deliberate future follow-up). It reuses the same signal weighting as the
@@ -89,6 +89,7 @@ import {loadIntegrationsSafely} from '../component/_adapter.mjs';
89
89
  import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
90
90
  import {discoverTemplates, extractComponents} from '../template/template.mjs';
91
91
  import {templateLookupIds} from '../../foundation/discovery/template-adapter.mjs';
92
+ import {listAvailableThemes} from '../theme/_adapter.mjs';
92
93
  import {
93
94
  guideEntry,
94
95
  loadDocsCatalog,
@@ -110,7 +111,7 @@ import {setResultCoverage} from './coverage.mjs';
110
111
  * A search candidate gathered from one content domain. Extra underscore-
111
112
  * prefixed fields carry domain-specific payload used only by {@link toResult}.
112
113
  * @typedef {object} Candidate
113
- * @property {'component'|'hook'|'doc'|'template'} domain
114
+ * @property {'component'|'hook'|'doc'|'template'|'theme'} domain
114
115
  * @property {string} name
115
116
  * @property {string[]} [keywords]
116
117
  * @property {string[]} [weakKeywords]
@@ -291,7 +292,13 @@ const isTypo = (a, b, dist) =>
291
292
  TYPO_MIN_LENGTH[/** @type {1 | 2 | 3} */ (dist)];
292
293
 
293
294
  /** Valid domain filters for `--type`. */
294
- export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template'];
295
+ export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template', 'theme'];
296
+
297
+ /**
298
+ * The domains a search reads without @astryxdesign/core. An open search outside
299
+ * an app covers these alone.
300
+ */
301
+ const CORELESS_DOMAINS = ['doc', 'theme'];
295
302
 
296
303
  /**
297
304
  * Filler words stripped from multi-word queries so natural-language phrasing
@@ -618,6 +625,7 @@ export function scoreQuery(term, tokens, candidate) {
618
625
  // strong hits, then reward coverage so candidates matching more terms win.
619
626
  let strongest = 0;
620
627
  let matched = 0;
628
+ let tokenSum = 0;
621
629
  /** @type {string[]} */
622
630
  const hitTerms = [];
623
631
  for (const tok of tokens) {
@@ -626,6 +634,7 @@ export function scoreQuery(term, tokens, candidate) {
626
634
  if (h.score > strongest) strongest = h.score;
627
635
  matched++;
628
636
  hitTerms.push(tok);
637
+ tokenSum += h.score;
629
638
  }
630
639
  }
631
640
  // The reverse of the title tier, a step lower: the query holds a whole title
@@ -650,14 +659,25 @@ export function scoreQuery(term, tokens, candidate) {
650
659
  // (50 + bonus + coverage = 77) lost to thirty docs that each match
651
660
  // `integration` alone, by name or in a code tick (98-108). The reader asked for
652
661
  // both; a candidate that has both comes first, ordered among its peers by
653
- // how strong its strongest match is. It needs one keyword-strength hit:
662
+ // how strong its matches are. It needs one keyword-strength hit:
654
663
  // every word mentioned in prose, or rendered by a page, is breadth, and
655
664
  // stays on the token sum below an exact hit on one word.
665
+ //
666
+ // The TOTAL quality of matches orders candidates within this tier, not
667
+ // just the strongest single hit. A doc matching both words by keyword
668
+ // (90 + 90 = 180) outranks one matching keyword + prose (90 + 50 = 140).
669
+ // Before this, every all-word match whose strongest hit was a keyword (90)
670
+ // scored 157, burying the better match among dozens of ties.
656
671
  if (matched === tokens.length && strongest >= STRONG_TOKEN_SCORE) {
657
672
  return {
658
673
  score:
659
674
  FULL_COVERAGE_SCORE +
660
- Math.floor((strongest - MIN_TOKEN_SCORE) / 6.25),
675
+ Math.min(
676
+ Math.floor(
677
+ (tokenSum - matched * MIN_TOKEN_SCORE) / (matched * 5),
678
+ ),
679
+ 8,
680
+ ),
661
681
  reason,
662
682
  matched,
663
683
  total,
@@ -1463,6 +1483,33 @@ async function gatherTemplates(cwd) {
1463
1483
  });
1464
1484
  }
1465
1485
 
1486
+ /**
1487
+ * Build theme candidates from bundled and integration-provided themes. Without
1488
+ * this, an integration's themes are invisible to `search` even though
1489
+ * `theme list` and `discover` already resolve them.
1490
+ * @param {string} cwd
1491
+ * @returns {Promise<Candidate[]>}
1492
+ */
1493
+ async function gatherThemes(cwd) {
1494
+ let themes;
1495
+ try {
1496
+ themes = await listAvailableThemes(cwd);
1497
+ } catch {
1498
+ return [];
1499
+ }
1500
+ return themes.map(t => ({
1501
+ domain: 'theme',
1502
+ name: t.slug,
1503
+ keywords: [
1504
+ t.displayName,
1505
+ ...(t.description ? t.description.split(/[^A-Za-z0-9]+/).filter(w => w.length > 3) : []),
1506
+ ],
1507
+ description: t.description || '',
1508
+ _displayName: t.displayName,
1509
+ _package: t.package,
1510
+ }));
1511
+ }
1512
+
1466
1513
  /**
1467
1514
  * Map a scored candidate to its public, actionable result shape. Each result
1468
1515
  * carries enough to act on it: the domain, name, a one-line description, and
@@ -1519,6 +1566,14 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
1519
1566
  command: `astryx template ${c._commandName ?? c.name} --type ${c._kind}`,
1520
1567
  };
1521
1568
  break;
1569
+ case 'theme':
1570
+ result = {
1571
+ ...base,
1572
+ displayName: c._displayName,
1573
+ command: `astryx theme add ${c.name}`,
1574
+ ...(c._package ? {package: c._package} : {}),
1575
+ };
1576
+ break;
1522
1577
  default:
1523
1578
  result = base;
1524
1579
  }
@@ -1526,12 +1581,12 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
1526
1581
  }
1527
1582
 
1528
1583
  /**
1529
- * Unified ranked search across components, hooks, docs, and templates.
1584
+ * Unified ranked search across components, hooks, docs, templates, and themes.
1530
1585
  *
1531
1586
  * @param {string} query - Free-text search term.
1532
1587
  * @param {object} [options]
1533
1588
  * @param {string} [options.cwd]
1534
- * @param {'component'|'hook'|'doc'|'template'} [options.type] - Restrict to one domain.
1589
+ * @param {'component'|'hook'|'doc'|'template'|'theme'} [options.type] - Restrict to one domain.
1535
1590
  * @param {number} [options.limit] - Max results (default 20).
1536
1591
  * @returns {Promise<import('./search.type.mjs').SearchResponse>}
1537
1592
  */
@@ -1568,12 +1623,14 @@ export async function search(query, options = {}) {
1568
1623
  const term = String(query).trim().toLowerCase();
1569
1624
  const tokens = tokenizeQuery(term);
1570
1625
 
1571
- // `astryx docs` reads docs without @astryxdesign/core, so a docs-only
1572
- // search must too. Every other domain reads core: asked for by name, it is
1573
- // an error without core; an open search then covers the docs alone.
1574
- const docsOnly = type === 'doc';
1575
- const coreDir = docsOnly ? null : findCoreDir(cwd);
1576
- if (type && !docsOnly && !coreDir) {
1626
+ // `astryx docs` reads docs without @astryxdesign/core, and `astryx theme
1627
+ // list` reads themes without it (bundled themes need no project), so a
1628
+ // search of either must too. Every other domain reads core: asked for by
1629
+ // name, it is an error without core; an open search then covers the docs
1630
+ // and themes alone.
1631
+ const needsCore = !type || !CORELESS_DOMAINS.includes(type);
1632
+ const coreDir = needsCore ? findCoreDir(cwd) : null;
1633
+ if (type && needsCore && !coreDir) {
1577
1634
  throw new AstryxError(
1578
1635
  'Could not find @astryxdesign/core package',
1579
1636
  undefined,
@@ -1583,17 +1640,19 @@ export async function search(query, options = {}) {
1583
1640
 
1584
1641
  // Gather candidates from each requested domain in parallel.
1585
1642
  /** @param {string} d */
1586
- const wants = d => (!type && (coreDir != null || d === 'doc')) || type === d;
1587
- const [components, hooks, docTopics, templates] = await Promise.all([
1643
+ const wants = d =>
1644
+ (!type && (coreDir != null || CORELESS_DOMAINS.includes(d))) || type === d;
1645
+ const [components, hooks, docTopics, templates, themes] = await Promise.all([
1588
1646
  wants('component')
1589
1647
  ? gatherComponents(/** @type {string} */ (coreDir), cwd)
1590
1648
  : [],
1591
1649
  wants('hook') ? gatherHooks(/** @type {string} */ (coreDir)) : [],
1592
1650
  wants('doc') ? gatherDocs(cwd) : [],
1593
1651
  wants('template') ? gatherTemplates(cwd) : [],
1652
+ wants('theme') ? gatherThemes(cwd) : [],
1594
1653
  ]);
1595
1654
 
1596
- const all = [...components, ...hooks, ...docTopics, ...templates];
1655
+ const all = [...components, ...hooks, ...docTopics, ...templates, ...themes];
1597
1656
 
1598
1657
  // Score every candidate on its own merits. The consumer groups results by
1599
1658
  // role (page / block / component) and takes the top of each, so there's no
@@ -1610,7 +1669,7 @@ export async function search(query, options = {}) {
1610
1669
 
1611
1670
  // Sort by score desc, then domain (stable order), then name.
1612
1671
  /** @type {Record<string, number>} */
1613
- const domainOrder = {component: 0, hook: 1, doc: 2, template: 3};
1672
+ const domainOrder = {component: 0, hook: 1, doc: 2, template: 3, theme: 4};
1614
1673
  scored.sort(
1615
1674
  (a, b) =>
1616
1675
  b.score - a.score ||
@@ -75,7 +75,7 @@ describe('search leaf — envelope + ranking', () => {
75
75
  });
76
76
 
77
77
  describe('search leaf — per-domain result fields', () => {
78
- it('carries import for components and hooks, title for docs, displayName and kind for templates', async () => {
78
+ it('carries import for components and hooks, title for docs, displayName and kind for templates, displayName for themes', async () => {
79
79
  const r = await search('theme', {cwd, limit: 60});
80
80
  expect(new Set(r.data.results.map(res => res.domain))).toEqual(
81
81
  new Set(SEARCH_DOMAINS),
@@ -89,9 +89,12 @@ describe('search leaf — per-domain result fields', () => {
89
89
  expect(res.title).toMatch(/\S/);
90
90
  const read = `astryx docs ${res.name}`;
91
91
  expect([read, `${read} --index`, `${read} ${res.section}`]).toContain(res.command);
92
- } else {
92
+ } else if (res.domain === 'template') {
93
93
  expect(res.displayName).toMatch(/\S/);
94
94
  expect(['page', 'block']).toContain(res.kind);
95
+ } else if (res.domain === 'theme') {
96
+ expect(res.displayName).toMatch(/\S/);
97
+ expect(res.command).toMatch(/^astryx theme add /);
95
98
  }
96
99
  }
97
100
  }, SLOW);
@@ -397,11 +400,10 @@ describe('search leaf — a candidate that matches every word outranks a partial
397
400
  expect(score(q, all)).toBeLessThan(160);
398
401
  });
399
402
 
400
- // Among candidates that match every word, the stronger match should come
401
- // first. Today every all-word match with a keyword hit gets the same score,
402
- // so this records the order without enforcing it: it fails, as expected,
403
- // until the scoring tells the two apart.
404
- it.fails('ranks the stronger of two all-word matches first', () => {
403
+ // Among candidates that match every word, the stronger match comes first:
404
+ // the all-words tier uses total match quality (sum of token scores), not
405
+ // just the strongest, so an exact keyword outranks a stem-form keyword.
406
+ it('ranks the stronger of two all-word matches first', () => {
405
407
  const all = {name: 'x', keywords: ['alphas'], description: 'alpha beta gamma delta'};
406
408
  const q = 'alpha beta gamma delta';
407
409
  expect(score(q, {name: 'y', keywords: ['alpha'], description: 'beta gamma delta'})).toBeGreaterThan(
@@ -4,7 +4,7 @@
4
4
  /**
5
5
  * The domain a search result belongs to.
6
6
  */
7
- export type SearchDomain = "component" | "hook" | "doc" | "template";
7
+ export type SearchDomain = "component" | "hook" | "doc" | "template" | "theme";
8
8
  /**
9
9
  * A single ranked search result, tagged with its domain.
10
10
  */
@@ -14,7 +14,7 @@ export type SearchResultEntry = {
14
14
  */
15
15
  domain: SearchDomain;
16
16
  /**
17
- * - Primary identifier (component/hook name, doc topic or docs-tree route, template dir).
17
+ * - Primary identifier (component/hook name, doc topic or docs-tree route, template dir, theme slug).
18
18
  */
19
19
  name: string;
20
20
  /**
@@ -30,7 +30,7 @@ export type SearchResultEntry = {
30
30
  */
31
31
  description: string;
32
32
  /**
33
- * - Follow-up command to act on this result (e.g. `astryx component Button`).
33
+ * - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add neutral` for a theme).
34
34
  */
35
35
  command: string;
36
36
  /**
@@ -46,7 +46,7 @@ export type SearchResultEntry = {
46
46
  */
47
47
  section?: string | undefined;
48
48
  /**
49
- * - The npm package that authored a doc result; for a section, the package whose file the section came from.
49
+ * - The npm package that authored a doc result (for a section, the package whose file the section came from), or that ships a theme result.
50
50
  */
51
51
  package?: string | undefined;
52
52
  /**
@@ -54,7 +54,7 @@ export type SearchResultEntry = {
54
54
  */
55
55
  parent?: string | undefined;
56
56
  /**
57
- * - Friendly display name — present for template results.
57
+ * - Friendly display name — present for template and theme results.
58
58
  */
59
59
  displayName?: string | undefined;
60
60
  /**
@@ -9,24 +9,24 @@
9
9
 
10
10
  /**
11
11
  * The domain a search result belongs to.
12
- * @typedef {'component' | 'hook' | 'doc' | 'template'} SearchDomain
12
+ * @typedef {'component' | 'hook' | 'doc' | 'template' | 'theme'} SearchDomain
13
13
  */
14
14
 
15
15
  /**
16
16
  * A single ranked search result, tagged with its domain.
17
17
  * @typedef {object} SearchResultEntry
18
18
  * @property {SearchDomain} domain - Which content domain this result came from.
19
- * @property {string} name - Primary identifier (component/hook name, doc topic or docs-tree route, template dir).
19
+ * @property {string} name - Primary identifier (component/hook name, doc topic or docs-tree route, template dir, theme slug).
20
20
  * @property {number} score - Relevance score (higher is better).
21
21
  * @property {string} reason - Human-readable reason the candidate matched (e.g. `keyword "button"`).
22
22
  * @property {string} description - One-line description, when available.
23
- * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`).
23
+ * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add neutral` for a theme).
24
24
  * @property {string} [import] - Import path — present for component and hook results.
25
25
  * @property {string} [title] - Doc title — present for doc results.
26
26
  * @property {string} [section] - Section key — present when a doc result is one section of a topic; `command` reads only that section.
27
- * @property {string} [package] - The npm package that authored a doc result; for a section, the package whose file the section came from.
27
+ * @property {string} [package] - The npm package that authored a doc result (for a section, the package whose file the section came from), or that ships a theme result.
28
28
  * @property {string} [parent] - Command that opens the level above a doc result — its topic's section list for a section, the docs-tree namespace it sits in for a tree node — so a reader can see the siblings and open another.
29
- * @property {string} [displayName] - Friendly display name — present for template results.
29
+ * @property {string} [displayName] - Friendly display name — present for template and theme results.
30
30
  * @property {'page' | 'block'} [kind] - Template kind (`page` | `block`) — present for template results.
31
31
  */
32
32