Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): add discover command for external package discovery (#1080)

Joey1fd6abd032fa
diff --git a/packages/cli/package-lock.json b/packages/cli/package-lock.json
new file mode 100644
index 0000000000..767b759d34
--- /dev/null
+++ b/packages/cli/package-lock.json
@@ -0,0 +1,93 @@
+{
+ "name": "@xds/cli",
+ "version": "0.0.10",
+ "lockfileVersion": 2,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@xds/cli",
+ "version": "0.0.10",
+ "license": "MIT",
+ "dependencies": {
+ "@clack/prompts": "^0.9.1",
+ "commander": "^12.1.0"
+ },
+ "bin": {
+ "xds": "bin/xds.mjs"
+ }
+ },
+ "node_modules/@clack/core": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/@clack/core/-/core-0.4.1.tgz",
+ "integrity": "sha512-Pxhij4UXg8KSr7rPek6Zowm+5M22rbd2g1nfojHJkxp5YkFqiZ2+YLEM/XGVIzvGOcM0nqjIFxrpDwWRZYWYjA==",
+ "dependencies": {
+ "picocolors": "^1.0.0",
+ "sisteransi": "^1.0.5"
+ }
+ },
+ "node_modules/@clack/prompts": {
+ "version": "0.9.1",
+ "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-0.9.1.tgz",
+ "integrity": "sha512-JIpyaboYZeWYlyP0H+OoPPxd6nqueG/CmN6ixBiNFsIDHREevjIf0n0Ohh5gr5C8pEDknzgvz+pIJ8dMhzWIeg==",
+ "dependencies": {
+ "@clack/core": "0.4.1",
+ "picocolors": "^1.0.0",
+ "sisteransi": "^1.0.5"
+ }
+ },
+ "node_modules/commander": {
+ "version": "12.1.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",
+ "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="
+ },
+ "node_modules/sisteransi": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
+ "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="
+ }
+ },
+ "dependencies": {
+ "@clack/core": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/@clack/core/-/core-0.4.1.tgz",
+ "integrity": "sha512-Pxhij4UXg8KSr7rPek6Zowm+5M22rbd2g1nfojHJkxp5YkFqiZ2+YLEM/XGVIzvGOcM0nqjIFxrpDwWRZYWYjA==",
+ "requires": {
+ "picocolors": "^1.0.0",
+ "sisteransi": "^1.0.5"
+ }
+ },
+ "@clack/prompts": {
+ "version": "0.9.1",
+ "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-0.9.1.tgz",
+ "integrity": "sha512-JIpyaboYZeWYlyP0H+OoPPxd6nqueG/CmN6ixBiNFsIDHREevjIf0n0Ohh5gr5C8pEDknzgvz+pIJ8dMhzWIeg==",
+ "requires": {
+ "@clack/core": "0.4.1",
+ "picocolors": "^1.0.0",
+ "sisteransi": "^1.0.5"
+ }
+ },
+ "commander": {
+ "version": "12.1.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",
+ "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="
+ },
+ "picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="
+ },
+ "sisteransi": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
+ "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="
+ }
+ }
+}
diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjs
new file mode 100644
index 0000000000..d98b023150
--- /dev/null
+++ b/packages/cli/src/commands/discover.mjs
@@ -0,0 +1,298 @@
+/**
+ * @file discover command — find external XDS packages and components
+ *
+ * Usage:
+ * xds discover List all packages
+ * xds discover @scope/name List components in a package
+ * xds discover @scope/name/Component Show docs for a component
+ * xds discover searchterm Search across all packages
+ */
+
+import {loadConfig} from '../lib/config.mjs';
+import {scanAllPackages, findComponentInPackages} from '../lib/package-scanner.mjs';
+import {loadDocs} from '../lib/component-loader.mjs';
+import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';
+import {levenshteinDistance} from '../lib/string-utils.mjs';
+
+export function registerDiscover(program) {
+ program
+ .command('discover [query]')
+ .description('Discover external XDS packages and components')
+ .option('--components', 'List components only')
+ .action(async (query, options) => {
+ const config = await loadConfig();
+ const detail = program.opts().detail || 'full';
+
+ if (config.packages.length === 0) {
+ console.log('');
+ console.log('No package directories configured.');
+ console.log('');
+ console.log('Add a packages field to xds.config.mjs:');
+ console.log('');
+ console.log(' export default {');
+ console.log(" packages: ['/path/to/your/libs'],");
+ console.log(' };');
+ console.log('');
+ return;
+ }
+
+ const packages = scanAllPackages(config.packages);
+
+ if (packages.length === 0) {
+ console.log('');
+ console.log('No external XDS packages found.');
+ console.log('');
+ console.log('Packages opt in by adding an "xds" field to package.json:');
+ console.log('');
+ console.log(' {');
+ console.log(' "xds": {');
+ console.log(' "docs": "./src",');
+ console.log(' "category": "Common"');
+ console.log(' }');
+ console.log(' }');
+ console.log('');
+ return;
+ }
+
+ // No query: list all packages
+ if (!query) {
+ printPackageList(packages, options.components);
+ return;
+ }
+
+ // Starts with @: package navigation
+ if (query.startsWith('@')) {
+ const slashIdx = query.indexOf('/', query.indexOf('/') + 1);
+ if (slashIdx > 0) {
+ // @scope/name/Component
+ const pkgName = query.slice(0, slashIdx);
+ const compName = query.slice(slashIdx + 1);
+ await showComponentDocs(packages, compName, pkgName, program, detail);
+ } else {
+ // @scope/name — list that package
+ const pkg = packages.find(p => p.name === query);
+ if (!pkg) {
+ console.error('Package "' + query + '" not found.');
+ console.error('');
+ console.error('Available packages:');
+ for (const p of packages) {
+ console.error(' ' + p.name);
+ }
+ process.exit(1);
+ }
+ printSinglePackage(pkg);
+ }
+ return;
+ }
+
+ // No @: search across all packages
+ await searchComponents(packages, query, program, detail);
+ });
+}
+
+function printPackageList(packages, showComponents) {
+ console.log('');
+ for (const pkg of packages) {
+ const count = pkg.components.length;
+ const label = count === 1 ? 'component' : 'components';
+ console.log(pkg.name + ' (' + count + ' ' + label + ')');
+
+ if (showComponents) {
+ for (const comp of pkg.components) {
+ console.log(' ' + comp);
+ }
+ } else {
+ const maxShow = 10;
+ const shown = pkg.components.slice(0, maxShow);
+ const remaining = count - maxShow;
+ const list = shown.join(', ');
+ if (remaining > 0) {
+ console.log(' ' + list + ', +' + remaining + ' more');
+ } else {
+ console.log(' ' + list);
+ }
+ }
+ console.log('');
+ }
+ console.log('Usage:');
+ console.log(' xds discover <package> Browse a package');
+ console.log(' xds discover <package>/Component View component docs');
+ console.log(' xds discover <search> Search all packages');
+ console.log('');
+}
+
+function printSinglePackage(pkg) {
+ console.log('');
+ console.log(pkg.name + ' (' + pkg.components.length + ' components)');
+ console.log('');
+ for (const comp of pkg.components) {
+ console.log(' ' + comp);
+ }
+ console.log('');
+ console.log('Usage: xds discover ' + pkg.name + '/<ComponentName>');
+ console.log('');
+}
+
+async function showComponentDocs(packages, compName, pkgName, program, detail) {
+ const pkg = packages.find(p => p.name === pkgName);
+ if (!pkg) {
+ console.error('Package "' + pkgName + '" not found.');
+ process.exit(1);
+ }
+
+ const result = findComponentInPackages([pkg], compName);
+ if (!result) {
+ // Substring match first, then fuzzy
+ const substringHits = pkg.components.filter(
+ c => c.toLowerCase().includes(compName.toLowerCase()),
+ );
+ const suggestions = substringHits.length > 0
+ ? substringHits
+ : fuzzyMatch(compName, pkg.components);
+ if (suggestions.length > 0) {
+ console.error('Component "' + compName + '" not found in ' + pkgName + '.');
+ console.error('');
+ console.error('Did you mean?');
+ for (const s of suggestions) {
+ console.error(' xds discover ' + pkgName + '/' + s);
+ }
+ } else {
+ console.error('Component "' + compName + '" not found in ' + pkgName + '.');
+ console.error('');
+ console.error('Available: ' + pkg.components.join(', '));
+ }
+ process.exit(1);
+ }
+
+ await renderDocs(result, program, detail);
+}
+
+async function searchComponents(packages, query, program, detail) {
+ const lower = query.toLowerCase();
+
+ // Exact match first
+ const exact = findComponentInPackages(packages, query);
+ if (exact) {
+ console.log('Found: ' + exact.pkg.name + '/' + exact.componentName);
+ console.log('');
+ await renderDocs(exact, program, detail);
+ return;
+ }
+
+ // Substring match
+ const substringMatches = [];
+ for (const pkg of packages) {
+ for (const comp of pkg.components) {
+ if (comp.toLowerCase().includes(lower)) {
+ substringMatches.push({pkg, comp});
+ }
+ }
+ }
+
+ if (substringMatches.length === 1) {
+ const match = substringMatches[0];
+ const result = findComponentInPackages([match.pkg], match.comp);
+ if (result) {
+ console.log('Found: ' + match.pkg.name + '/' + match.comp);
+ console.log('');
+ await renderDocs(result, program, detail);
+ return;
+ }
+ }
+
+ if (substringMatches.length > 1) {
+ console.log('');
+ console.log('Found ' + substringMatches.length + ' matches for "' + query + '":');
+ console.log('');
+ for (const m of substringMatches) {
+ console.log(' xds discover ' + m.pkg.name + '/' + m.comp);
+ }
+ console.log('');
+ return;
+ }
+
+ // Fuzzy match across all packages
+ const allComponents = [];
+ for (const pkg of packages) {
+ for (const comp of pkg.components) {
+ allComponents.push({pkg, comp});
+ }
+ }
+ const fuzzyMatches = allComponents
+ .map(item => ({
+ ...item,
+ distance: levenshteinDistance(lower, item.comp.toLowerCase()),
+ }))
+ .filter(m => m.distance <= 3)
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, 5);
+
+ if (fuzzyMatches.length > 0) {
+ console.error('"' + query + '" not found. Did you mean?');
+ console.error('');
+ for (const m of fuzzyMatches) {
+ console.error(' xds discover ' + m.pkg.name + '/' + m.comp);
+ }
+ } else {
+ console.error('"' + query + '" not found in any package.');
+ console.error('');
+ console.error('Run xds discover to see available packages.');
+ }
+ process.exit(1);
+}
+
+function fuzzyMatch(name, components, maxDistance = 3) {
+ const lower = name.toLowerCase();
+ return components
+ .map(c => ({name: c, distance: levenshteinDistance(lower, c.toLowerCase())}))
+ .filter(m => m.distance <= maxDistance)
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, 5)
+ .map(m => m.name);
+}
+
+/**
+ * Validate that a docs object has the minimum required shape.
+ */
+function validateDocs(docs) {
+ if (!docs || typeof docs !== 'object') return 'docs export is missing or not an object';
+ if (typeof docs.name !== 'string' || !docs.name) return 'docs.name is missing or not a string';
+ if (typeof docs.description !== 'string') return 'docs.description is missing or not a string';
+ if (docs.props && !Array.isArray(docs.props)) return 'docs.props must be an array';
+ if (docs.components && !Array.isArray(docs.components)) return 'docs.components must be an array';
+ if (docs.examples && !Array.isArray(docs.examples)) return 'docs.examples must be an array';
+ if (docs.features && !Array.isArray(docs.features)) return 'docs.features must be an array';
+ return null;
+}
+
+async function renderDocs(result, program, detail) {
+ let docs;
+ try {
+ const zh = program.opts().zh || false;
+ const lang = program.opts().lang || null;
+ docs = await loadDocs(result.docPath, {zh, lang});
+ } catch (e) {
+ console.error('Failed to load docs for ' + result.componentName + ': ' + e.message);
+ console.error('File: ' + result.docPath);
+ process.exit(1);
+ }
+
+ const validationError = validateDocs(docs);
+ if (validationError) {
+ console.error('Invalid docs for ' + result.componentName + ': ' + validationError);
+ console.error('File: ' + result.docPath);
+ process.exit(1);
+ }
+
+ if (detail === 'brief') {
+ console.log(formatBrief(docs, result.componentName, result.pkg.name + '/' + result.componentName));
+ } else if (detail === 'compact') {
+ console.log(formatCompact(docs, result.componentName, result.pkg.name + '/' + result.componentName));
+ } else {
+ console.log(formatFull(docs));
+ }
+
+ console.log('');
+ console.log('Package: ' + result.pkg.name);
+ console.log('');
+}
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index b419965f81..648df5919d 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -65,6 +65,7 @@ const commands = [
{name: 'gap-report', path: './commands/gap-report.mjs', register: 'registerGapReport'},
{name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},
{name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},
+ {name: 'discover', path: './commands/discover.mjs', register: 'registerDiscover'},
];
for (const cmd of commands) {
diff --git a/packages/cli/src/lib/config.mjs b/packages/cli/src/lib/config.mjs
new file mode 100644
index 0000000000..78e251192f
--- /dev/null
+++ b/packages/cli/src/lib/config.mjs
@@ -0,0 +1,72 @@
+/**
+ * @file Config loader — reads xds.config.mjs from project root
+ *
+ * Walks up from cwd looking for xds.config.mjs.
+ * Returns the config object or defaults if not found.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+
+const DEFAULTS = {
+ packages: [],
+};
+
+/**
+ * Find xds.config.mjs by walking up from startDir.
+ * Returns the absolute path or null.
+ */
+export function findConfigPath(startDir = process.cwd()) {
+ let dir = startDir;
+ for (let i = 0; i < 10; i++) {
+ const candidate = path.join(dir, 'xds.config.mjs');
+ if (fs.existsSync(candidate)) return candidate;
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return null;
+}
+
+/**
+ * Load and return the config from xds.config.mjs.
+ * Returns defaults if no config file is found.
+ */
+export async function loadConfig(startDir = process.cwd()) {
+ const configPath = findConfigPath(startDir);
+ if (!configPath) return {...DEFAULTS};
+
+ try {
+ const mod = await import(pathToFileURL(configPath).href);
+ const config = mod.default || {};
+ return {
+ ...DEFAULTS,
+ ...config,
+ packages: normalizePackages(config.packages, path.dirname(configPath)),
+ };
+ } catch {
+ return {...DEFAULTS};
+ }
+}
+
+/**
+ * Normalize packages to an array of unique absolute paths.
+ * Filters out empty strings and non-string values.
+ * Relative paths resolved from config file directory.
+ * Deduplicates by resolved path.
+ */
+function normalizePackages(packages, configDir) {
+ if (!packages) return [];
+ const arr = Array.isArray(packages) ? packages : [packages];
+ const seen = new Set();
+ const result = [];
+ for (const p of arr) {
+ if (typeof p !== 'string' || p === '') continue;
+ const resolved = path.isAbsolute(p) ? p : path.resolve(configDir, p);
+ if (seen.has(resolved)) continue;
+ seen.add(resolved);
+ result.push(resolved);
+ }
+ return result;
+}
diff --git a/packages/cli/src/lib/package-scanner.mjs b/packages/cli/src/lib/package-scanner.mjs
new file mode 100644
index 0000000000..efe8c4c2e6
--- /dev/null
+++ b/packages/cli/src/lib/package-scanner.mjs
@@ -0,0 +1,89 @@
+/**
+ * @file Package scanner for config-based discovery
+ */
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+export function scanDirectory(scanDir) {
+ if (!fs.existsSync(scanDir)) return [];
+ const entries = fs.readdirSync(scanDir, {withFileTypes: true});
+ const packages = [];
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const pkgPath = path.join(scanDir, entry.name, 'package.json');
+ if (!fs.existsSync(pkgPath)) continue;
+ let pkg;
+ try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')); } catch { continue; }
+ if (!pkg.xds || !pkg.xds.docs) continue;
+ const pkgDir = path.join(scanDir, entry.name);
+ const docsDir = path.resolve(pkgDir, pkg.xds.docs);
+ const components = discoverDocComponents(docsDir);
+ if (components.length === 0) continue;
+ packages.push({
+ name: pkg.name || entry.name,
+ dir: pkgDir,
+ xds: pkg.xds,
+ category: pkg.xds.category || pkg.name || entry.name,
+ docsDir,
+ components,
+ });
+ }
+ return packages;
+}
+
+export function scanAllPackages(packageDirs) {
+ const all = [];
+ const seen = new Set();
+ for (const dir of packageDirs) {
+ for (const pkg of scanDirectory(dir)) {
+ if (seen.has(pkg.name)) continue;
+ seen.add(pkg.name);
+ all.push(pkg);
+ }
+ }
+ return all;
+}
+
+function discoverDocComponents(docsDir) {
+ if (!fs.existsSync(docsDir)) return [];
+ const components = [];
+ function walk(dir) {
+ let entries;
+ try { entries = fs.readdirSync(dir, {withFileTypes: true}); } catch { return; }
+ for (const entry of entries) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else if (entry.name.endsWith('.doc.mjs')) components.push(entry.name.replace('.doc.mjs', ''));
+ }
+ }
+ walk(docsDir);
+ return components.sort();
+}
+
+export function findComponentInPackages(packages, name) {
+ const lower = name.toLowerCase();
+ for (const pkg of packages) {
+ const match = pkg.components.find(c => c.toLowerCase() === lower);
+ if (!match) continue;
+ const docPath = findDocFile(pkg.docsDir, match);
+ if (docPath) return {pkg, docPath, componentName: match};
+ }
+ return null;
+}
+
+function findDocFile(docsDir, name) {
+ const target = name + '.doc.mjs';
+ function walk(dir) {
+ let entries;
+ try { entries = fs.readdirSync(dir, {withFileTypes: true}); } catch { return null; }
+ for (const entry of entries) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) { const f = walk(full); if (f) return f; }
+ else if (entry.name === target) return full;
+ }
+ return null;
+ }
+ return walk(docsDir);
+}