An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): unified search across components, hooks, docs, and templates (#2564)
Joey9888b6e4405e
diff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjsindex b7b880e597..a3b89de1ec 100644--- a/.github/scripts/api-cli-parity-test.mjs+++ b/.github/scripts/api-cli-parity-test.mjs@@ -181,6 +181,18 @@ if (hookSample) {add('hook NotARealHook99', ['hook', 'NotARealHook99'],() => apiCall(api.hook, 'NotARealHook99', {cwd: ROOT}));+// Search — unified ranked search across all content domains+add('search button', ['search', 'button'],+ () => apiCall(api.search, 'button', {cwd: ROOT}));+add('search button --limit 5', ['search', 'button', '--limit', '5'],+ () => apiCall(api.search, 'button', {limit: 5, cwd: ROOT}));+add('search modal --type component', ['search', 'modal', '--type', 'component'],+ () => apiCall(api.search, 'modal', {type: 'component', cwd: ROOT}));+add('search (no match)', ['search', 'zzqqxx_no_match'],+ () => apiCall(api.search, 'zzqqxx_no_match', {cwd: ROOT}));+add('search (bad type)', ['search', 'x', '--type', 'bogus'],+ () => apiCall(api.search, 'x', {type: 'bogus', cwd: ROOT}));+// Other commands — probe with safe read-only args (no API yet)const otherCommands = [['swizzle', '--list'],diff --git a/packages/cli/README.md b/packages/cli/README.mdindex fbbcdd8399..f33fff16f8 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -4,18 +4,57 @@ The CLI is the primary interface for working with the design system — for huma```bashnpx xds --help+npx xds search buttonnpx xds component Buttonnpx xds docs tokensnpx xds docs migrationnpx xds template --list```+### Finding things — `xds search`++When you don't know whether what you need is a component, a hook, a docs topic,+or a template, search across all of them at once. Results are ranked by+relevance (name and keyword matches outrank incidental prose mentions, with+fuzzy matching for typos) and tagged with their domain plus the follow-up+command to run:++```bash+$ npx xds search button++Results for "button" (20):++ [component] Button+ Button triggers an action when clicked. Use it for form submissions…+ → npx xds component Button++ [component] IconButton+ A button that shows only an icon with no visible text…+ → npx xds component IconButton++ [hook] useClickableContainer+ Makes a container element clickable while preserving nested…+ → npx xds hook useClickableContainer++ [template] Banner — Collapsible+ Combine an action button, dismiss control, and expandable detail area…+ → npx xds template BannerCollapsibleContent+```++Options:++- `--type <component|hook|doc|template>` — restrict to a single domain+- `--limit <n>` — cap the number of results (default 20)+- `--detail` — include the import path and the match reason/score+- `--json` — typed `{ type: 'search', data: { query, results } }` envelope+## Commands| Command | Description || ------------- | --------------------------------------------------------------------------------------- || `init` | Initialize the design system in your project — installs packages, sets up theming, adds AI agent docs || `component` | List components or print detailed docs, props, usage examples, and source |+| `search` | Find components, hooks, docs, and templates in one ranked, cross-domain result set || `docs` | Print reference documentation (tokens, theme, color, typography, spacing, etc.) || `template` | Inject page or block templates into your project || `hook` | List hooks and print hook documentation |@@ -57,7 +96,7 @@ Errors:The same logic that powers `xds --json` is available as importable, type-safe functions:```typescript-import {component, docs, discover, template, hook, XDSError} from '@xds/cli/api';+import {component, docs, discover, template, hook, search, XDSError} from '@xds/cli/api';// Same result as: xds --json component Buttonconst btn = await component('Button');@@ -141,6 +180,7 @@ Every response has a `type` string that uniquely identifies it:| `xds --json hook --list --detail full` | `hook.full` | `HookFullResponse` || `xds --json hook <name>` | `hook.detail` | `HookDetailResponse` || `xds --json hook <name> --params` | `hook.detail.params` | `HookDetailParamsResponse` |+| `xds --json search <query>` | `search` | `SearchResponse` || `xds --json swizzle [--list]` | `swizzle.list` | `SwizzleListResponse` || `xds --json swizzle <component>` | `swizzle.copy` | `SwizzleCopyResponse` || `xds --json theme build <file>` | `theme.build` | `ThemeBuildResponse` |diff --git a/packages/cli/src/api/index.mjs b/packages/cli/src/api/index.mjsindex 39fcaccb2a..ffdaacec7c 100644--- a/packages/cli/src/api/index.mjs+++ b/packages/cli/src/api/index.mjs@@ -24,4 +24,5 @@ export {docs} from './docs.mjs';export {discover} from './discover.mjs';export {template} from './template.mjs';export {hook} from './hook.mjs';+export {search} from './search.mjs';export {XDSError} from './error.mjs';diff --git a/packages/cli/src/api/search.mjs b/packages/cli/src/api/search.mjsnew file mode 100644index 0000000000..4cf85e4fbf--- /dev/null+++ b/packages/cli/src/api/search.mjs@@ -0,0 +1,363 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Programmatic API for the unified `search` command.+ *+ * Returns the same typed envelope { type, data } that `xds --json search`+ * outputs. The CLI command handler is a thin wrapper around this function.+ *+ * `search(query)` is the single "I'm looking for X" entry point across ALL+ * content domains — components, hooks, docs topics, and templates (page ++ * block). Today, finding the right thing requires four separate list calls+ * (`component --list`, `hook --list`, `docs`, `template --list`) plus manual+ * scanning; this collapses them into one ranked, typed result set.+ *+ * Scoring is keyword + fuzzy ranking (NOT semantic / embeddings — that is a+ * deliberate future follow-up). It reuses the same signal weighting as the+ * component fuzzy resolver in lib/string-utils.mjs:+ *+ * 100 exact name match+ * 90 exact keyword match+ * 80 name Levenshtein distance 1+ * 70 keyword substring / distance 1+ * 60 name substring (>=4 chars, >=50% coverage)+ * 50 description / prose mentions the term+ * 40 name Levenshtein distance 2+ * 30 keyword Levenshtein distance 2+ * 20 name Levenshtein distance 3+ *+ * Name + keyword signals always outweigh description/prose, so an exact match+ * sorts above an incidental mention.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {pathToFileURL} from 'node:url';+import {findCoreDir, CLI_ROOT} from '../utils/paths.mjs';+import {+ discoverComponents,+ findComponentReadme,+ resolveImportPath,+} from '../lib/component-discovery.mjs';+import {discoverHooks, findHookDoc} from '../lib/hook-discovery.mjs';+import {levenshteinDistance} from '../lib/string-utils.mjs';+import {discoverTemplates} from './template.mjs';+import {XDSError} from './error.mjs';++const DOCS_DIR = path.join(CLI_ROOT, 'docs');++/** Valid domain filters for `--type`. */+export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template'];++/**+ * Score a single candidate against the search term across name, keywords,+ * and prose signals. Returns the best (highest) score plus a human reason,+ * or null if nothing matched above the floor.+ *+ * @param {string} term - Lowercased search term.+ * @param {object} candidate+ * @param {string} candidate.name - Primary identifier (component/hook name, topic, template name).+ * @param {string[]} [candidate.keywords]+ * @param {string} [candidate.description]+ * @param {string[]} [candidate.prose] - Extra free-text blobs (doc section text, best practices).+ * @returns {{score: number, reason: string} | null}+ */+export function scoreCandidate(term, {name, keywords = [], description = '', prose = []}) {+ let best = 0;+ let reason = '';+ const consider = (score, why) => {+ if (score > best) {+ best = score;+ reason = why;+ }+ };++ const nameLower = name.toLowerCase();++ // ── Name signals ────────────────────────────────────────────────+ if (nameLower === term) {+ consider(100, 'exact name');+ } else {+ // Substring (both directions), min 4 chars, >=50% coverage.+ const shorter = term.length < nameLower.length ? term : nameLower;+ const longer = term.length < nameLower.length ? nameLower : term;+ if (shorter.length >= 4 && longer.includes(shorter) && shorter.length / longer.length >= 0.5) {+ consider(60, `name contains "${shorter}"`);+ }+ const dist = levenshteinDistance(term, nameLower);+ if (dist === 1) consider(80, `similar name (distance ${dist})`);+ else if (dist === 2) consider(40, `similar name (distance ${dist})`);+ else if (dist === 3) consider(20, `similar name (distance ${dist})`);+ }++ // ── Keyword signals ─────────────────────────────────────────────+ for (const kw of keywords) {+ const kwLower = String(kw).toLowerCase();+ if (kwLower === term) {+ consider(90, `keyword "${kw}"`);+ continue;+ }+ const s = term.length < kwLower.length ? term : kwLower;+ const l = term.length < kwLower.length ? kwLower : term;+ if (s.length >= 4 && l.includes(s) && s.length / l.length >= 0.5) {+ consider(70, `keyword "${kw}"`);+ }+ const dist = levenshteinDistance(term, kwLower);+ if (dist === 1) consider(70, `keyword "${kw}" (distance ${dist})`);+ else if (dist === 2) consider(30, `keyword "${kw}" (distance ${dist})`);+ }++ // ── Prose / description signals (whole-word boundary) ───────────+ if (term.length >= 3) {+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const re = new RegExp(`\\b${escaped}\\b`);+ if (description && re.test(description.toLowerCase())) {+ consider(50, `description mentions "${term}"`);+ } else {+ for (const blob of prose) {+ if (blob && re.test(String(blob).toLowerCase())) {+ consider(50, `docs mention "${term}"`);+ break;+ }+ }+ }+ }++ return best > 0 ? {score: best, reason} : null;+}++/** Load a doc module's `docs`/`doc` export, swallowing errors. */+async function loadModuleDoc(docPath, exportName = 'docs') {+ try {+ const mod = await import(pathToFileURL(docPath).href);+ return mod[exportName] ?? null;+ } catch {+ return null;+ }+}++/**+ * Build component candidates: name + keywords + usage/description from the+ * component's .doc.mjs.+ * @param {string} coreDir+ */+async function gatherComponents(coreDir) {+ const grouped = discoverComponents(coreDir);+ const names = Object.values(grouped).flat();+ const candidates = [];+ for (const comp of names) {+ const readme = findComponentReadme(coreDir, comp);+ let keywords = [];+ let description = '';+ if (readme && readme.endsWith('.doc.mjs')) {+ const doc = await loadModuleDoc(readme);+ if (doc) {+ keywords = Array.isArray(doc.keywords) ? doc.keywords : [];+ description = doc.usage?.description || doc.description || '';+ }+ }+ candidates.push({+ domain: 'component',+ name: comp,+ keywords,+ description,+ _import: resolveImportPath(coreDir, comp),+ });+ }+ return candidates;+}++/**+ * Build hook candidates: name + keywords + usage/description from the hook's+ * .doc.mjs.+ * @param {string} coreDir+ */+async function gatherHooks(coreDir) {+ const grouped = discoverHooks(coreDir);+ const names = Object.values(grouped).flat();+ const candidates = [];+ for (const hookName of names) {+ const docPath = findHookDoc(coreDir, hookName);+ let keywords = [];+ let description = '';+ let importPath = '@xds/core/hooks';+ if (docPath) {+ const doc = await loadModuleDoc(docPath);+ if (doc) {+ keywords = Array.isArray(doc.keywords) ? doc.keywords : [];+ description = doc.usage?.description || doc.description || '';+ importPath = doc.importPath || importPath;+ }+ }+ candidates.push({+ domain: 'hook',+ name: hookName,+ keywords,+ description,+ _import: importPath,+ });+ }+ return candidates;+}++/** Build doc-topic candidates: topic name + description + section prose. */+async function gatherDocs() {+ if (!fs.existsSync(DOCS_DIR)) return [];+ const candidates = [];+ for (const file of fs.readdirSync(DOCS_DIR)) {+ const match = file.match(/^([\w-]+)\.doc\.mjs$/);+ if (!match) continue;+ const topic = match[1];+ const doc = await loadModuleDoc(path.join(DOCS_DIR, file));+ let description = '';+ const prose = [];+ if (doc) {+ description = doc.description || '';+ for (const section of doc.sections || []) {+ if (section.title) prose.push(section.title);+ for (const block of section.content || []) {+ if (block.type === 'prose' && block.text) prose.push(block.text);+ }+ }+ }+ candidates.push({+ domain: 'doc',+ name: topic,+ keywords: [],+ description,+ prose,+ _title: doc?.title || topic,+ });+ }+ return candidates;+}++/** Build template candidates (page + block) from the template discovery API. */+async function gatherTemplates(cwd) {+ let templates = [];+ try {+ templates = await discoverTemplates(cwd);+ } catch {+ return [];+ }+ return templates.map(t => ({+ domain: 'template',+ name: t.dirName,+ keywords: Array.isArray(t.componentsUsed) ? t.componentsUsed : [],+ description: t.description || '',+ _displayName: t.name,+ _kind: t.type, // 'page' | 'block'+ }));+}++/**+ * Map a scored candidate to its public, actionable result shape. Each result+ * carries enough to act on it: the domain, name, a one-line description, and+ * the follow-up command (and import path where relevant).+ *+ * @param {object} c - candidate+ * @param {number} score+ * @param {string} reason+ */+function toResult(c, score, reason) {+ const base = {+ domain: c.domain,+ name: c.name,+ score,+ reason,+ description: c.description || '',+ };+ switch (c.domain) {+ case 'component':+ return {+ ...base,+ import: c._import,+ command: `xds component ${c.name}`,+ };+ case 'hook':+ return {+ ...base,+ import: c._import,+ command: `xds hook ${c.name}`,+ };+ case 'doc':+ return {+ ...base,+ title: c._title,+ command: `xds docs ${c.name}`,+ };+ case 'template':+ return {+ ...base,+ displayName: c._displayName,+ kind: c._kind,+ command: `xds template ${c.name}`,+ };+ default:+ return base;+ }+}++/**+ * Unified ranked search across components, hooks, docs, and templates.+ *+ * @param {string} query - Free-text search term.+ * @param {object} [options]+ * @param {string} [options.cwd]+ * @param {'component'|'hook'|'doc'|'template'} [options.type] - Restrict to one domain.+ * @param {number} [options.limit] - Max results (default 20).+ * @returns {Promise<{type: 'search', data: {query: string, results: Array<object>}}>}+ */+export async function search(query, options = {}) {+ const {cwd = process.cwd(), type, limit = 20} = options;++ if (!query || !String(query).trim()) {+ throw new XDSError('A search query is required', [+ {name: 'xds search button', reason: 'example'},+ ]);+ }++ if (type && !SEARCH_DOMAINS.includes(type)) {+ throw new XDSError(+ `Unknown --type "${type}"`,+ SEARCH_DOMAINS.map(d => ({name: d, reason: 'valid type'})),+ );+ }++ const term = String(query).trim().toLowerCase();++ const coreDir = findCoreDir(cwd);+ if (!coreDir) {+ throw new XDSError('Could not find @xds/core package');+ }++ // Gather candidates from each requested domain in parallel.+ const wants = d => !type || type === d;+ const [components, hooks, docTopics, templates] = await Promise.all([+ wants('component') ? gatherComponents(coreDir) : [],+ wants('hook') ? gatherHooks(coreDir) : [],+ wants('doc') ? gatherDocs() : [],+ wants('template') ? gatherTemplates(cwd) : [],+ ]);++ const all = [...components, ...hooks, ...docTopics, ...templates];++ const scored = [];+ for (const candidate of all) {+ const hit = scoreCandidate(term, candidate);+ if (hit) scored.push(toResult(candidate, hit.score, hit.reason));+ }++ // Sort by score desc, then domain (stable order), then name.+ const domainOrder = {component: 0, hook: 1, doc: 2, template: 3};+ scored.sort(+ (a, b) =>+ b.score - a.score ||+ (domainOrder[a.domain] ?? 9) - (domainOrder[b.domain] ?? 9) ||+ a.name.localeCompare(b.name),+ );++ const limited = limit > 0 ? scored.slice(0, limit) : scored;++ return {type: 'search', data: {query: String(query).trim(), results: limited}};+}diff --git a/packages/cli/src/commands/search.mjs b/packages/cli/src/commands/search.mjsnew file mode 100644index 0000000000..85f8c88e76--- /dev/null+++ b/packages/cli/src/commands/search.mjs@@ -0,0 +1,100 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file search command — unified ranked search across all content domains.+ *+ * One "I'm looking for X" entry point spanning components, hooks, docs topics,+ * and templates (page + block). Results are ranked by relevance and tagged+ * with their domain, with a follow-up command so the user knows what to run+ * next.+ *+ * Usage:+ * xds search button Ranked results across all domains+ * xds search modal --type component Filter to a single domain+ * xds search forms --limit 5 Cap the result count+ * xds search button --detail Verbose (include import / reason)+ * xds search button --json Typed JSON envelope+ */++import {getRunPrefix} from '../utils/package-manager.mjs';+import {jsonOut, humanLog} from '../lib/json.mjs';+import {cliError} from '../lib/cli-error.mjs';+import {search as searchApi, SEARCH_DOMAINS} from '../api/search.mjs';++const DOMAIN_LABEL = {+ component: 'component',+ hook: 'hook',+ doc: 'docs',+ template: 'template',+};++export function registerSearch(program) {+ program+ .command('search <query>')+ .description('Search components, hooks, docs, and templates in one ranked list')+ .option('--type <domain>', `Filter to one domain (${SEARCH_DOMAINS.join('|')})`)+ .option('--limit <n>', 'Max number of results (default 20)')+ .option('--detail', 'Verbose output (include import paths and match reason)')+ .action(async (query, options) => {+ const json = program.opts().json || false;++ let limit = 20;+ if (options.limit != null) {+ const parsed = Number.parseInt(options.limit, 10);+ if (!Number.isFinite(parsed) || parsed <= 0) {+ cliError(`Invalid --limit value "${options.limit}". Must be a positive integer.`);+ return;+ }+ limit = parsed;+ }++ let result;+ try {+ result = await searchApi(query, {+ cwd: process.cwd(),+ type: options.type,+ limit,+ });+ } catch (e) {+ cliError(e.message, {suggestions: e.suggestions});+ return;+ }++ if (json) return jsonOut(result.type, result.data);++ // ── Text output ──────────────────────────────────────────────+ const run = getRunPrefix();+ const {query: q, results} = result.data;++ // No matches is a valid, successful outcome — clean message, exit 0.+ if (results.length === 0) {+ humanLog('');+ humanLog(`No results for "${q}".`);+ humanLog('');+ humanLog(`Try a broader term, or browse: ${run} xds component --list`);+ humanLog('');+ return;+ }++ humanLog('');+ humanLog(`Results for "${q}" (${results.length}):`);+ humanLog('');+ for (const r of results) {+ const tag = `[${DOMAIN_LABEL[r.domain] || r.domain}]`.padEnd(12);+ const display = r.domain === 'template' && r.displayName ? r.displayName : r.name;+ humanLog(` ${tag} ${display}`);+ if (r.description) {+ humanLog(` ${r.description}`);+ }+ humanLog(` → ${run} ${r.command}`);+ if (options.detail) {+ if (r.import) humanLog(` import: ${r.import}`);+ humanLog(` match: ${r.reason} (score ${r.score})`);+ }+ humanLog('');+ }+ });+}++// Re-export the API for external consumers.+export {search, SEARCH_DOMAINS} from '../api/search.mjs';diff --git a/packages/cli/src/commands/search.test.mjs b/packages/cli/src/commands/search.test.mjsnew file mode 100644index 0000000000..52dfa78373--- /dev/null+++ b/packages/cli/src/commands/search.test.mjs@@ -0,0 +1,202 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tests for the unified `search` command + its programmatic API.+ *+ * Two layers:+ * 1. API-level (direct import of api/search.mjs) — ranking, cross-domain+ * results, --type/--limit, typo tolerance, empty results, envelope shape.+ * 2. CLI-level (spawned subprocess) — exit codes and the --json contract,+ * which only fire through a real Commander .parse() against argv.+ */++import {describe, it, expect} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {search, scoreCandidate, SEARCH_DOMAINS} from '../api/search.mjs';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');+// Run against the monorepo root so @xds/core is discoverable.+const REPO_ROOT = path.resolve(__dirname, '../../../..');+const OPTS = {cwd: REPO_ROOT};++function runCli(args) {+ const res = spawnSync('node', [CLI_BIN, ...args], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ timeout: 30_000,+ });+ return {status: res.status, stdout: res.stdout || '', stderr: res.stderr || ''};+}++describe('search() API — ranking', () => {+ it('ranks an exact component name match first', async () => {+ const {data} = await search('button', OPTS);+ expect(data.results.length).toBeGreaterThan(0);+ const top = data.results[0];+ expect(top.domain).toBe('component');+ expect(top.name).toBe('Button');+ expect(top.score).toBe(100);+ expect(top.command).toBe('xds component Button');+ });++ it('returns components/hooks tagged with a matching keyword', async () => {+ const {data} = await search('button', OPTS);+ // IconButton carries the "button" keyword; should be present and scored+ // on a keyword (not name) signal.+ const iconButton = data.results.find(r => r.name === 'IconButton');+ expect(iconButton).toBeTruthy();+ expect(iconButton.domain).toBe('component');+ expect(iconButton.score).toBeGreaterThanOrEqual(70);+ expect(iconButton.reason.toLowerCase()).toContain('keyword');+ });+});++describe('search() API — cross-domain', () => {+ it('returns results from more than one domain for a broad query', async () => {+ const {data} = await search('color', OPTS);+ const domains = new Set(data.results.map(r => r.domain));+ // "color" is a doc topic AND appears across components.+ expect(domains.has('doc')).toBe(true);+ expect(domains.size).toBeGreaterThan(1);+ // The doc topic should carry a follow-up `xds docs` command.+ const docHit = data.results.find(r => r.domain === 'doc');+ expect(docHit.command.startsWith('xds docs ')).toBe(true);+ });++ it('every result is tagged with a known domain and a command', async () => {+ const {data} = await search('button', OPTS);+ for (const r of data.results) {+ expect(SEARCH_DOMAINS).toContain(r.domain);+ expect(typeof r.command).toBe('string');+ expect(r.command.length).toBeGreaterThan(0);+ }+ });+});++describe('search() API — filters', () => {+ it('--type component returns only components', async () => {+ const {data} = await search('modal', {...OPTS, type: 'component'});+ expect(data.results.length).toBeGreaterThan(0);+ for (const r of data.results) {+ expect(r.domain).toBe('component');+ }+ });++ it('--type doc returns only docs', async () => {+ const {data} = await search('color', {...OPTS, type: 'doc'});+ for (const r of data.results) {+ expect(r.domain).toBe('doc');+ }+ });++ it('respects --limit', async () => {+ const {data} = await search('button', {...OPTS, limit: 3});+ expect(data.results.length).toBeLessThanOrEqual(3);+ });++ it('rejects an unknown --type', async () => {+ await expect(search('x', {...OPTS, type: 'bogus'})).rejects.toThrow(/Unknown --type/);+ });+});++describe('search() API — fuzzy / typo tolerance', () => {+ it('finds Button for the typo "buton"', async () => {+ const {data} = await search('buton', OPTS);+ const button = data.results.find(r => r.name === 'Button');+ expect(button).toBeTruthy();+ expect(button.domain).toBe('component');+ });+});++describe('search() API — empty + envelope', () => {+ it('returns an empty result set (not an error) for a no-match query', async () => {+ const {type, data} = await search('zzqqxx_definitely_no_match', OPTS);+ expect(type).toBe('search');+ expect(data.results).toEqual([]);+ expect(data.query).toBe('zzqqxx_definitely_no_match');+ });++ it('throws when the query is empty', async () => {+ await expect(search('', OPTS)).rejects.toThrow(/query is required/);+ });++ it('returns the correct envelope shape', async () => {+ const result = await search('button', OPTS);+ expect(result.type).toBe('search');+ expect(result.data).toHaveProperty('query');+ expect(Array.isArray(result.data.results)).toBe(true);+ const top = result.data.results[0];+ expect(top).toHaveProperty('domain');+ expect(top).toHaveProperty('name');+ expect(top).toHaveProperty('score');+ expect(top).toHaveProperty('description');+ expect(top).toHaveProperty('command');+ });+});++describe('scoreCandidate()', () => {+ it('scores an exact name match at 100', () => {+ expect(scoreCandidate('button', {name: 'button'}).score).toBe(100);+ });++ it('scores an exact keyword above a description mention', () => {+ const kw = scoreCandidate('toggle', {name: 'Switch', keywords: ['toggle']});+ const desc = scoreCandidate('toggle', {name: 'Switch', description: 'A toggle control'});+ expect(kw.score).toBeGreaterThan(desc.score);+ });++ it('returns null when nothing matches', () => {+ expect(scoreCandidate('zzzz', {name: 'Button', keywords: ['cta']})).toBeNull();+ });+});++describe('search CLI — exit codes + JSON contract', () => {+ it('exits 0 for a successful search', () => {+ const r = runCli(['search', 'button']);+ expect(r.status).toBe(0);+ });++ it('exits 0 for a no-match query (valid empty result, not failure)', () => {+ const r = runCli(['search', 'zzqqxx_no_match']);+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('No results');+ });++ it('exits 1 for an invalid --type', () => {+ const r = runCli(['search', 'x', '--type', 'bogus']);+ expect(r.status).toBe(1);+ });++ it('exits 1 for an invalid --limit', () => {+ const r = runCli(['search', 'x', '--limit', '0']);+ expect(r.status).toBe(1);+ });++ it('emits a valid --json envelope', () => {+ const r = runCli(['--json', 'search', 'button']);+ expect(r.status).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.type).toBe('search');+ expect(parsed.data.query).toBe('button');+ expect(Array.isArray(parsed.data.results)).toBe(true);+ expect(parsed.data.results[0].name).toBe('Button');+ });++ it('emits a valid --json envelope with empty results for no match', () => {+ const r = runCli(['--json', 'search', 'zzqqxx_no_match']);+ expect(r.status).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.type).toBe('search');+ expect(parsed.data.results).toEqual([]);+ });++ it('shows the follow-up command hint in human output', () => {+ const r = runCli(['search', 'button']);+ expect(r.stdout).toContain('xds component Button');+ expect(r.stdout).toContain('[component]');+ });+});diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjsindex bf916c8f9b..c3b8ee8c04 100644--- a/packages/cli/src/index.mjs+++ b/packages/cli/src/index.mjs@@ -52,6 +52,7 @@ export const JSON_SUPPORTED = new Set(['component','docs','discover',+ 'search','swizzle','template','hook',@@ -119,7 +120,7 @@ programname: 'xds',version: pkg.version,commands: [- 'component', 'docs', 'discover', 'swizzle', 'template',+ 'component', 'docs', 'discover', 'search', 'swizzle', 'template','hook', 'theme', 'gap-report', 'upgrade', 'init',],jsonSupported: [...JSON_SUPPORTED].sort(),@@ -228,6 +229,7 @@ const commands = [{name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},{name: 'hook', path: './commands/hook/index.mjs', register: 'registerHook'},{name: 'discover', path: './commands/discover.mjs', register: 'registerDiscover'},+ {name: 'search', path: './commands/search.mjs', register: 'registerSearch'},];for (const cmd of commands) {diff --git a/packages/cli/src/types/api.d.ts b/packages/cli/src/types/api.d.tsindex 0641c370b7..c7779ece56 100644--- a/packages/cli/src/types/api.d.ts+++ b/packages/cli/src/types/api.d.ts@@ -41,6 +41,7 @@ import type {HookDetailResponse,HookDetailParamsResponse,} from './hook';+import type {SearchResponse, SearchDomain} from './search';/** Structured API error with optional suggestions. */export declare class XDSError extends Error {@@ -167,3 +168,16 @@ export declare function hook(name?: string,options?: HookOptions,): Promise<HookResult>;++// ── Search ───────────────────────────────────────────────────────────++export interface SearchOptions {+ cwd?: string;+ type?: SearchDomain;+ limit?: number;+}++export declare function search(+ query: string,+ options?: SearchOptions,+): Promise<SearchResponse>;diff --git a/packages/cli/src/types/base.d.ts b/packages/cli/src/types/base.d.tsindex 4766c28039..f7e95736f7 100644--- a/packages/cli/src/types/base.d.ts+++ b/packages/cli/src/types/base.d.ts@@ -48,6 +48,7 @@ import type {GapReportCategoriesResponse,GapReportFileResponse,} from './gap-report';+import type {SearchResponse} from './search';/** Structured error. Check `'error' in result` to discriminate. */export interface CLIError {@@ -94,7 +95,8 @@ export type CLIAnyResponse =| UpgradeListResponse| UpgradeRunResponse| GapReportCategoriesResponse- | GapReportFileResponse;+ | GapReportFileResponse+ | SearchResponse;/** Union of all type discriminator string literals. */export type CLIResponseType = CLIAnyResponse['type'];diff --git a/packages/cli/src/types/index.d.ts b/packages/cli/src/types/index.d.tsindex db1e211255..8ac76d040d 100644--- a/packages/cli/src/types/index.d.ts+++ b/packages/cli/src/types/index.d.ts@@ -10,3 +10,4 @@ export * from './swizzle';export * from './theme';export * from './gap-report';export * from './upgrade';+export * from './search';diff --git a/packages/cli/src/types/search.d.ts b/packages/cli/src/types/search.d.tsnew file mode 100644index 0000000000..6b9fb8cf77--- /dev/null+++ b/packages/cli/src/types/search.d.ts@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Search command JSON responses.+ *+ * `xds search <query>` returns a single ranked, typed result set spanning all+ * content domains — components, hooks, docs topics, and templates. Scoring is+ * keyword + fuzzy ranking (not semantic / embeddings).+ *+ * Invocation -> type discriminator+ * ------------------------------------------------------------------+ * xds --json search button -> search+ * xds --json search modal --type component -> search (filtered)+ * xds --json search forms --limit 5 -> search (capped)+ * xds --json search zzznomatch -> search (empty results, exit 0)+ * (no query) -> CLIError+ */++/** The domain a search result belongs to. */+export type SearchDomain = 'component' | 'hook' | 'doc' | 'template';++/** A single ranked search result, tagged with its domain. */+export interface SearchResultEntry {+ /** Which content domain this result came from. */+ domain: SearchDomain;+ /** Primary identifier (component/hook name, doc topic, template dir). */+ name: string;+ /** Relevance score (higher is better). */+ score: number;+ /** Human-readable reason the candidate matched (e.g. `keyword "button"`). */+ reason: string;+ /** One-line description, when available. */+ description: string;+ /** Follow-up command to act on this result (e.g. `xds component Button`). */+ command: string;+ /** Import path — present for component and hook results. */+ import?: string;+ /** Doc title — present for doc results. */+ title?: string;+ /** Friendly display name — present for template results. */+ displayName?: string;+ /** Template kind (`page` | `block`) — present for template results. */+ kind?: 'page' | 'block';+}++/** xds --json search <query> */+export interface SearchResponse {+ type: 'search';+ data: {+ query: string;+ results: SearchResultEntry[];+ };+}