An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): add @xds/cli/api — programmatic API with same code path as CLI (#1208)
Joey03d16941f6c8
diff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjsnew file mode 100644index 0000000000..deed580dc2--- /dev/null+++ b/.github/scripts/api-cli-parity-test.mjs@@ -0,0 +1,287 @@+#!/usr/bin/env node+/**+ * API ↔ CLI parity test.+ *+ * Auto-discovers every component, doc topic, and CLI command,+ * then verifies the programmatic API returns identical results+ * to `xds --json` for each one. Nothing is hardcoded.+ *+ * Usage:+ * node .github/scripts/api-cli-parity-test.mjs # full run+ * node .github/scripts/api-cli-parity-test.mjs --no-baseline # skip git worktree comparison+ */++import {spawnSync, execSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import * as path from 'node:path';+import * as fs from 'node:fs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const CLI = path.join(ROOT, 'packages/cli/bin/xds.mjs');+const skipBaseline = process.argv.includes('--no-baseline');+const baselineRef = process.argv.includes('--baseline')+ ? process.argv[process.argv.indexOf('--baseline') + 1]+ : 'main';++// ─── Helpers ──────────────────────────────────────────────────────────────────++function cliJson(args, cwd = ROOT) {+ const r = spawnSync(process.execPath, [CLI, '--json', ...args], {+ cwd, encoding: 'utf8', timeout: 30_000,+ });+ try {+ return JSON.parse(r.stdout);+ } catch {+ return {__parse_error: true, raw: r.stdout?.slice(0, 200)};+ }+}++async function apiCall(fn, ...args) {+ try {+ const r = await fn(...args);+ return {type: r.type, data: r.data};+ } catch (e) {+ return {error: e.message, suggestions: e.suggestions};+ }+}++const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);++function typeOf(r) {+ if (!r) return '(null)';+ if (r.__parse_error) return '(parse error)';+ if (r.error) return 'error';+ return r.type || '(no type)';+}++// ─── Discover ─────────────────────────────────────────────────────────────────++console.log('Discovering...');++const api = await import('../../packages/cli/src/api/index.mjs');++const componentList = cliJson(['component', '--list']);+const allComponents = componentList.data && !componentList.error+ ? Object.values(componentList.data).flat()+ : [];++const docsList = cliJson(['docs']);+const allTopics = docsList.data && !docsList.error+ ? docsList.data.map(e => e.topic)+ : [];++const categories = componentList.data ? Object.keys(componentList.data) : [];++console.log(` ${allComponents.length} components, ${allTopics.length} doc topics, ${categories.length} categories`);++// ─── Build cases ──────────────────────────────────────────────────────────────+//+// Each case: { label, cli, apiFn? }+// - cli: args for `xds --json ...`+// - apiFn: if present, called to get API result; compared with CLI result+// - if apiFn is absent, CLI-only (still counted for coverage)++const cases = [];++function add(label, cli, apiFn) {+ cases.push({label, cli, apiFn: apiFn || null});+}++// Component — list variants+add('component --list', ['component', '--list'],+ () => apiCall(api.component, undefined, {list: true, cwd: ROOT}));+add('component --detail brief', ['component', '--detail', 'brief'],+ () => apiCall(api.component, undefined, {detail: 'brief', cwd: ROOT}));++for (const cat of categories) {+ add(`component --category ${cat}`, ['component', '--category', cat],+ () => apiCall(api.component, undefined, {category: cat, cwd: ROOT}));+}++// Component — every discovered component+for (const name of allComponents) {+ add(`component ${name}`, ['component', name],+ () => apiCall(api.component, name, {cwd: ROOT}));+}++// Component — props + source (sample)+const sample = allComponents.includes('Button') ? 'Button' : allComponents[0];+if (sample) {+ add(`component ${sample} --props`, ['component', sample, '--props'],+ () => apiCall(api.component, sample, {props: true, cwd: ROOT}));+ add(`component ${sample} --source`, ['component', sample, '--source'],+ () => apiCall(api.component, sample, {source: true, cwd: ROOT}));+}++// Component — error+add('component NotARealThing99', ['component', 'NotARealThing99'],+ () => apiCall(api.component, 'NotARealThing99', {cwd: ROOT}));++// Docs — every topic+add('docs (list)', ['docs'], () => apiCall(api.docs));+for (const topic of allTopics) {+ add(`docs ${topic}`, ['docs', topic], () => apiCall(api.docs, topic));+}+add('docs nonexistent', ['docs', 'nonexistent_xyz'],+ () => apiCall(api.docs, 'nonexistent_xyz'));++// Other commands — probe with safe read-only args+const otherCommands = [+ ['swizzle', '--list'],+ ['template', '--list'],+ ['gap-report', '--list-categories'],+ ['upgrade', '--list'],+];+for (const args of otherCommands) {+ const probe = cliJson(args);+ if (!probe.__parse_error && !probe.error?.includes('not supported')) {+ add(args.join(' '), args);+ }+}++console.log(` ${cases.length} test cases\n`);++// ─── Run ──────────────────────────────────────────────────────────────────────++console.log('Running API + CLI...');++const results = [];+for (const tc of cases) {+ const cli = cliJson(tc.cli);+ const apiResult = tc.apiFn ? await tc.apiFn() : null;+ results.push({...tc, cli, api: apiResult});+}++// ─── Baseline (optional) ─────────────────────────────────────────────────────++const oldResults = new Map();+if (!skipBaseline) {+ console.log(`Running baseline CLI (${baselineRef})...`);+ const wt = path.join(ROOT, '.worktree-parity-test');+ try {+ execSync(`git worktree add "${wt}" ${baselineRef} --detach 2>/dev/null`, {cwd: ROOT});+ if (!fs.existsSync(path.join(wt, 'node_modules'))) {+ execSync('yarn install --frozen-lockfile 2>/dev/null || true', {cwd: wt, timeout: 60_000});+ }+ const oldCli = path.join(wt, 'packages/cli/bin/xds.mjs');+ for (const r of results) {+ const old = spawnSync(process.execPath, [oldCli, '--json', ...r.cli], {+ cwd: wt, encoding: 'utf8', timeout: 30_000,+ });+ try { oldResults.set(r.label, JSON.parse(old.stdout)); }+ catch { oldResults.set(r.label, {__parse_error: true}); }+ }+ } catch (e) {+ console.log(` Warning: ${e.message}`);+ }+ try { execSync(`git worktree remove "${wt}" --force 2>/dev/null`, {cwd: ROOT}); }+ catch {}+} else {+ console.log('Baseline: skipped (--no-baseline)');+}++// ─── Report ───────────────────────────────────────────────────────────────────++import {createHash} from 'node:crypto';++function sha(obj) {+ return createHash('sha256').update(JSON.stringify(obj)).digest('hex').slice(0, 12);+}++function summarize(obj) {+ if (!obj) return '(null)';+ if (obj.__parse_error) return '(parse error)';+ if (obj.error) return `error: "${obj.error}"`;+ const d = obj.data;+ if (Array.isArray(d)) return `[${d.length} items]`;+ if (d && typeof d === 'object') {+ if (d.name) return `{name: "${d.name}", ${Object.keys(d).length} keys}`;+ if (d.source) return `{source: ${d.source.length} chars}`;+ const keys = Object.keys(d);+ if (keys.length <= 4) return `{${keys.join(', ')}}`;+ return `{${keys.slice(0, 3).join(', ')}, +${keys.length - 3}}`;+ }+ return String(d).slice(0, 60);+}++let pass = 0;+let fail = 0;+const failures = [];+const apiTypes = new Set();+const cliTypes = new Set();+const cliOnlyTypes = new Set();++// Write full JSON to a file for inspection+const fullOutput = {};++for (const r of results) {+ const cliData = r.cli;+ const apiData = r.api;+ const ct = typeOf(cliData);++ if (!cliData?.error) cliTypes.add(ct);++ let identical;+ if (!apiData) {+ identical = null;+ if (!cliData?.error && cliData?.type) cliOnlyTypes.add(ct);+ } else {+ if (!apiData.error) apiTypes.add(typeOf(apiData));+ identical = deepEqual(apiData, cliData);+ }++ const ok = identical === true || identical === null;+ if (ok) pass++; else {+ fail++;+ failures.push(r);+ }++ const cliHash = sha(cliData);+ const apiHash = apiData ? sha(apiData) : '—';++ console.log('');+ console.log(`${ ok ? 'PASS' : 'FAIL'} ${r.label}`);+ console.log(` CLI: type=${ct} hash=${cliHash} ${summarize(cliData)}`);+ if (apiData) {+ console.log(` API: type=${typeOf(apiData)} hash=${apiHash} ${summarize(apiData)}`);+ } else {+ console.log(` API: (no API function — CLI-only command)`);+ }+ if (identical === true) {+ console.log(` Match: identical (${cliHash})`);+ } else if (identical === false) {+ console.log(` MISMATCH — CLI and API returned different data:`);+ console.log(` CLI: ${JSON.stringify(cliData).slice(0, 200)}`);+ console.log(` API: ${JSON.stringify(apiData).slice(0, 200)}`);+ }++ fullOutput[r.label] = {cli: cliData, api: apiData, identical};+}++// Write full results to file for manual inspection+const outPath = path.join(ROOT, '.parity-test-results.json');+fs.writeFileSync(outPath, JSON.stringify(fullOutput, null, 2));+console.log(`\nFull results written to ${path.relative(ROOT, outPath)}`);++// Coverage check+const uncovered = [...cliTypes].filter(t => !apiTypes.has(t) && !cliOnlyTypes.has(t));+if (uncovered.length > 0) {+ console.log(`\nCOVERAGE GAP — CLI types without API or probe coverage:`);+ for (const t of uncovered) console.log(` ${t}`);+ fail += uncovered.length;+}++console.log(`\n${results.length} cases | ${cliTypes.size} CLI types | ${apiTypes.size} API types | ${cliOnlyTypes.size} CLI-only`);+console.log(`PASS: ${pass} FAIL: ${fail}`);++if (fail > 0) {+ console.log('\nFAILURES:');+ for (const f of failures) {+ console.log(`\n ${f.label}`);+ console.log(` CLI: ${JSON.stringify(f.cli).slice(0, 300)}`);+ console.log(` API: ${JSON.stringify(f.api).slice(0, 300)}`);+ }+ process.exit(1);+}++console.log('\nAll checks passed.');diff --git a/.github/scripts/cli-smoke-test.mjs b/.github/scripts/cli-smoke-test.mjsindex 4f2c2b78d8..6ea8d9ba6c 100644--- a/.github/scripts/cli-smoke-test.mjs+++ b/.github/scripts/cli-smoke-test.mjs@@ -49,7 +49,14 @@ function check(label, args, {minLength = 10} = {}) {let reason = null;if (timedOut) reason = 'timed out';- else if (status !== 0) reason = `exit ${status}`;+ else if (status !== 0) {+ if (output.includes('needs a typed doc file')) {+ console.log(` skip ${label} (no .doc.mjs — undocumented component)`);+ passed++;+ return;+ }+ reason = `exit ${status}`;+ }else if (output.length < minLength) reason = `output too short (${output.length} chars, need ${minLength})`;if (reason) {diff --git a/.github/workflows/cli-smoke-test.yml b/.github/workflows/cli-smoke-test.ymlindex 9f31331101..04ac5f4123 100644--- a/.github/workflows/cli-smoke-test.yml+++ b/.github/workflows/cli-smoke-test.yml@@ -35,3 +35,6 @@ jobs:- name: CLI --json smoke testrun: node .github/scripts/cli-json-smoke-test.mjs++ - name: API ↔ CLI parity test+ run: node .github/scripts/api-cli-parity-test.mjs --no-baselinediff --git a/.gitignore b/.gitignoreindex c709729b1e..6d53adf133 100644--- a/.gitignore+++ b/.gitignore@@ -51,3 +51,5 @@ apps/sandbox/.next/apps/sandbox/out/apps/sandbox/next-env.d.tsapps/example-nextjs-tailwind/.next+.parity-test-results.json+.worktree-parity-testdiff --git a/packages/cli/README.md b/packages/cli/README.mdindex e6c1752088..97d8df4f66 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -26,7 +26,40 @@ Errors:}```-### Consumer utilities+### Programmatic API++The same logic that powers `xds --json` is available as importable, type-safe functions:++```typescript+import {component, docs, discover, XDSError} from '@xds/cli/api';++// Same result as: xds --json component Button+const btn = await component('Button');+btn.type; // 'component.detail'+btn.data.name; // 'Button' (typed as ComponentDoc)++// Same result as: xds --json component --list+const list = await component(undefined, {list: true});+list.data; // Record<string, string[]>++// Same result as: xds --json docs principles+const principles = await docs('principles');+principles.data.title; // 'XDS Principles'++// Errors throw XDSError with optional .suggestions+try {+ await component('Buttn');+} catch (e) {+ e.message; // 'No component named "Buttn"'+ e.suggestions; // [{ name: 'Button', reason: 'similar name' }]+}+```++The CLI command handlers are thin wrappers around these functions — they parse args, call the API, then format the output (JSON or text). This guarantees that `@xds/cli/api` and `xds --json` always return identical data.++### Consumer utilities (for parsing CLI stdout)++If you're spawning the CLI as a subprocess rather than importing the API directly:```typescriptimport {parseResponse, isError, assertResponse} from '@xds/cli/json';@@ -75,7 +108,6 @@ Every response has a `type` string that uniquely identifies it:| `xds --json upgrade [--apply]` | `upgrade.run` | `UpgradeRunResponse` || `xds --json gap-report --list-categories` | `gap-report.categories` | `GapReportCategoriesResponse` || `xds --json gap-report --component X ...` | `gap-report.file` | `GapReportFileResponse` |-| legacy README.md fallback | `markdown` | `CLIMarkdownResponse` || any error | -- | `CLIError` || unsupported command | -- | `CLIUnsupportedError` |@@ -83,13 +115,36 @@ Every response has a `type` string that uniquely identifies it:## Adding a new command-### 1. Create the command+### 1. Write the API function-Add a file in `src/commands/` and register it in `src/index.mjs`:+Add a file in `src/api/` with the core logic. It returns `{ type, data }` on success and throws `XDSError` on failure:++```javascript+// src/api/my-command.mjs+import {XDSError} from './error.mjs';++export async function myCommand(name, options = {}) {+ if (!name) {+ return {type: 'my-command.list', data: getAllItems()};+ }++ const item = findItem(name);+ if (!item) {+ throw new XDSError(`Item "${name}" not found`, suggestions);+ }++ return {type: 'my-command.detail', data: item};+}+```++### 2. Create the CLI wrapper++Add a thin wrapper in `src/commands/` that parses args, calls the API, and formats output:```javascript// src/commands/my-command.mjsimport {jsonOut, jsonError} from '../lib/json.mjs';+import {myCommand} from '../api/my-command.mjs';export function registerMyCommand(program) {program@@ -98,10 +153,17 @@ export function registerMyCommand(program) {.action(async (name, options) => {const json = program.opts().json || false;- // ... your logic ...-- if (json) return jsonOut('my-command.list', data);- console.log(textOutput);+ let result;+ try {+ result = await myCommand(name, options);+ } catch (e) {+ if (json) return jsonError(e.message, e.suggestions);+ console.error(e.message);+ process.exit(1);+ }++ if (json) return jsonOut(result.type, result.data);+ console.log(formatText(result));});}```@@ -199,33 +261,53 @@ Sub-objects in arrays. No `Response` suffix.## Architecture+The CLI is a thin wrapper around type-safe API functions. Each command follows the same pattern:++```+User calls API function User runs CLI+ | |+ v v+ api/component.mjs ◄──────── commands/component/index.mjs+ | |+ v v+ { type, data } jsonOut(type, data) or formatText(data)+```++Both paths run identical code. The CLI handler just adds argument parsing and output formatting.+```src/- index.mjs # Commander setup, --json flag, fallback hook+ api/ # Programmatic API (exported as @xds/cli/api)+ index.mjs # barrel: component, docs, discover, XDSError+ component.mjs # component(name?, opts?) → { type, data }+ docs.mjs # docs(topic?, section?, opts?) → { type, data }+ discover.mjs # discover(query?, opts?) → { type, data }+ error.mjs # XDSError class (carries .suggestions)+ commands/ # CLI wrappers (thin: parse args → call API → format output)+ component/index.mjs # registerComponent(program) — calls api/component.mjs+ docs.mjs # registerDocs(program) — calls api/docs.mjs+ discover.mjs # registerDiscover(program) — calls api/discover.mjs+ template.mjs # side-effect command (copies files)+ swizzle.mjs # side-effect command (copies + rewrites)+ build-theme.mjs # side-effect command (compiles theme)+ upgrade.mjs # side-effect command (runs codemods)+ gap-report.mjs # side-effect command (files issues)+ init.mjs # interactive only (no --json)lib/- json.mjs # jsonOut(type, data), jsonError(msg) -- internal- parse.mjs # parseResponse, isError, assertResponse -- consumer+ json.mjs # jsonOut(type, data), jsonError(msg) — internal+ parse.mjs # parseResponse, isError, assertResponse — consumertypes/- base.d.ts # CLIError, CLIResult<T>, CLIAnyResponse, CLIResponseType- component.d.ts # ComponentListResponse, ComponentDetailResponse, ...- discover.d.ts # DiscoverListResponse, ...- docs.d.ts # DocsListResponse, ...- template.d.ts # TemplateListResponse, TemplateCopyResponse- swizzle.d.ts # SwizzleListResponse, SwizzleCopyResponse- theme.d.ts # ThemeBuildResponse- upgrade.d.ts # UpgradeListResponse, UpgradeRunResponse- gap-report.d.ts # GapReportCategoriesResponse, GapReportFileResponse- index.d.ts # barrel re-export- commands/- component/index.mjs # uses jsonOut('component.list', ...) etc.- discover.mjs- docs.mjs- template.mjs- swizzle.mjs- build-theme.mjs- upgrade.mjs- gap-report.mjs- init.mjs # no --json (interactive only, fallback hook handles it)+ api.d.ts # API function signatures + XDSError+ base.d.ts # CLIError, CLIResult<T>, CLIAnyResponse, CLIResponseType+ component.d.ts # ComponentListResponse, ComponentDetailResponse, ...+ discover.d.ts # DiscoverListResponse, ...+ docs.d.ts # DocsListResponse, ...+ template.d.ts # TemplateListResponse, TemplateCopyResponse+ swizzle.d.ts # SwizzleListResponse, SwizzleCopyResponse+ theme.d.ts # ThemeBuildResponse+ upgrade.d.ts # UpgradeListResponse, UpgradeRunResponse+ gap-report.d.ts # GapReportCategoriesResponse, GapReportFileResponse+ index.d.ts # barrel re-export```### How the fallback hook works@@ -239,7 +321,8 @@ src/- `tsconfig.json-api.json` typechecks `json.mjs` and `parse.mjs` against the `.d.ts` declarations- `.github/scripts/cli-json-smoke-test.mjs` validates every `--json` command outputs valid JSON with correct envelope shape-- Both run in the `cli-smoke-test.yml` workflow on every PR+- `.github/scripts/api-cli-parity-test.mjs` verifies the programmatic API returns identical data to `xds --json` for every command+- All three run in the `cli-smoke-test.yml` workflow on every PR### Suppressing stdout for --jsondiff --git a/packages/cli/docs/principles.md b/packages/cli/docs/principles.mddeleted file mode 100644index 04bdd939f9..0000000000--- a/packages/cli/docs/principles.md+++ /dev/null@@ -1,83 +0,0 @@-# XDS Principles--React design system for internal tools. Components use `XDS` prefix.--## Rules--1. Use XDS components for everything they cover-2. StyleX for styling (not inline styles)-3. Semantic tokens, not hardcoded values-4. CSS variables for colors, not hex-5. Form inputs are controlled (value + onChange)--## Style Overrides: xstyle prop--Most XDS components accept an `xstyle` prop for customizing styles.-It supports three formats — pick the one that fits:--**Inline styles** — for simple one-off overrides:--```tsx-<XDSTextInput label="Name" xstyle={{ maxWidth: 300 }} />-<XDSCard xstyle={{ height: 200, padding: 16 }} />-```--**StyleX styles** — for complex, reusable, or pseudo-class overrides:--```tsx-import * as stylex from '@stylexjs/stylex';-const overrides = stylex.create({- hoverCard: {- boxShadow: {- default: 'none',- ':hover': {'@media (hover: hover)': '0 4px 12px rgba(0,0,0,0.15)'},- },- },-});-<XDSCard xstyle={overrides.hoverCard} />;-```--**CSS class name** — for Tailwind, CSS Modules, or external CSS:--```tsx-<XDSCard xstyle="my-custom-card" />-<XDSCard xstyle={styles.customCard} /> // CSS Module-```--Rules of thumb:--- 1-2 simple properties → inline-- 3+ properties, reusable, or named → `stylex.create`-- Pseudo-classes (`:hover`, `:focus-visible`) → `stylex.create` (required)-- All `:hover` MUST use `@media (hover: hover)` guards--## Anti-Patterns--❌ Inline styles on raw elements → Use `xstyle` on XDS components-❌ Hardcoded colors (#fff) → Use var(--color-_)-❌ Hardcoded spacing (16px) → Use spacing tokens or var(--spacing-_)-❌ Inventing props → Read component docs first--## StyleX Usage--```tsx-import * as stylex from '@stylexjs/stylex';--const styles = stylex.create({- container: {- padding: 'var(--spacing-4)',- backgroundColor: 'var(--color-background-surface)',- borderRadius: 'var(--radius-element)',- },-});--<div {...stylex.props(styles.container)}>-```--## Quick Token Reference--See `tokens.md` for the full list. Key values:--**Spacing**: 0=0px | 0.5=2px | 1=4px | 2=8px | 3=12px | 4=16px | 5=20px | 6=24px | 7=32px-**Radius**: rounded=pill | container=12px | element=8px | content=4px-**Colors**: accent, surface, wash, positive, negative, warningdiff --git a/packages/cli/docs/theme.md b/packages/cli/docs/theme.mddeleted file mode 100644index b4f9e5199c..0000000000--- a/packages/cli/docs/theme.md+++ /dev/null@@ -1,317 +0,0 @@-# XDS Theme System--## Quick Start--```tsx-import {XDSTheme} from '@xds/core';-import {defaultTheme} from '@xds/theme/default';--function App() {- return (- <XDSTheme theme={defaultTheme}>- <YourApp />- </XDSTheme>- );-}-```--## Available Themes--| Theme | Import | Description |-| ------- | ------------------------------------------------- | ------------------------------------- |-| Default | `import {defaultTheme} from '@xds/theme/default'` | Blue accent, system fonts, light/dark |-| Neutral | `import {neutralTheme} from '@xds/theme/neutral'` | Grayscale, shadcn-inspired |--Run `npx xds theme --list` to see themes in your project.--## XDSTheme Props--| Prop | Type | Default | Description |-| ---------- | ------------------------------- | ---------- | --------------------------------------------- |-| `theme` | `Theme` | — | Theme object (required) |-| `mode` | `'system' \| 'light' \| 'dark'` | `'system'` | Color mode. `'system'` follows OS preference. |-| `children` | `ReactNode` | — | App content |--## Creating a Custom Theme--### Scaffold with CLI (recommended)--```bash-npx xds theme-```--Interactive wizard that generates a `.stylex.ts` theme file with your brand colors.--### Manual creation--A theme is an object with `name` and `styles`. Only override token groups that differ from the defaults — omitted groups automatically use the `defineVars` defaults from `@xds/core`.--```tsx-import * as stylex from '@stylexjs/stylex';-import type {ThemeType as Theme} from '@xds/core/theme';-import {colorVars, colorDefaults} from '@xds/core/theme/tokens.stylex';--// 1. Define your color overrides-const colorOverrides = {- '--color-accent': 'light-dark(#7B61FF, #9B85FF)',- '--color-background-surface': 'light-dark(#FFFFFF, #1A1A2E)',- // ... all ~60 color tokens (see npx xds docs tokens)-} as const;--// 2. Create StyleX theme override-const colorTheme = stylex.createTheme(- colorVars,- colorOverrides as unknown as typeof colorDefaults,-);--// 3. Export the theme — only include overridden groups-export const myTheme: Theme = {- name: 'my-theme',- styles: {- colors: colorTheme,- // spacing, radius, etc. omitted — uses defaults- },- raw: {- colors: colorOverrides,- // Include raw values for programmatic access (charting libs, theme editors)- },-};-```--**Token groups** (all optional in `styles`):-colors, spacing, size, radius, elevation, transition, typography, textSize, lineHeight, fontWeight--Omitted groups use the `defineVars` defaults from `tokens.stylex.ts`.--### ⚠️ Static Analysis Constraint--StyleX's Babel plugin requires that **all values passed to `stylex.createTheme()` are inline object literals** — not variable references, spread expressions, or function return values. This is a compile-time constraint.--```tsx-// ❌ BROKEN — StyleX cannot statically analyze variable references-const sharedSpacing = {- '--spacing-1': '4px',- '--spacing-2': '8px',-};-const spacingTheme = stylex.createTheme(spacingVars, sharedSpacing);-// Error: "Only static values are allowed inside of a createTheme() call"--// ❌ BROKEN — spread also fails-const spacingTheme = stylex.createTheme(spacingVars, {...sharedSpacing});--// ✅ WORKS — inline object literal-const spacingTheme = stylex.createTheme(spacingVars, {- '--spacing-1': '4px',- '--spacing-2': '8px',-});-```--### Partial overrides--You only need to create `stylex.createTheme()` calls for token groups you want to change. For example, if your theme only changes colors and radius:--```tsx-export const myTheme: Theme = {- name: 'my-theme',- styles: {- colors: colorTheme,- radius: radiusTheme,- // All other groups (spacing, size, elevation, transition,- // typography, textSize, lineHeight, fontWeight) use defaults- },-};-```--### defineTheme (recommended for new themes)--`defineTheme` is a higher-level API that wraps the raw `stylex.createTheme` pattern. It supports scale configs that generate tokens from parameters.--```tsx-import {defineTheme} from '@xds/core/theme';--const myTheme = defineTheme({- name: 'my-theme',-- // Type scale — generates heading and text tokens from base size + ratio- typography: {scale: {base: 14, ratio: 1.2}},-- // Radius scale — generates radius tokens from base unit + multiplier- radius: {base: 4, multiplier: 1},-- // Explicit token overrides (highest precedence — overrides scale values)- tokens: {- '--color-accent': ['#7B61FF', '#9B85FF'],- },-- // Component-level style overrides- components: {- button: {- 'variant:primary': {color: 'white'},- },- },-});-```--**Scale configs:**--| Config | What it generates | Parameters |-| ------------------ | ----------------------------------------------------------------- | -------------------------------- |-| `typography.scale` | `--heading-*-size/weight/leading`, `--text-*-size/weight/leading` | `base` (px), `ratio`, `weights?` |-| `radius` | `--radius-none` through `--radius-page`, `--radius-full` | `base` (px), `multiplier` (0–2) |--Explicit `tokens` overrides always take precedence over scale-generated values.--## Light/Dark Mode--### Automatic (recommended)--Use `light-dark()` in token values:--```tsx-'--color-accent': 'light-dark(#0064E0, #2694FE)',-// ^light ^dark-```--Then use `mode="system"` (default) on XDSTheme — it follows OS preference.--### Toggle with a button--```tsx-const [mode, setMode] = useState<'light' | 'dark'>('light');--<XDSTheme theme={myTheme} mode={mode}>- <XDSButton- label={mode === 'light' ? 'Switch to Dark' : 'Switch to Light'}- onClick={() => setMode(m => (m === 'light' ? 'dark' : 'light'))}- />-</XDSTheme>;-```--### Dark-only or light-only theme--Set `mode` explicitly and use single values (not `light-dark()`):--```tsx-<XDSTheme theme={darkTheme} mode="dark">-```--## Nesting Themes--Wrap different sections in separate `<XDSTheme>` providers:--```tsx-<XDSTheme theme={lightTheme} mode="light">- <XDSLayout- header={<XDSLayoutHeader>...</XDSLayoutHeader>}- start={- <XDSTheme theme={darkTheme} mode="dark">- <XDSLayoutPanel>{/* Dark sidebar */}</XDSLayoutPanel>- </XDSTheme>- }- content={<XDSLayoutContent>{/* Light content */}</XDSLayoutContent>}- />-</XDSTheme>-```--## Page Background--**Important:** `XDSTheme` uses `display: contents` — it doesn't create a visual box.-To apply the theme's background color, add it to a wrapper element via StyleX:--```tsx-const styles = stylex.create({- page: {- backgroundColor: 'var(--color-background-body)',- minHeight: '100vh',- },-});--<XDSTheme theme={myTheme}>- <div {...stylex.props(styles.page)}>- <XDSLayout>...</XDSLayout>- </div>-</XDSTheme>;-```--## Component Style Overrides--Themes can override individual component styles via the `components` field.--### How it works--1. Components register their themeable properties via module augmentation:--```tsx-// Inside XDSCard.tsx-declare module '../theme/types' {- interface ComponentStyles {- card?: {- container?: ThemeStyleXStyles;- content?: ThemeStyleXStyles;- };- }-}-```--2. Your theme provides StyleX overrides:--```tsx-const cardOverrides = stylex.create({- container: {- borderRadius: '20px',- background:- 'linear-gradient(135deg, var(--color-accent), var(--color-success))',- padding: '2px', // gradient border width- },- content: {- backgroundColor: 'var(--color-background-card)',- borderRadius: '18px', // inner radius = outer - padding- },-});--export const myTheme: Theme = {- name: 'my-theme',- styles: {- colors: colorTheme,- },- components: {- card: {- container: cardOverrides.container,- content: cardOverrides.content,- },- } as Theme['components'],-};-```--### Available component overrides--| Component | Key | Slots | What to customize |-| --------- | --------- | -------------------------------------------------------------------------- | -------------------------------------- |-| Button | `button` | `variants` (by variant name) | Background, border, shadow per variant |-| Card | `card` | `container`, `content` | Border, radius, shadow, background |-| Heading | `heading` | `styles` (h1-h6), `editorialStyles` (h1-h6) | Font, size, weight, color per level |-| Text | `text` | `styles` (body, large, label, supporting, code) | Font, size, weight, color per type |-| Prose | `prose` | `base`, `styles` (p, ul, ol, li, blockquote, code, pre, hr, strong, em, a) | Prose element styling |--Run `npx xds --detail compact component <Name>` to see a component's themeable slots.--### The `as Theme['components']` cast--The `components` field requires a type assertion because `ComponentStyles` is augmented by individual components via `declare module`. The theme package doesn't import those components, so the augmentations aren't visible at compile time. The cast is safe — types are enforced at the consumer site.--## useXDSTheme Hook--Access the current theme in any component:--```tsx-import {useXDSTheme} from '@xds/core';--function MyComponent() {- const ctx = useXDSTheme();- // ctx.theme — the Theme object- // ctx.mode — 'system' | 'light' | 'dark'- return null;-}-```--**Note:** This is read-only. To change the theme/mode, manage state at the app level and pass it to `<XDSTheme>`.diff --git a/packages/cli/docs/tokens.md b/packages/cli/docs/tokens.mddeleted file mode 100644index 81e3b57211..0000000000--- a/packages/cli/docs/tokens.md+++ /dev/null@@ -1,291 +0,0 @@-# XDS Design Tokens--All design tokens are defined in `packages/core/src/theme/tokens.stylex.ts`.--## Spacing Tokens--| Token | Value | Usage |-| ------------- | ----- | ---------------- |-| --spacing-0 | 0px | No spacing |-| --spacing-0-5 | 2px | Hairline spacing |-| --spacing-1 | 4px | Tight spacing |-| --spacing-2 | 8px | Compact spacing |-| --spacing-3 | 12px | Default small |-| --spacing-4 | 16px | Default medium |-| --spacing-5 | 20px | Comfortable |-| --spacing-6 | 24px | Loose |-| --spacing-7 | 28px | Semi-loose |-| --spacing-8 | 32px | Extra loose |-| --spacing-9 | 36px | Spacious |-| --spacing-10 | 40px | Extra spacious |-| --spacing-11 | 44px | Ultra spacious |-| --spacing-12 | 48px | Maximum spacing |--Component `gap` props use numeric scale values (e.g. `gap={4}` for 16px). The scale maps to these tokens: 0=0px, 0.5=2px, 1=4px, 2=8px, 3=12px, 4=16px, 5=20px, 6=24px, 8=32px, 10=40px.--## Size Tokens--Control heights for consistent sizing across buttons, inputs, and selectors.--| Token | Value | Usage |-| ----------------- | ----- | ------------------------------- |-| --size-element-sm | 28px | Compact controls |-| --size-element-md | 32px | Default control size |-| --size-element-lg | 36px | Larger, more prominent controls |--## Color Tokens--### Semantic Colors--| Token | Usage |-| -------------------------- | -------------------------------------------- |-| --color-accent | Primary action color |-| --color-background-surface | Background surface |-| --color-background-body | Page-level background (app shell, page body) |-| --color-success | Success states |-| --color-error | Error states |-| --color-warning | Warning states |-| --color-on-accent | Text/icon on accent background |-| --color-on-success | Text/icon on success background |-| --color-on-error | Text/icon on error background |-| --color-on-warning | Text/icon on warning background |-| --color-on-dark | Text/icon on dark media |-| --color-on-light | Text/icon on light media |--### Neutral Grays--Three tokens for "gray" backgrounds. Choosing the right one depends on what the element _is_:--| Token | Role | Use for |-| ------------------------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |-| --color-neutral | Neutral fill for elements | Buttons (default), badges, tokens, kbd, avatar fallback, pagination dots, status dots, selected nav items, icon containers |-| --color-background-muted | Background for content areas | Sections, code blocks, table zebra stripes, progress/slider tracks, disabled input fills, featured cards |-| --color-overlay-hover | Translucent hover/active state | Hover on ghost buttons, list item highlights, menu item highlights, table row hover |--**Decision tree:**--1. Is it a **hover/active/highlighted state**? → `--color-overlay-hover`-2. Is it a **container with other content inside** (text, icons, controls)? → `--color-background-muted`-3. Is it a **self-contained element sitting on a surface**? → `--color-neutral`--### Text Colors--| Token | Usage |-| ---------------------- | -------------- |-| --color-text-primary | Main text |-| --color-text-secondary | Secondary text |-| --color-text-disabled | Disabled text |-| --color-text-accent | Link text |--### Icon Colors--| Token | Usage |-| ---------------------- | --------------- |-| --color-icon-accent | Accent icons |-| --color-icon-primary | Main icons |-| --color-icon-secondary | Secondary icons |-| --color-icon-disabled | Disabled icons |--## Radius Tokens--Semantic scale based on a 4dp base unit. Tokens inner through page scale with the theme's `radius` multiplier; none and full are fixed.--| Token | Value | Usage | Scales |-| ------------------ | ------ | ------------------------------------- | ------ |-| --radius-none | 0px | No radius (dividers, table cells) | No |-| --radius-inner | 4px | Code blocks, inner content | Yes |-| --radius-element | 8px | Buttons, inputs, text areas | Yes |-| --radius-container | 12px | Cards, modals, popovers, dropdowns | Yes |-| --radius-page | 28px | Page sections, large containers | Yes |-| --radius-full | 9999px | Badges, avatars, status dots, toggles | No |--### radius (via defineTheme)--Generate all radius tokens from a base unit and multiplier:--```tsx-import {defineTheme} from '@xds/core/theme';--const roundedTheme = defineTheme({- name: 'rounded',- radius: {base: 4, multiplier: 1.5},- // Produces: radius-1=6px, radius-2=12px, radius-3=18px, radius-4=24px- // radius-0 stays 0px, radius-rounded stays 9999px-});--const sharpTheme = defineTheme({- name: 'sharp',- radius: {base: 4, multiplier: 0},- // All scalable radii become 0px-});-```--| Multiplier | Effect | radius-3 becomes |-| ----------- | --------- | ---------------- |-| 0 | Sharp | 0px |-| 0.5 | Subtle | 6px |-| 1 (default) | Default | 12px |-| 1.5 | Rounded | 18px |-| 2 | Pill-like | 24px |--## Border Tokens--| Token | Value | Usage |-| -------------- | ----- | ---------------------------------- |-| --border-width | 1px | Default border width across the UI |--## Shadow Tokens--| Token | Usage |-| ----------------------- | ------------------------- |-| --shadow-low | Subtle lift (cards) |-| --shadow-low | Floating elements (menus) |-| --shadow-med | Hover lift, toasts |-| --shadow-high | Dialogs, modals |-| --shadow-inset-hover | Input hover ring |-| --shadow-inset-selected | Input focused/active ring |-| --shadow-inset-success | Input success ring |-| --shadow-inset-warning | Input warning ring |-| --shadow-inset-error | Input error ring |--## Typography Tokens--### Font Families--- `--font-family-body`: System UI font stack-- `--font-family-code`: Monospace font stack-- `--font-family-heading`: System UI font stack--### Text Sizes--Computed from a geometric scale: `round(base × ratio^step)`.-Default: base=14px, ratio=1.2.--| Token | Step | Default | Usage |-| ---------------- | ---- | ------- | --------------- |-| --font-size-4xs | -5 | 6px | Citation, micro |-| --font-size-3xs | -4 | 7px | Micro labels |-| --font-size-2xs | -3 | 8px | Small micro |-| --font-size-xs | -2 | 10px | Extra small |-| --font-size-sm | -1 | 12px | Small text |-| --font-size-base | 0 | 14px | Body (anchor) |-| --font-size-lg | +1 | 17px | Large text |-| --font-size-xl | +2 | 20px | Extra large |-| --font-size-2xl | +3 | 24px | 2× large |-| --font-size-3xl | +4 | 29px | 3× large |-| --font-size-4xl | +5 | 35px | 4× large |--### Type Scale (Semantic Tokens)--Semantic tokens map headings and text types to the raw size scale.-Sizes are `var()` references; line heights are 4px-grid-snapped computed values.--Override the entire scale with `typography.scale: { base, ratio }` in `defineTheme()`.--#### Heading Tokens--| Token | Maps to | Default | Leading |-| ------------------------ | --------------------- | ------- | ------- |-| --text-heading-1-size | var(--font-size-2xl) | 24px | |-| --text-heading-1-weight | semibold | | |-| --text-heading-1-leading | | | 1.3333 |-| --text-heading-2-size | var(--font-size-xl) | 20px | |-| --text-heading-2-weight | semibold | | |-| --text-heading-2-leading | | | 1.4 |-| --text-heading-3-size | var(--font-size-lg) | 17px | |-| --text-heading-3-weight | semibold | | |-| --text-heading-3-leading | | | 1.4118 |-| --text-heading-4-size | var(--font-size-base) | 14px | |-| --text-heading-4-weight | semibold | | |-| --text-heading-4-leading | | | 1.4286 |-| --text-heading-5-size | var(--font-size-sm) | 12px | |-| --text-heading-5-weight | semibold | | |-| --text-heading-5-leading | | | 1.6667 |-| --text-heading-6-size | var(--font-size-xs) | 10px | |-| --text-heading-6-weight | semibold | | |-| --text-heading-6-leading | | | 1.6 |--#### Text Type Tokens--| Token | Maps to | Default | Leading | Weight |-| ------------------------- | --------------------- | ------- | ------- | -------- |-| --text-body-size | var(--font-size-base) | 14px | | |-| --text-body-weight | | | | normal |-| --text-body-leading | | | 1.4286 | |-| --text-large-size | var(--font-size-lg) | 17px | | |-| --text-large-weight | | | | semibold |-| --text-large-leading | | | 1.4118 | |-| --text-label-size | var(--font-size-base) | 14px | | |-| --text-label-weight | | | | medium |-| --text-label-leading | | | 1.4286 | |-| --text-code-size | var(--font-size-base) | 14px | | |-| --text-code-weight | | | | normal |-| --text-code-leading | | | 1.4286 | |-| --text-supporting-size | var(--font-size-sm) | 12px | | |-| --text-supporting-weight | | | | normal |-| --text-supporting-leading | | | 1.6667 | |--#### Display Tokens--| Token | Maps to | Default | Leading |-| ------------------------ | -------------------- | ------- | ------- |-| --text-display-1-size | var(--font-size-5xl) | 42px | |-| --text-display-1-weight | | | normal |-| --text-display-1-leading | | | 1.2381 |-| --text-display-2-size | var(--font-size-4xl) | 35px | |-| --text-display-2-weight | | | normal |-| --text-display-2-leading | | | 1.2571 |-| --text-display-3-size | var(--font-size-3xl) | 29px | |-| --text-display-3-weight | | | normal |-| --text-display-3-leading | | | 1.2414 |--### Font Weights--- `--font-weight-normal`: 400-- `--font-weight-medium`: 500-- `--font-weight-semibold`: 600-- `--font-weight-bold`: 700--### Line Heights (Named Leading) — Deprecated--> **Deprecated.** Use semantic type scale leading tokens instead.-> Components should pair their `fontSize` with the matching semantic leading:-> `--text-body-leading`, `--text-label-leading`, `--text-supporting-leading`, etc.--| Old Token | Value | Replacement |-| ----------------- | ------ | ------------------------- |-| --leading-base | 1.4286 | --text-body-leading |-| --leading-snug | 1.375 | --text-label-leading |-| --leading-normal | 1.5 | --text-large-leading |-| --leading-tight | 1.25 | --text-heading-1-leading |-| --leading-relaxed | 1.625 | --text-supporting-leading |--## Usage in StyleX--```tsx-import * as stylex from '@stylexjs/stylex';-import {colorVars, spacingVars, sizeVars, radiusVars} from '@xds/core';--const styles = stylex.create({- card: {- padding: spacingVars['--spacing-4'],- backgroundColor: colorVars['--color-background-surface'],- borderRadius: radiusVars['--radius-container'],- },- button: {- height: sizeVars['--size-element-md'],- },-});-```--Or use CSS custom properties directly:--```tsx-const styles = stylex.create({- card: {- padding: 'var(--spacing-4)',- backgroundColor: 'var(--color-background-surface)',- borderRadius: 'var(--radius-container)',- },-});-```diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex f3189e3359..366ed245d1 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -11,6 +11,10 @@"./json": {"types": "./src/types/index.d.ts","import": "./src/lib/parse.mjs"+ },+ "./api": {+ "types": "./src/types/api.d.ts",+ "import": "./src/api/index.mjs"}},"files": [diff --git a/packages/cli/src/api/component.mjs b/packages/cli/src/api/component.mjsnew file mode 100644index 0000000000..a52a55d036--- /dev/null+++ b/packages/cli/src/api/component.mjs@@ -0,0 +1,191 @@+/**+ * @file Programmatic API for the component command.+ *+ * Returns the same typed envelope { type, data } that `xds --json component` outputs.+ * The CLI command handler is a thin wrapper around this function.+ */++import * as fs from 'node:fs';+import {findCoreDir, discoverExternalPackages} from '../utils/paths.mjs';+import {+ discoverComponents,+ discoverExternalComponents,+ findComponentReadme,+ findComponentSource,+ findExternalComponentDoc,+ resolveImportPath,+} from '../lib/component-discovery.mjs';+import {loadDocs} from '../lib/component-loader.mjs';+import {searchComponents} from '../lib/string-utils.mjs';+import {XDSError} from './error.mjs';++/**+ * @param {string} [name]+ * @param {object} [options]+ * @param {string} [options.cwd]+ * @param {boolean} [options.list]+ * @param {string} [options.category]+ * @param {boolean} [options.props]+ * @param {boolean} [options.source]+ * @param {'full'|'compact'|'brief'} [options.detail]+ * @param {string} [options.lang]+ * @param {boolean} [options.zh]+ * @param {boolean} [options.dense]+ * @returns {Promise<{type: string, data: unknown}>}+ */+export async function component(name, options = {}) {+ const {+ cwd = process.cwd(),+ list = false,+ category,+ props = false,+ source = false,+ detail = 'full',+ lang = null,+ zh = false,+ dense = false,+ } = options;++ const coreDir = findCoreDir(cwd);+ if (!coreDir) {+ throw new XDSError('Could not find @xds/core package');+ }++ // ── List mode ──────────────────────────────────────────────────++ if (category || list || !name) {+ const components = discoverComponents(coreDir);++ if (category) {+ const match = Object.entries(components).find(+ ([key]) => key.toLowerCase() === category.toLowerCase(),+ );+ if (!match) {+ throw new XDSError(+ `Unknown category "${category}"`,+ Object.keys(components).map(k => ({name: k, reason: 'valid category'})),+ );+ }++ if (detail === 'brief') {+ const entries = [];+ for (const comp of match[1]) {+ const readme = findComponentReadme(coreDir, comp);+ if (readme && readme.endsWith('.doc.mjs')) {+ try {+ const docs = await loadDocs(readme, {zh, lang});+ entries.push({name: comp, description: docs.description, import: resolveImportPath(coreDir, comp)});+ } catch {+ entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ }+ } else {+ entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ }+ }+ return {type: 'component.brief', data: {[match[0]]: entries}};+ }++ return {type: 'component.list', data: {[match[0]]: match[1]}};+ }++ // All components+ if (detail === 'brief') {+ /** @type {Record<string, Array<import('../types/component').ComponentBriefEntry>>} */+ const result = {};+ for (const [cat, comps] of Object.entries(components)) {+ result[cat] = [];+ for (const comp of comps) {+ const readme = findComponentReadme(coreDir, comp);+ if (readme && readme.endsWith('.doc.mjs')) {+ try {+ const docs = await loadDocs(readme, {zh, lang});+ result[cat].push({name: comp, description: docs.description, import: resolveImportPath(coreDir, comp)});+ } catch {+ result[cat].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ }+ } else {+ result[cat].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ }+ }+ }+ return {type: 'component.brief', data: result};+ }++ const externals = discoverExternalPackages(cwd);+ for (const ext of externals) {+ const extComps = discoverExternalComponents(ext.docsDir);+ if (extComps.length > 0) {+ components[`${ext.category} (${ext.name})`] = extComps;+ }+ }+ return {type: 'component.list', data: components};+ }++ // ── Single component ───────────────────────────────────────────++ const dirName = name.replace(/^XDS/, '');++ if (source) {+ const sourcePath = findComponentSource(coreDir, dirName);+ if (!sourcePath) {+ throw new XDSError(`Source for "${name}" not found`);+ }+ return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(sourcePath, 'utf-8')}};+ }++ let readmePath = findComponentReadme(coreDir, dirName);+ let resolvedName = dirName;+ let fromExternal = null;++ if (!readmePath) {+ const externals = discoverExternalPackages(cwd);+ for (const ext of externals) {+ const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);+ if (extDocPath) {+ readmePath = extDocPath;+ fromExternal = ext;+ break;+ }+ }+ }++ if (!readmePath) {+ const components = discoverComponents(coreDir);+ const results = await searchComponents(dirName, coreDir, components);++ if (results.length > 0) {+ const topScore = results[0].score;+ const topTied = results.filter(r => r.score === topScore);+ const secondScore = results.length > topTied.length ? results[topTied.length].score : 0;+ const gap = topScore - secondScore;++ if (topScore >= 90 && topTied.length === 1 && gap >= 20) {+ resolvedName = topTied[0].name;+ readmePath = findComponentReadme(coreDir, resolvedName);+ } else {+ const threshold = Math.max(topScore - 20, 1);+ const candidates = results.filter(r => r.score >= threshold).slice(0, 5);+ if (candidates.length < 2) candidates.push(...results.slice(candidates.length, 2));+ throw new XDSError(+ `No component named "${name}"`,+ candidates.map(c => ({name: c.name, reason: c.reason})),+ );+ }+ } else {+ throw new XDSError(`No component named "${name}"`);+ }+ }++ if (!readmePath || !readmePath.endsWith('.doc.mjs')) {+ throw new XDSError(`No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`);+ }++ const docs = await loadDocs(readmePath, {zh, dense, lang});++ if (props) {+ const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);+ return {type: 'component.detail.props', data: p};+ }++ return {type: 'component.detail', data: docs};+}diff --git a/packages/cli/src/api/discover.mjs b/packages/cli/src/api/discover.mjsnew file mode 100644index 0000000000..c75d618632--- /dev/null+++ b/packages/cli/src/api/discover.mjs@@ -0,0 +1,153 @@+/**+ * @file Programmatic API for the discover command.+ */++import {loadConfig} from '../lib/config.mjs';+import {scanAllPackages, findComponentInPackages} from '../lib/package-scanner.mjs';+import {loadDocs} from '../lib/component-loader.mjs';+import {levenshteinDistance} from '../lib/string-utils.mjs';+import {XDSError} from './error.mjs';++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;+}++/**+ * @param {string} [query]+ * @param {object} [options]+ * @param {boolean} [options.components]+ * @param {string} [options.lang]+ * @param {boolean} [options.zh]+ * @returns {Promise<{type: string, data: unknown}>}+ */+export async function discover(query, options = {}) {+ const {lang = null, zh = false} = options;+ const config = await loadConfig();+ const toEntry = (pkg) => ({name: pkg.name, category: pkg.category, components: pkg.components});++ if (config.packages.length === 0) {+ return {type: 'discover.list', data: []};+ }++ const packages = scanAllPackages(config.packages);++ if (packages.length === 0) {+ return {type: 'discover.list', data: []};+ }++ if (!query) {+ return {type: 'discover.list', data: packages.map(toEntry)};+ }++ // Scoped package query: @scope/name or @scope/name/Component+ if (query.startsWith('@')) {+ const slashIdx = query.indexOf('/', query.indexOf('/') + 1);+ if (slashIdx > 0) {+ const pkgName = query.slice(0, slashIdx);+ const compName = query.slice(slashIdx + 1);+ return await resolveComponentDocs(packages, compName, pkgName, {lang, zh});+ }++ const pkg = packages.find(p => p.name === query);+ if (!pkg) {+ throw new XDSError(+ `Package "${query}" not found`,+ packages.map(p => ({name: p.name, reason: 'available package'})),+ );+ }+ return {type: 'discover.detail', data: toEntry(pkg)};+ }++ // Search mode+ const lower = query.toLowerCase();++ const exact = findComponentInPackages(packages, query);+ if (exact) {+ return await loadAndValidate(exact, {lang, zh});+ }++ 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) return await loadAndValidate(result, {lang, zh});+ }++ if (substringMatches.length > 1) {+ return {type: 'discover.search', data: {query, matches: substringMatches.map(m => ({package: m.pkg.name, component: m.comp}))}};+ }++ // Fuzzy fallback+ 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) {+ throw new XDSError(+ `"${query}" not found`,+ fuzzyMatches.map(m => ({name: m.pkg.name + '/' + m.comp, reason: 'similar name'})),+ );+ }++ throw new XDSError(`"${query}" not found in any package`);+}++async function resolveComponentDocs(packages, compName, pkgName, {lang, zh}) {+ const pkg = packages.find(p => p.name === pkgName);+ if (!pkg) throw new XDSError(`Package "${pkgName}" not found`);++ const result = findComponentInPackages([pkg], compName);+ if (!result) {+ const lower = compName.toLowerCase();+ const hits = pkg.components.filter(c => c.toLowerCase().includes(lower));+ const suggestions = hits.length > 0+ ? hits+ : pkg.components+ .map(c => ({name: c, distance: levenshteinDistance(lower, c.toLowerCase())}))+ .filter(m => m.distance <= 3)+ .sort((a, b) => a.distance - b.distance)+ .slice(0, 5)+ .map(m => m.name);+ throw new XDSError(+ `Component "${compName}" not found in ${pkgName}`,+ suggestions.map(s => ({name: s, reason: 'similar name'})),+ );+ }++ return await loadAndValidate(result, {lang, zh});+}++async function loadAndValidate(result, {lang, zh}) {+ let docs;+ try {+ docs = await loadDocs(result.docPath, {zh, lang});+ } catch (e) {+ throw new XDSError(`Failed to load docs for ${result.componentName}: ${e.message}`);+ }+ const err = validateDocs(docs);+ if (err) throw new XDSError(`Invalid docs for ${result.componentName}: ${err}`);+ return {type: 'discover.detail.doc', data: docs};+}diff --git a/packages/cli/src/api/docs.mjs b/packages/cli/src/api/docs.mjsnew file mode 100644index 0000000000..e520ffca2e--- /dev/null+++ b/packages/cli/src/api/docs.mjs@@ -0,0 +1,110 @@+/**+ * @file Programmatic API for the docs command.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {pathToFileURL} from 'node:url';+import {CLI_ROOT} from '../utils/paths.mjs';+import {XDSError} from './error.mjs';++const DOCS_DIR = path.join(CLI_ROOT, 'docs');++function discoverTopics() {+ const topics = {};+ if (!fs.existsSync(DOCS_DIR)) return topics;+ for (const file of fs.readdirSync(DOCS_DIR)) {+ const match = file.match(/^(\w+)\.doc\.mjs$/);+ if (match) topics[match[1]] = path.join(DOCS_DIR, file);+ }+ return topics;+}++async function loadReferenceDocs(docPath, {lang} = {}) {+ const mod = await import(pathToFileURL(docPath).href);+ const docs = mod.docs;+ if (!lang || lang === 'en') return docs;++ const dir = path.dirname(docPath);+ const base = path.basename(docPath, '.doc.mjs');+ const locale = lang === 'dense' ? 'dense' : lang;+ const translationPath = path.join(dir, `${base}.doc.${locale}.mjs`);+ if (!fs.existsSync(translationPath)) return docs;++ const translationMod = await import(pathToFileURL(translationPath).href);+ const translation = translationMod.docsZh || translationMod.docsDense;+ if (!translation) return docs;++ return {+ ...docs,+ description: translation.description || docs.description,+ sections: docs.sections.map((section, si) => {+ const ts = translation.sections?.[si];+ if (!ts) return section;+ return {+ ...section,+ title: ts.title || section.title,+ content: section.content.map((block, bi) => {+ const tb = ts.content?.[bi];+ if (!tb) return block;+ if (tb.type === 'prose' && block.type === 'prose') return {...block, text: tb.text};+ if (tb.type === 'list' && block.type === 'list') return {...block, items: tb.items};+ return block;+ }),+ };+ }),+ };+}++/**+ * @param {string} [topic]+ * @param {string} [section]+ * @param {object} [options]+ * @param {string} [options.lang]+ * @param {boolean} [options.zh]+ * @param {boolean} [options.dense]+ * @returns {Promise<{type: string, data: unknown}>}+ */+export async function docs(topic, section, options = {}) {+ const {lang = null, zh = false, dense = false} = options;+ const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);+ const topics = discoverTopics();++ if (!topic) {+ /** @type {Array<import('../types/docs').DocsListEntry>} */+ const entries = [];+ for (const [name, docPath] of Object.entries(topics)) {+ try {+ const mod = await import(pathToFileURL(docPath).href);+ entries.push({topic: name, description: mod.docs.description});+ } catch {+ entries.push({topic: name, description: ''});+ }+ }+ return {type: 'docs.list', data: entries};+ }++ const normalized = topic.toLowerCase();+ if (!topics[normalized]) {+ throw new XDSError(+ `Unknown topic "${topic}"`,+ Object.keys(topics).map(t => ({name: t, reason: 'available topic'})),+ );+ }++ const docsData = await loadReferenceDocs(topics[normalized], {lang: effectiveLang});++ if (section) {+ const normalizedSection = section.toLowerCase();+ const match = docsData.sections.find(s => s.title.toLowerCase().includes(normalizedSection));+ if (!match) {+ throw new XDSError(+ `Section "${section}" not found in "${topic}"`,+ docsData.sections.map(s => ({name: s.title, reason: 'available section'})),+ );+ }+ return {type: 'docs.detail.section', data: match};+ }++ return {type: 'docs.detail', data: docsData};+}diff --git a/packages/cli/src/api/error.mjs b/packages/cli/src/api/error.mjsnew file mode 100644index 0000000000..fdb9b857d6--- /dev/null+++ b/packages/cli/src/api/error.mjs@@ -0,0 +1,18 @@+/**+ * @file API error class — carries structured error info matching CLIError shape.+ */++export class XDSError extends Error {+ /** @type {Array<{name: string, reason: string}> | undefined} */+ suggestions;++ /**+ * @param {string} message+ * @param {Array<{name: string, reason: string}>} [suggestions]+ */+ constructor(message, suggestions) {+ super(message);+ this.name = 'XDSError';+ if (suggestions?.length) this.suggestions = suggestions;+ }+}diff --git a/packages/cli/src/api/index.mjs b/packages/cli/src/api/index.mjsnew file mode 100644index 0000000000..f32f6bdd27--- /dev/null+++ b/packages/cli/src/api/index.mjs@@ -0,0 +1,20 @@+/**+ * @file Programmatic API for the XDS CLI.+ *+ * Every function returns the same { type, data } envelope that `xds --json` outputs.+ * Errors throw XDSError (with optional .suggestions).+ *+ * @example+ * import { component, docs, XDSError } from '@xds/cli/api';+ *+ * const result = await component('Button');+ * // { type: 'component.detail', data: { name: 'Button', ... } }+ *+ * const list = await component(undefined, { list: true });+ * // { type: 'component.list', data: { Layout: [...], ... } }+ */++export {component} from './component.mjs';+export {docs} from './docs.mjs';+export {discover} from './discover.mjs';+export {XDSError} from './error.mjs';diff --git a/packages/cli/src/commands/component.test.mjs b/packages/cli/src/commands/component.test.mjsindex 10d5a451de..c1ec098ff8 100644--- a/packages/cli/src/commands/component.test.mjs+++ b/packages/cli/src/commands/component.test.mjs@@ -6,9 +6,6 @@ import {discoverComponents,discoverExternalComponents,findExternalComponentDoc,- cleanReadme,- extractCompact,- extractProps,findComponentReadme,findComponentSource,levenshteinDistance,@@ -79,130 +76,49 @@ describe('discoverComponents', () => {});});-describe('cleanReadme', () => {- it('strips SYNC comments, rewrites title, collapses blanks', () => {- const input = [- '# /packages/core/src/Button',- '<!-- SYNC: something -->',- '',- 'Description here.',- '',- '',- '',- 'More text.',- ].join('\n');-- const result = cleanReadme(input, 'Button');- expect(result).toContain('# Button');- expect(result).not.toContain('SYNC');- // Should collapse consecutive blank lines- expect(result).not.toContain('\n\n\n');- });-- it('preserves XDS prefix in display name', () => {- const input = '# /packages/core/src/XDSButton\n\nContent.\n';- const result = cleanReadme(input, 'XDSButton');- expect(result).toContain('# XDSButton');- });-});--describe('extractCompact', () => {- it('skips configured sections', () => {- const input = [- '# /packages/core/src/Button',- '',- '## Features',- 'Feature list.',- '',- '## Files',- 'This should be skipped.',- '',- '## RTL Support',- 'Also skipped.',- '',- '## Props',- 'Props content.',- ].join('\n');-- const result = extractCompact(input, 'Button');- expect(result).toContain('# Button');- expect(result).toContain('Feature list.');- expect(result).not.toContain('This should be skipped.');- expect(result).not.toContain('Also skipped.');- expect(result).toContain('Props content.');- });-- it('limits code blocks to MAX_EXAMPLES (3)', () => {- const blocks = [];- for (let i = 0; i < 5; i++) {- blocks.push(`\`\`\`tsx\ncode block ${i}\n\`\`\``);- }- const input = `# /Button\n\n## Usage\n\n${blocks.join('\n\n')}\n`;-- const result = extractCompact(input, 'Button');- // Should include at most 3 code blocks- const codeBlockCount = (result.match(/```tsx/g) || []).length;- expect(codeBlockCount).toBeLessThanOrEqual(3);- });-- it('strips ASCII art blocks', () => {- const input = [- '# /Button',- '',- '```',- '┌──────────────┐',- '│ ASCII art │',- '└──────────────┘',- '```',- '',- 'Regular text.',- ].join('\n');-- const result = extractCompact(input, 'Button');- expect(result).not.toContain('┌──────────────┐');- expect(result).toContain('Regular text.');- });-});-describe('findComponentReadme', () => {- it('finds direct README: src/{name}/README.md', () => {+ it('finds direct .doc.mjs: src/{name}/{Name}.doc.mjs', () => {const srcDir = path.join(tmpDir, 'src');const compDir = path.join(srcDir, 'Button');fs.mkdirSync(compDir, {recursive: true});- fs.writeFileSync(path.join(compDir, 'README.md'), '# Button');+ fs.writeFileSync(path.join(compDir, 'Button.doc.mjs'), 'export const docs = {}');const result = findComponentReadme(tmpDir, 'Button');- expect(result).toBe(path.join(compDir, 'README.md'));+ expect(result).toBe(path.join(compDir, 'Button.doc.mjs'));});- it('finds nested README: src/*/{name}/README.md', () => {+ it('finds nested .doc.mjs: src/*/{name}/{Name}.doc.mjs', () => {const srcDir = path.join(tmpDir, 'src');const nestedDir = path.join(srcDir, 'Layout', 'Container');fs.mkdirSync(nestedDir, {recursive: true});- fs.writeFileSync(path.join(nestedDir, 'README.md'), '# Container');+ fs.writeFileSync(path.join(nestedDir, 'Container.doc.mjs'), 'export const docs = {}');const result = findComponentReadme(tmpDir, 'Container');- expect(result).toBe(path.join(nestedDir, 'README.md'));+ expect(result).toBe(path.join(nestedDir, 'Container.doc.mjs'));});- it('falls back to README near source file', () => {+ it('finds parent .doc.mjs for sub-components', () => {const srcDir = path.join(tmpDir, 'src');- const deepDir = path.join(srcDir, 'Layout', 'Container', 'Card');- fs.mkdirSync(deepDir, {recursive: true});- fs.writeFileSync(path.join(deepDir, 'XDSCard.tsx'), '');- // README in Container (parent of Card)- fs.writeFileSync(- path.join(srcDir, 'Layout', 'Container', 'README.md'),- '# Container',- );+ const stackDir = path.join(srcDir, 'Stack');+ fs.mkdirSync(stackDir, {recursive: true});+ fs.writeFileSync(path.join(stackDir, 'XDSStackItem.tsx'), '');+ fs.writeFileSync(path.join(stackDir, 'Stack.doc.mjs'), 'export const docs = {}');- const result = findComponentReadme(tmpDir, 'Card');- expect(result).toBe(- path.join(srcDir, 'Layout', 'Container', 'README.md'),- );+ const result = findComponentReadme(tmpDir, 'StackItem');+ expect(result).toBe(path.join(stackDir, 'Stack.doc.mjs'));});- it('returns null when no README found', () => {+ it('ignores README.md files', () => {+ const srcDir = path.join(tmpDir, 'src');+ const compDir = path.join(srcDir, 'Button');+ fs.mkdirSync(compDir, {recursive: true});+ fs.writeFileSync(path.join(compDir, 'README.md'), '# Button');++ const result = findComponentReadme(tmpDir, 'Button');+ expect(result).toBeNull();+ });++ it('returns null when no doc found', () => {const srcDir = path.join(tmpDir, 'src');fs.mkdirSync(srcDir, {recursive: true});expect(findComponentReadme(tmpDir, 'NonExistent')).toBeNull();@@ -318,82 +234,6 @@ describe('findClosestComponents', () => {});});-describe('extractProps', () => {- it('extracts a Props section from README content', () => {- const input = [- '# Button',- '',- '## Description',- 'A button component.',- '',- '## Props',- '',- '| Prop | Type | Default |',- '|------|------|---------|',- '| size | string | "md" |',- '| variant | string | "primary" |',- '',- '## Examples',- 'Some examples here.',- ].join('\n');-- const result = extractProps(input, 'Button');- expect(result).toContain('## Props');- expect(result).toContain('| size | string | "md" |');- expect(result).toContain('| variant | string | "primary" |');- expect(result).not.toContain('## Description');- expect(result).not.toContain('## Examples');- });-- it('extracts multiple Props sections', () => {- const input = [- '# Layout',- '',- '## XDSLayout Props',- '| Prop | Type |',- '|------|------|',- '| gap | number |',- '',- '## XDSLayoutItem Props',- '| Prop | Type |',- '|------|------|',- '| flex | number |',- '',- '## Examples',- 'Some examples.',- ].join('\n');-- const result = extractProps(input, 'Layout');- expect(result).toContain('## XDSLayout Props');- expect(result).toContain('| gap | number |');- expect(result).toContain('## XDSLayoutItem Props');- expect(result).toContain('| flex | number |');- expect(result).not.toContain('## Examples');- });-- it('returns fallback message when no Props section found', () => {- const input = '# Button\n\n## Description\nA button.\n';- const result = extractProps(input, 'Button');- expect(result).toBe('No props documentation found for Button.\n');- });-- it('trims trailing blank lines', () => {- const input = [- '## Props',- '| Prop | Type |',- '|------|------|',- '| size | string |',- '',- '',- '',- ].join('\n');-- const result = extractProps(input, 'Button');- expect(result).not.toMatch(/\n\n$/);- expect(result).toMatch(/\n$/);- });-});-describe('discoverExternalComponents', () => {it('finds .doc.mjs files in the docs directory', () => {const docsDir = path.join(tmpDir, 'src');diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjsindex c7b98b3dfe..0b2b8ff47c 100644--- a/packages/cli/src/commands/component/index.mjs+++ b/packages/cli/src/commands/component/index.mjs@@ -4,15 +4,11 @@* Global options: --detail full|compact|brief, --lang en|zh|dense*/-import * as fs from 'node:fs';-import * as path from 'node:path';import {findCoreDir, discoverExternalPackages} from '../../utils/paths.mjs';import {discoverComponents,discoverExternalComponents,findComponentReadme,- findComponentSource,- findExternalComponentDoc,resolveImportPath,} from '../../lib/component-discovery.mjs';import {loadDocs} from '../../lib/component-loader.mjs';@@ -23,17 +19,10 @@ import {formatProps,formatBriefAll,} from '../../lib/component-format.mjs';-import {- cleanReadme,- extractCompact,- extractBrief,- ensureImportStatement,- extractProps,-} from '../../lib/component-legacy.mjs';-import {findClosestComponents, searchComponents} from '../../lib/string-utils.mjs';import {resolveTheme} from '../../lib/resolve-theme.mjs';import {getRunPrefix} from '../../utils/package-manager.mjs';import {jsonOut, jsonError} from '../../lib/json.mjs';+import {component as componentApi} from '../../api/component.mjs';export function registerComponent(program) {program@@ -45,7 +34,6 @@ export function registerComponent(program) {.option('--source', 'Print component source code').action(async (name, options) => {const run = getRunPrefix();- const coreDir = findCoreDir(process.cwd());const zh = program.opts().zh || false;const dense = program.opts().dense || false;const lang = program.opts().lang || null;@@ -60,244 +48,90 @@ export function registerComponent(program) {process.exit(1);}- if (!coreDir) {- if (json) return jsonError('Could not find @xds/core package');- console.error(- 'Error: Could not find @xds/core package.\n' +- 'Make sure you are inside the XDS monorepo or have @xds/core installed.',- );+ let result;+ try {+ result = await componentApi(name, {+ cwd: process.cwd(),+ list: options.list,+ category: options.category,+ props: options.props,+ source: options.source,+ detail,+ lang, zh, dense,+ });+ } catch (e) {+ if (json) return jsonError(e.message, e.suggestions);+ console.error(`Error: ${e.message}`);+ if (e.suggestions?.length) {+ console.error('');+ for (const s of e.suggestions) {+ console.error(` ${s.name} (${s.reason})`);+ }+ }process.exit(1);}- // Resolve active theme for variant merging- const themeData = resolveTheme(process.cwd());-- if (options.category || options.list || !name) {- const components = discoverComponents(coreDir);+ if (json) return jsonOut(result.type, result.data);- if (options.category) {- const cat = options.category;- const match = Object.entries(components).find(- ([key]) => key.toLowerCase() === cat.toLowerCase(),- );- if (!match) {- if (json) return jsonError(`Unknown category "${cat}"`, Object.keys(components).map(k => ({name: k, reason: 'valid category'})));- console.error(`Error: Unknown category "${cat}".`);- console.error(- `Available categories: ${Object.keys(components).join(', ')}`,- );- process.exit(1);- }-- if (json && detail === 'brief') {- const entries = [];- for (const comp of match[1]) {- const readme = findComponentReadme(coreDir, comp);- if (readme && readme.endsWith('.doc.mjs')) {- try {- const docs = await loadDocs(readme, {zh, lang});- entries.push({name: comp, description: docs.description, import: resolveImportPath(coreDir, comp)});- } catch {- entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});- }- } else {- entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});- }- }- return jsonOut('component.brief', {[match[0]]: entries});- }- if (json) return jsonOut('component.list', {[match[0]]: match[1]});+ // ── Text output ────────────────────────────────────────────+ const coreDir = findCoreDir(process.cwd());+ const themeData = resolveTheme(process.cwd());- if (detail === 'brief') {- for (const comp of match[1]) {- const readme = findComponentReadme(coreDir, comp);- if (readme && readme.endsWith('.doc.mjs')) {- try {- const docs = await loadDocs(readme, {zh, lang});- const importHint = resolveImportPath(coreDir, comp);- console.log(formatBrief(docs, comp, importHint, { themeData }));- } catch {- console.log(` ${comp}`);- }- } else {- console.log(` ${comp}`);- }- }- } else {- console.log(`\n${match[0]}:`);- for (const comp of match[1]) {- console.log(` ${comp}`);- }+ switch (result.type) {+ case 'component.list': {+ if (options.category) {+ const [cat, comps] = Object.entries(result.data)[0];+ console.log(`\n${cat}:`);+ for (const comp of comps) console.log(` ${comp}`);console.log('');- }- return;- }-- // --list or no name: show all components- if (json && detail === 'brief') {- /** @type {Record<string, Array<import('../../types/component').ComponentBriefEntry>>} */- const result = {};- for (const [category, comps] of Object.entries(components)) {- result[category] = [];- for (const comp of comps) {- const readme = findComponentReadme(coreDir, comp);- if (readme && readme.endsWith('.doc.mjs')) {- try {- const docs = await loadDocs(readme, {zh, lang});- result[category].push({name: comp, description: docs.description, import: resolveImportPath(coreDir, comp)});- } catch {- result[category].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});- }- } else {- result[category].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});- }- }- }- return jsonOut('component.brief', result);- }- if (json) {- const externals = discoverExternalPackages(process.cwd());- for (const ext of externals) {- const extComps = discoverExternalComponents(ext.docsDir);- if (extComps.length > 0) {- components[`${ext.category} (${ext.name})`] = extComps;- }- }- return jsonOut('component.list', components);- }-- if (detail === 'brief') {- console.log(await formatBriefAll(coreDir, {zh, lang, themeData}));- } else {- console.log('');- for (const [category, comps] of Object.entries(components)) {- console.log(`${category}:`);- for (const comp of comps) {- console.log(` ${comp}`);- }+ } else {console.log('');- }- const externals = discoverExternalPackages(process.cwd());- for (const ext of externals) {- const extComponents = discoverExternalComponents(ext.docsDir);- if (extComponents.length > 0) {- console.log(`${ext.category} (${ext.name}):`);- for (const comp of extComponents) {- console.log(` ${comp}`);- }+ for (const [cat, comps] of Object.entries(result.data)) {+ console.log(`${cat}:`);+ for (const comp of comps) console.log(` ${comp}`);console.log('');}+ console.log(`Usage: ${run} xds component <name>`);+ console.log('');}-- console.log(`Usage: ${run} xds component <name>`);- console.log('');+ break;}- return;- }-- // Normalize: strip XDS prefix for directory lookup- const dirName = name.replace(/^XDS/, '');-- if (options.source) {- const sourcePath = findComponentSource(coreDir, dirName);- if (!sourcePath) {- if (json) return jsonError(`Source for "${name}" not found`);- console.error(`Error: Source for "${name}" not found.`);- process.exit(1);- }- const source = fs.readFileSync(sourcePath, 'utf-8');- if (json) return jsonOut('component.detail.source', {component: dirName, source});- console.log(source);- return;- }-- let readmePath = findComponentReadme(coreDir, dirName);- let resolvedName = dirName;- let fromExternal = null;- // If not found in core, check external packages- if (!readmePath) {- const externals = discoverExternalPackages(process.cwd());- for (const ext of externals) {- const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);- if (extDocPath) {- readmePath = extDocPath;- fromExternal = ext;- break;+ case 'component.brief': {+ if (options.category || options.list || !name) {+ console.log(await formatBriefAll(coreDir, {zh, lang, themeData}));+ } else {+ const resolvedName = (name || '').replace(/^XDS/, '');+ const importHint = resolveImportPath(coreDir, resolvedName);+ console.log(formatBrief(result.data, resolvedName, importHint, {themeData}));}+ break;}- }-- if (!readmePath) {- const components = discoverComponents(coreDir);- const results = await searchComponents(dirName, coreDir, components);- if (results.length > 0) {- const topScore = results[0].score;- const topTied = results.filter(r => r.score === topScore);- const secondScore = results.length > topTied.length- ? results[topTied.length].score : 0;- const gap = topScore - secondScore;-- if (topScore >= 90 && topTied.length === 1 && gap >= 20) {- resolvedName = topTied[0].name;- readmePath = findComponentReadme(coreDir, resolvedName);- if (readmePath && topScore < 100 && !json) {- console.log(`Showing results for ${resolvedName} (matched ${topTied[0].reason})\n`);- }+ case 'component.detail': {+ if (detail === 'brief') {+ const resolvedName = (name || '').replace(/^XDS/, '');+ const importHint = resolveImportPath(coreDir, resolvedName);+ console.log(formatBrief(result.data, resolvedName, importHint, {themeData}));+ } else if (detail === 'compact') {+ const resolvedName = (name || '').replace(/^XDS/, '');+ const importHint = resolveImportPath(coreDir, resolvedName);+ console.log(formatCompact(result.data, resolvedName, importHint));} else {- const threshold = Math.max(topScore - 20, 1);- const candidates = results.filter(r => r.score >= threshold).slice(0, 5);- if (candidates.length < 2) candidates.push(...results.slice(candidates.length, 2));-- if (json) return jsonError(`No component named "${name}"`, candidates.map(c => ({name: c.name, reason: c.reason})));- console.error(`No component named "${name}". Did you mean:\n`);- for (const match of candidates) {- console.error(` ${match.name} (${match.reason})`);- }- console.error(`\nRun \`${run} xds component <name>\` to view docs.`);- process.exit(1);+ console.log(formatFull(result.data, {themeData}));}- } else {- if (json) return jsonError(`No component named "${name}"`);- console.error(`No component named "${name}".`);- console.error(`Run \`${run} xds component --list\` to see available components.`);- process.exit(1);+ break;}- }- if (readmePath.endsWith('.doc.mjs')) {- const docs = await loadDocs(readmePath, {zh, dense, lang});- const importHint = fromExternal ? fromExternal.name : resolveImportPath(coreDir, resolvedName);- if (json) {- if (options.props) {- const props = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);- return jsonOut('component.detail.props', props);- }- return jsonOut('component.detail', docs);- }- if (options.props) {- console.log(formatProps(docs, resolvedName));- } else if (detail === 'brief') {- console.log(formatBrief(docs, resolvedName, importHint, { themeData }));- } else if (detail === 'compact') {- console.log(formatCompact(docs, resolvedName, importHint));- } else {- console.log(formatFull(docs, { themeData }));+ case 'component.detail.props': {+ const resolvedName = (name || '').replace(/^XDS/, '');+ console.log(formatProps({props: result.data}, resolvedName));+ break;}- } else {- // Legacy path for README.md files- const content = fs.readFileSync(readmePath, 'utf-8');- if (json) return jsonOut('markdown', {name: resolvedName, format: 'markdown', content});- if (options.props) {- console.log(extractProps(content, resolvedName));- } else if (detail === 'brief') {- console.log(extractBrief(content, resolvedName));- } else if (detail === 'compact') {- const compact = extractCompact(content, resolvedName);- console.log(ensureImportStatement(compact, resolvedName, coreDir));- } else {- console.log(cleanReadme(content, resolvedName));++ case 'component.detail.source': {+ console.log(result.data.source);+ break;}}});@@ -310,5 +144,4 @@ export {discoverComponents, discoverExternalComponents, findComponentReadme, finexport {discoverExternalPackages} from '../../utils/paths.mjs';export {loadDocs} from '../../lib/component-loader.mjs';export {formatFull, formatCompact, formatBrief, formatProps, formatBriefAll} from '../../lib/component-format.mjs';-export {cleanReadme, extractCompact, extractBrief, ensureImportStatement, extractProps} from '../../lib/component-legacy.mjs';export {levenshteinDistance, findClosestComponents, searchComponents} from '../../lib/string-utils.mjs';diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjsindex 5e18f746ab..a7c676404c 100644--- a/packages/cli/src/commands/discover.mjs+++ b/packages/cli/src/commands/discover.mjs@@ -9,11 +9,10 @@*/import {loadConfig} from '../lib/config.mjs';-import {scanAllPackages, findComponentInPackages} from '../lib/package-scanner.mjs';-import {loadDocs} from '../lib/component-loader.mjs';+import {scanAllPackages} from '../lib/package-scanner.mjs';import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';-import {levenshteinDistance} from '../lib/string-utils.mjs';import {jsonOut, jsonError} from '../lib/json.mjs';+import {discover as discoverApi} from '../api/discover.mjs';export function registerDiscover(program) {program@@ -21,292 +20,115 @@ export function registerDiscover(program) {.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';const json = program.opts().json || false;-- /** @param {object} pkg */- const toEntry = (pkg) => ({name: pkg.name, category: pkg.category, components: pkg.components});-- if (config.packages.length === 0) {- if (json) return jsonOut('discover.list', []);- 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) {- if (json) return jsonOut('discover.list', []);- 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;- }-- if (!query) {- if (json) return jsonOut('discover.list', packages.map(toEntry));- printPackageList(packages, options.components);- return;+ const lang = program.opts().lang || null;+ const zh = program.opts().zh || false;++ let result;+ try {+ result = await discoverApi(query, {components: options.components, lang, zh});+ } catch (e) {+ if (json) return jsonError(e.message, e.suggestions);+ console.error(`Error: ${e.message}`);+ if (e.suggestions?.length) {+ console.error('');+ for (const s of e.suggestions) {+ console.error(` ${s.name} (${s.reason})`);+ }+ }+ process.exit(1);}- if (query.startsWith('@')) {- const slashIdx = query.indexOf('/', query.indexOf('/') + 1);- if (slashIdx > 0) {- const pkgName = query.slice(0, slashIdx);- const compName = query.slice(slashIdx + 1);- await showComponentDocs(packages, compName, pkgName, program, detail, json);- } else {- const pkg = packages.find(p => p.name === query);- if (!pkg) {- if (json) return jsonError('Package "' + query + '" not found', packages.map(p => ({name: p.name, reason: 'available package'})));- console.error('Package "' + query + '" not found.');- console.error('');- console.error('Available packages:');- for (const p of packages) {- console.error(' ' + p.name);+ if (json) return jsonOut(result.type, result.data);++ switch (result.type) {+ case 'discover.list': {+ if (result.data.length === 0) {+ const config = await loadConfig();+ console.log('');+ if (config.packages.length === 0) {+ 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(' };');+ } else {+ 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('');+ } else {+ console.log('');+ for (const pkg of result.data) {+ const count = pkg.components.length;+ const label = count === 1 ? 'component' : 'components';+ console.log(pkg.name + ' (' + count + ' ' + label + ')');++ if (options.components) {+ 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(', ');+ console.log(remaining > 0 ? ' ' + list + ', +' + remaining + ' more' : ' ' + list);+ }+ console.log('');}- process.exit(1);+ 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('');}- if (json) return jsonOut('discover.detail', toEntry(pkg));- printSinglePackage(pkg);+ break;}- return;- }- await searchComponents(packages, query, program, detail, json);- });-}--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, json) {- const pkg = packages.find(p => p.name === pkgName);- if (!pkg) {- if (json) return jsonError('Package "' + pkgName + '" not found');- console.error('Package "' + pkgName + '" not found.');- process.exit(1);- }-- const result = findComponentInPackages([pkg], compName);- if (!result) {- const substringHits = pkg.components.filter(- c => c.toLowerCase().includes(compName.toLowerCase()),- );- const suggestions = substringHits.length > 0- ? substringHits- : fuzzyMatch(compName, pkg.components);- if (json) return jsonError('Component "' + compName + '" not found in ' + pkgName, suggestions.map(s => ({name: s, reason: 'similar name'})));- 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, json);-}--async function searchComponents(packages, query, program, detail, json) {- const lower = query.toLowerCase();-- const exact = findComponentInPackages(packages, query);- if (exact) {- if (!json) {- console.log('Found: ' + exact.pkg.name + '/' + exact.componentName);- console.log('');- }- await renderDocs(exact, program, detail, json);- return;- }+ case 'discover.detail': {+ console.log('');+ console.log(result.data.name + ' (' + result.data.components.length + ' components)');+ console.log('');+ for (const comp of result.data.components) console.log(' ' + comp);+ console.log('');+ console.log('Usage: xds discover ' + result.data.name + '/<ComponentName>');+ console.log('');+ break;+ }- const substringMatches = [];- for (const pkg of packages) {- for (const comp of pkg.components) {- if (comp.toLowerCase().includes(lower)) {- substringMatches.push({pkg, comp});- }- }- }+ case 'discover.detail.doc': {+ const docs = result.data;+ if (detail === 'brief') {+ console.log(formatBrief(docs, docs.name, ''));+ } else if (detail === 'compact') {+ console.log(formatCompact(docs, docs.name, ''));+ } else {+ console.log(formatFull(docs));+ }+ console.log('');+ break;+ }- if (substringMatches.length === 1) {- const match = substringMatches[0];- const result = findComponentInPackages([match.pkg], match.comp);- if (result) {- if (!json) {- console.log('Found: ' + match.pkg.name + '/' + match.comp);- console.log('');+ case 'discover.search': {+ console.log('');+ console.log('Found ' + result.data.matches.length + ' matches for "' + result.data.query + '":');+ console.log('');+ for (const m of result.data.matches) {+ console.log(' xds discover ' + m.package + '/' + m.component);+ }+ console.log('');+ break;+ }}- await renderDocs(result, program, detail, json);- return;- }- }-- if (substringMatches.length > 1) {- if (json) return jsonOut('discover.search', {query, matches: substringMatches.map(m => ({package: m.pkg.name, component: m.comp}))});- 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;- }-- 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) {- if (json) return jsonError('"' + query + '" not found', fuzzyMatches.map(m => ({name: m.pkg.name + '/' + m.comp, reason: 'similar name'})));- 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 {- if (json) return jsonError('"' + query + '" not found in any package');- 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, json) {- let docs;- try {- const zh = program.opts().zh || false;- const lang = program.opts().lang || null;- docs = await loadDocs(result.docPath, {zh, lang});- } catch (e) {- if (json) return jsonError('Failed to load docs for ' + result.componentName + ': ' + e.message);- 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) {- if (json) return jsonError('Invalid docs for ' + result.componentName + ': ' + validationError);- console.error('Invalid docs for ' + result.componentName + ': ' + validationError);- console.error('File: ' + result.docPath);- process.exit(1);- }-- if (json) return jsonOut('discover.detail.doc', docs);-- 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/commands/docs.mjs b/packages/cli/src/commands/docs.mjsindex 541cef861b..1ae4a75528 100644--- a/packages/cli/src/commands/docs.mjs+++ b/packages/cli/src/commands/docs.mjs@@ -10,93 +10,9 @@* xds docs <topic> <section> Print one section*/-import * as fs from 'node:fs';-import * as path from 'node:path';-import {pathToFileURL} from 'node:url';-import {CLI_ROOT} from '../utils/paths.mjs';import {getRunPrefix} from '../utils/package-manager.mjs';import {jsonOut, jsonError} from '../lib/json.mjs';--const DOCS_DIR = path.join(CLI_ROOT, 'docs');--// ─── Discovery ───────────────────────────────────────────────────────────────--/**- * Discover all .doc.mjs files in the docs directory.- * Returns a map of topic name -> file path.- */-function discoverTopics() {- const topics = {};- if (!fs.existsSync(DOCS_DIR)) return topics;-- for (const file of fs.readdirSync(DOCS_DIR)) {- // Match foo.doc.mjs but not foo.doc.dense.mjs or foo.doc.zh.mjs- const match = file.match(/^(\w+)\.doc\.mjs$/);- if (match) {- topics[match[1]] = path.join(DOCS_DIR, file);- }- }- return topics;-}--// ─── Loading ─────────────────────────────────────────────────────────────────--/**- * Load a reference doc, optionally merging a translation overlay.- */-async function loadReferenceDocs(docPath, {lang} = {}) {- const mod = await import(pathToFileURL(docPath).href);- const docs = mod.docs;-- if (!lang || lang === 'en') return docs;-- // Try loading translation file: foo.doc.zh.mjs or foo.doc.dense.mjs- const dir = path.dirname(docPath);- const base = path.basename(docPath, '.doc.mjs');- const locale = lang === 'dense' ? 'dense' : lang;- const translationPath = path.join(dir, `${base}.doc.${locale}.mjs`);-- if (!fs.existsSync(translationPath)) return docs;-- const translationMod = await import(pathToFileURL(translationPath).href);- const translation = translationMod.docsZh || translationMod.docsDense;-- if (!translation) return docs;-- return mergeTranslation(docs, translation);-}--/**- * Merge a translation overlay onto a base reference doc.- * Prose and list blocks get swapped. Code and table blocks pass through.- */-function mergeTranslation(base, translation) {- return {- ...base,- description: translation.description || base.description,- sections: base.sections.map((section, si) => {- const ts = translation.sections?.[si];- if (!ts) return section;-- return {- ...section,- title: ts.title || section.title,- content: section.content.map((block, bi) => {- const tb = ts.content?.[bi];- if (!tb) return block;-- if (tb.type === 'prose' && block.type === 'prose') {- return {...block, text: tb.text};- }- if (tb.type === 'list' && block.type === 'list') {- return {...block, items: tb.items};- }- return block;- }),- };- }),- };-}+import {docs as docsApi} from '../api/docs.mjs';// ─── Formatting ──────────────────────────────────────────────────────────────@@ -113,7 +29,6 @@ function formatTable(headers, rows) {}function formatTableCompact(headers, rows) {- // key=value pairs, one line per rowreturn rows.map(r => r.join(' = ')).join('\n');}@@ -129,7 +44,6 @@ function formatBlock(block, detail) {case 'table':if (detail === 'brief') {- // One-liner: first two columns as key=valuereturn block.rows.map(r => r.slice(0, 2).join('=')).join(' | ');}if (detail === 'compact') {@@ -156,7 +70,6 @@ function formatSection(section, detail) {.filter(Boolean);if (detail === 'brief') {- // Just the first prose block or first table one-linerconst first = blocks[0] || '';return `${section.title}: ${first.split('\n')[0]}`;}@@ -188,80 +101,46 @@ export function registerDocs(program) {.description('Print XDS reference docs').action(async (topic, section) => {const run = getRunPrefix();- const topics = discoverTopics();const lang = program.opts().lang || null;const zh = program.opts().zh || false;const dense = program.opts().dense || false;const detail = program.opts().detail || 'full';const json = program.opts().json || false;- const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);- if (!topic) {- if (json) {- /** @type {Array<import('../types/docs').DocsListEntry>} */- const entries = [];- for (const [name, docPath] of Object.entries(topics)) {- try {- const mod = await import(pathToFileURL(docPath).href);- entries.push({topic: name, description: mod.docs.description});- } catch {- entries.push({topic: name, description: ''});- }- }- return jsonOut('docs.list', entries);+ let result;+ try {+ result = await docsApi(topic, section, {lang, zh, dense});+ } catch (e) {+ if (json) return jsonError(e.message, e.suggestions);+ console.error(`Error: ${e.message}`);+ if (e.suggestions?.length) {+ console.error(`Available: ${e.suggestions.map(s => s.name).join(', ')}`);}- console.log('\nAvailable docs:\n');- for (const [name, docPath] of Object.entries(topics)) {- try {- const mod = await import(pathToFileURL(docPath).href);- console.log(` ${name.padEnd(14)} ${mod.docs.description}`);- } catch {- console.log(` ${name}`);- }- }- console.log(`\nUsage: ${run} xds docs <topic>`);- console.log(` ${run} xds docs <topic> <section>\n`);- return;+ process.exit(1);}- const normalized = topic.toLowerCase();+ if (json) return jsonOut(result.type, result.data);- if (!topics[normalized]) {- const mdPath = path.join(DOCS_DIR, `${normalized}.md`);- if (fs.existsSync(mdPath)) {- const content = fs.readFileSync(mdPath, 'utf-8');- if (json) return jsonOut('markdown', {name: normalized, format: 'markdown', content});- console.log(content);- return;+ switch (result.type) {+ case 'docs.list': {+ console.log('\nAvailable docs:\n');+ for (const entry of result.data) {+ console.log(` ${entry.topic.padEnd(14)} ${entry.description}`);+ }+ console.log(`\nUsage: ${run} xds docs <topic>`);+ console.log(` ${run} xds docs <topic> <section>\n`);+ break;}- if (json) return jsonError(`Unknown topic "${topic}"`, Object.keys(topics).map(t => ({name: t, reason: 'available topic'})));- console.error(`Error: Unknown topic "${topic}".`);- console.error(`Available topics: ${Object.keys(topics).join(', ')}`);- process.exit(1);- }-- const docs = await loadReferenceDocs(topics[normalized], {lang: effectiveLang});+ case 'docs.detail': {+ console.log(formatReferenceFull(result.data, detail));+ break;+ }- if (section) {- const normalizedSection = section.toLowerCase();- const match = docs.sections.find(- s => s.title.toLowerCase().includes(normalizedSection),- );- if (!match) {- if (json) return jsonError(`Section "${section}" not found in "${topic}"`, docs.sections.map(s => ({name: s.title, reason: 'available section'})));- console.error(`Error: Section "${section}" not found in "${topic}".`);- console.error(- `Available sections: ${docs.sections.map(s => s.title).join(', ')}`,- );- process.exit(1);+ case 'docs.detail.section': {+ console.log(formatSection(result.data, detail));+ break;}- if (json) return jsonOut('docs.detail.section', match);- console.log(formatSection(match, detail));- return;}-- if (json) return jsonOut('docs.detail', docs);- console.log(formatReferenceFull(docs, detail));});}diff --git a/packages/cli/src/lib/component-discovery.mjs b/packages/cli/src/lib/component-discovery.mjsindex f3bc88aa81..6c5504b94d 100644--- a/packages/cli/src/lib/component-discovery.mjs+++ b/packages/cli/src/lib/component-discovery.mjs@@ -111,40 +111,35 @@ export function discoverComponents(coreDir) {}/**- * Merge a TranslationDoc overlay onto a base ComponentDoc.- * Replaces prose fields (description, features, notes, accessibility, keyboard,- * prop descriptions) while keeping structure (props, examples, types, defaults).+ * Find the .doc.mjs file for a component.+ * For sub-components (e.g. StackItem), returns the parent's .doc.mjs+ * if the sub-component is documented there.*/export function findComponentReadme(coreDir, name) {const srcDir = path.join(coreDir, 'src');- // Preferred: {Name}.doc.mjs, then README.md- const docNames = [`${name}.doc.mjs`, 'README.md'];+ const exactDoc = `${name}.doc.mjs`;- for (const docName of docNames) {- // Direct match: src/{name}/{Name}.doc.mjs (or README.md)- const direct = path.join(srcDir, name, docName);- if (fs.existsSync(direct)) return direct;- }+ // Direct match: src/{name}/{Name}.doc.mjs+ const direct = path.join(srcDir, name, exactDoc);+ if (fs.existsSync(direct)) return direct;- // Nested match: src/*/{name}/{Name}.doc.mjs (or README.md)+ // Nested match: src/*/{name}/{Name}.doc.mjsconst entries = fs.readdirSync(srcDir, {withFileTypes: true});- for (const docName of docNames) {- for (const entry of entries) {- if (!entry.isDirectory()) continue;- const nested = path.join(srcDir, entry.name, name, docName);- if (fs.existsSync(nested)) return nested;- }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const nested = path.join(srcDir, entry.name, name, exactDoc);+ if (fs.existsSync(nested)) return nested;}- // Fallback: find the directory containing XDS{name}.tsx,- // then return the doc file in that directory or nearest parent+ // Sub-component fallback: find the source file, then walk up+ // looking for any .doc.mjs in the same or parent directoriesconst sourcePath = findComponentSource(coreDir, name);if (sourcePath) {let dir = path.dirname(sourcePath);while (dir.startsWith(srcDir)) {- for (const docName of docNames) {- const docFile = path.join(dir, docName);- if (fs.existsSync(docFile)) return docFile;+ const dirEntries = fs.readdirSync(dir);+ for (const f of dirEntries) {+ if (f.endsWith('.doc.mjs')) return path.join(dir, f);}dir = path.dirname(dir);}diff --git a/packages/cli/src/lib/component-format.mjs b/packages/cli/src/lib/component-format.mjsindex dd83585a77..141567491f 100644--- a/packages/cli/src/lib/component-format.mjs+++ b/packages/cli/src/lib/component-format.mjs@@ -4,7 +4,6 @@import {discoverComponents, findComponentReadme, resolveImportPath} from './component-discovery.mjs';import {loadDocs} from './component-loader.mjs';-import {extractBrief} from './component-legacy.mjs';import * as fs from 'node:fs';/** Derive the theme component key from a theming target (strips 'xds-' prefix). */@@ -478,11 +477,6 @@ export async function formatBriefAll(coreDir, {zh = false, lang, themeData = nulconst docs = await loadDocs(readmePath, {zh, lang});const importPath = resolveImportPath(coreDir, comp);output.push(formatBrief(docs, comp, importPath, { themeData }));- } else if (readmePath) {- // Legacy README.md path- const content = fs.readFileSync(readmePath, 'utf-8');- const importPath = resolveImportPath(coreDir, comp);- output.push(extractBrief(content, comp, importPath));} else {output.push(`XDS${comp}\n (no docs)\n`);}diff --git a/packages/cli/src/lib/component-legacy.mjs b/packages/cli/src/lib/component-legacy.mjsdeleted file mode 100644index 447cfb483c..0000000000--- a/packages/cli/src/lib/component-legacy.mjs+++ /dev/null@@ -1,502 +0,0 @@-/**- * @file Legacy README.md parsing — extract docs from markdown files- *- * These functions parse raw README.md content using regex.- * They exist for backward compatibility with components that- * haven't been converted to .doc.mjs format yet.- * Delete this file when all components have .doc.mjs files.- */--import * as fs from 'node:fs';-import * as path from 'node:path';-import {discoverComponents, findComponentReadme, resolveImportPath} from './component-discovery.mjs';-import {getRunPrefix} from '../utils/package-manager.mjs';--export function cleanReadme(content, componentName) {- const displayName = componentName.startsWith('XDS')- ? componentName- : componentName.charAt(0).toUpperCase() + componentName.slice(1);-- const lines = content.split('\n');- const output = [];-- for (const line of lines) {- if (line.includes('<!-- SYNC:') || line.includes('SYNC:')) continue;-- if (line.startsWith('# /')) {- output.push(`# ${displayName}`);- continue;- }-- output.push(line);- }-- // Collapse consecutive blank lines- const cleaned = [];- let prevEmpty = false;- for (const line of output) {- const isEmpty = line.trim() === '';- if (isEmpty && prevEmpty) continue;- cleaned.push(line);- prevEmpty = isEmpty;- }-- // Trim trailing blank lines- while (cleaned.length > 0 && cleaned[cleaned.length - 1].trim() === '') {- cleaned.pop();- }-- return cleaned.join('\n') + '\n';-}--// Sections to skip in compact mode-const COMPACT_SKIP_SECTIONS = [- 'Files',- 'RTL Support',- 'Related',- 'Dividers',- 'Components',- 'Overview',-];-const MAX_EXAMPLES = 3;--/**- * Extract compact docs for LLM consumption.- * Keeps: title, description, Features, Usage (limited examples), Props, Implementation Notes.- * Drops: Files, RTL Support, Related, ASCII art, overflow code blocks.- */-export function extractCompact(content, componentName) {- const lines = content.split('\n');- const output = [];- let inSkipSection = false;- let inCodeBlock = false;- let codeBlockCount = 0;- let skipCurrentBlock = false;- let currentSection = null;-- const displayName = componentName.startsWith('XDS')- ? componentName- : componentName.charAt(0).toUpperCase() + componentName.slice(1);-- for (let i = 0; i < lines.length; i++) {- const line = lines[i];-- if (line.startsWith('```')) {- if (!inCodeBlock) {- inCodeBlock = true;- const nextLine = lines[i + 1] || '';- const isAsciiBlock =- /^[┌┐└┘├┤┬┴┼─│\s]+$/.test(nextLine) ||- /^\s*[│├└┌]/.test(nextLine);- if (isAsciiBlock) {- skipCurrentBlock = true;- continue;- }- if (codeBlockCount >= MAX_EXAMPLES) {- skipCurrentBlock = true;- continue;- }- codeBlockCount++;- skipCurrentBlock = false;- } else {- inCodeBlock = false;- if (skipCurrentBlock) {- skipCurrentBlock = false;- continue;- }- }- }-- if (inCodeBlock && skipCurrentBlock) continue;-- const sectionMatch = line.match(/^##\s+(.+)$/);- if (sectionMatch) {- const sectionName = sectionMatch[1].trim();- codeBlockCount = 0;-- if (COMPACT_SKIP_SECTIONS.some(s => sectionName.includes(s))) {- inSkipSection = true;- currentSection = sectionName;- continue;- }- inSkipSection = false;- currentSection = sectionName;- }-- const subsectionMatch = line.match(/^###\s+(.+)$/);- if (- subsectionMatch &&- currentSection === 'Usage' &&- codeBlockCount >= MAX_EXAMPLES- ) {- continue;- }-- if (inSkipSection) continue;- if (line.includes('<!-- SYNC:') || line.includes('SYNC:')) continue;- if (- /^[┌┐└┘├┤┬┴┼─│\s]+$/.test(line) ||- /^\s*[│├└┌]\s*/.test(line)- ) {- continue;- }-- if (line.startsWith('# /')) {- output.push(`# ${displayName}`);- continue;- }-- output.push(line);- }-- while (output.length > 0 && output[output.length - 1].trim() === '') {- output.pop();- }-- const cleaned = [];- let prevEmpty = false;- for (const line of output) {- const isEmpty = line.trim() === '';- if (isEmpty && prevEmpty) continue;- cleaned.push(line);- prevEmpty = isEmpty;- }-- return cleaned.join('\n') + '\n';-}--/**- * Extract a brief, LLM-optimized summary from a README.- *- * Format: component signature + key props + one usage example.- * Targets ~200-400 chars per component (vs ~2-3KB for --detail compact).- *- * Example output:- * Button(variant: primary|secondary|ghost|destructive, size: sm|md|lg)- * label: string (required) · isLoading isDisabled icon tooltip children- * <XDSButton variant="primary" onClick={fn}>Save</XDSButton>- */-export function extractBrief(content, componentName, importHint) {- const displayName = componentName.startsWith('XDS')- ? componentName- : `XDS${componentName}`;-- const lines = content.split('\n');-- // 1. Extract first paragraph as description- let description = '';- for (let i = 0; i < lines.length; i++) {- const line = lines[i].trim();- if (line.startsWith('#')) continue;- if (line === '') continue;- if (line.startsWith('|') || line.startsWith('```')) break;- description = line;- break;- }-- // 2. Extract props from the Props table- // Supports two README layouts:- // a) Single-component: `## Props` section with a table- // b) Multi-component: `### XDSComponentName` subsection with a table- const props = [];- let inPropsTable = false;- let headerParsed = false;- let inComponentSection = false;-- // For multi-component READMEs, find the section for this specific component- const componentSectionRe = new RegExp(- `^###\\s+${displayName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`- );-- for (const line of lines) {- // Detect `## Props` (single-component layout)- if (/^#{2,3}\s+Props/.test(line)) {- inPropsTable = true;- headerParsed = false;- continue;- }-- // Detect `### XDSComponentName` (multi-component layout)- if (componentSectionRe.test(line)) {- inComponentSection = true;- continue;- }-- // Exit component section when hitting another ### heading- if (inComponentSection && /^###\s+/.test(line) && !componentSectionRe.test(line)) {- inComponentSection = false;- if (inPropsTable) inPropsTable = false;- continue;- }-- // Within a component section, a pipe-delimited table is a props table- if (inComponentSection && !inPropsTable && /^\|\s*`?Prop/.test(line)) {- inPropsTable = true;- headerParsed = false;- // Don't continue — let the header row logic below handle it- }-- if (inPropsTable && /^#{2,3}\s+/.test(line) && !/Props/.test(line) && !inComponentSection) {- inPropsTable = false;- continue;- }- if (!inPropsTable) continue;-- // Skip table header separator- if (/^\|\s*-/.test(line)) {- headerParsed = true;- continue;- }- // Skip the header row itself- if (!headerParsed && /^\|\s*`?Prop/.test(line)) continue;-- // Parse prop row: | `name` | `type` | `default` | description |- const cells = line- .split('|')- .map(c => c.trim().replace(/`/g, ''))- .filter(Boolean);- if (cells.length >= 3) {- const name = cells[0];- const type = cells[1];- const defaultVal = cells[2] || '';- const desc = cells[3] || '';-- // Skip internal/style props- if (['xstyle', 'data-testid', 'className', 'style'].includes(name))- continue;-- props.push({name, type, defaultVal, desc});- }- }-- // 3. Build signature line from variant/size/type/level props- const signatureProps = [];- const otherProps = [];-- for (const prop of props) {- // Props with union types go in the signature- if (prop.type.includes('|') && !prop.type.includes('ReactNode')) {- const values = prop.type- .replace(/['"]/g, '')- .split('|')- .map(v => v.trim())- .join('|');- signatureProps.push(`${prop.name}: ${values}`);- } else if (prop.desc.includes('required') || prop.defaultVal === '—' || prop.defaultVal === '-') {- otherProps.unshift(`${prop.name}: ${prop.type.split('|')[0].trim()}`);- } else {- otherProps.push(prop.name);- }- }-- // 4. Extract first code example- // For multi-component READMEs, prefer examples from the component's section- let example = '';- let fallbackExample = '';- let inCode = false;- let inCompSection = false;-- for (const line of lines) {- // Track whether we're in this component's subsection- if (componentSectionRe.test(line)) {- inCompSection = true;- continue;- }- if (inCompSection && /^###\s+/.test(line) && !componentSectionRe.test(line)) {- inCompSection = false;- }-- if (line.startsWith('```tsx') || line.startsWith('```jsx')) {- inCode = true;- continue;- }- if (inCode && line.startsWith('```')) {- inCode = false;- continue;- }- if (inCode) {- const trimmed = line.trim();- // Take the first substantial JSX line- if (trimmed.startsWith('<XDS') || trimmed.startsWith('<')) {- if (inCompSection && !example) {- // Prefer example from this component's section- example = trimmed;- } else if (!fallbackExample) {- // Fallback: first example from anywhere in the README- fallbackExample = trimmed;- }- if (example) break; // Found one in the right section, done- }- }- }- // Use component-section example if found, otherwise fallback- if (!example) example = fallbackExample;-- // 5. Build output- const output = [];-- // Signature line- const sigStr =- signatureProps.length > 0- ? `${displayName}(${signatureProps.join(', ')})`- : displayName;- output.push(importHint ? `${sigStr} ← from '${importHint}'` : sigStr);-- // Description (shortened)- if (description) {- const shortDesc =- description.length > 80- ? description.slice(0, 77) + '...'- : description;- output.push(` ${shortDesc}`);- }-- // Other props- if (otherProps.length > 0) {- output.push(` ${otherProps.join(' · ')}`);- }-- // Example- if (example) {- output.push(` ${example}`);- }-- // Warn on stderr when extraction is incomplete (doesn't pollute brief output)- if (props.length === 0) {- console.warn(- `⚠️ No props found for ${displayName}. Ensure README has a '### ${displayName}' section with a props table.`,- );- }- if (!example) {- console.warn(`⚠️ No code example found for ${displayName}.`);- }-- return output.join('\n') + '\n';-}--/**- * Extract brief summaries for ALL components in one output.- * One read, zero round-trips — the LLM gets enough to use any component.- */-export function extractBriefAll(coreDir) {- const components = discoverComponents(coreDir);- const output = [];-- // Add xstyle override hint at the top- output.push(- `> **Style overrides:** Most components accept an \`xstyle\` prop.`,- `> Use inline objects for simple overrides: \`xstyle={{ maxWidth: 300 }}\``,- `> Use \`stylex.create()\` for pseudo-classes/media queries or 3+ properties.`,- `> See \`${getRunPrefix()} xds docs principles\` for details.\n`,- );-- for (const [category, comps] of Object.entries(components)) {- output.push(`## ${category}\n`);- for (const comp of comps) {- const readmePath = findComponentReadme(coreDir, comp);- if (readmePath) {- const content = fs.readFileSync(readmePath, 'utf-8');- const importPath = resolveImportPath(coreDir, comp);- output.push(extractBrief(content, comp, importPath));- } else {- output.push(`XDS${comp}\n (no docs)\n`);- }- }- }-- return output.join('\n');-}--/**- * Ensure compact output includes an import statement.- * If the output already contains `from '@xds/core`, returns as-is.- * Otherwise, injects an ## Import section after the title/description,- * before the first ## section.- */-export function ensureImportStatement(compactOutput, componentName, coreDir) {- // Already has an Import section — return as-is- if (/^## Import$/m.test(compactOutput)) {- return compactOutput;- }-- const displayName = componentName.startsWith('XDS')- ? componentName- : `XDS${componentName}`;-- const importPath = resolveImportPath(coreDir, componentName);- const importBlock = `## Import\n\n\`\`\`tsx\nimport { ${displayName} } from '${importPath}';\n\`\`\`\n`;-- // Find the first ## section and inject before it- const lines = compactOutput.split('\n');- const output = [];- let injected = false;-- for (let i = 0; i < lines.length; i++) {- if (!injected && lines[i].startsWith('## ')) {- output.push(importBlock);- injected = true;- }- output.push(lines[i]);- }-- // If no ## section found, append at the end- if (!injected) {- output.push('');- output.push(importBlock);- }-- return output.join('\n');-}--/**- * Extract only the Props section(s) from a README.- * Useful for quick reference and LLM context.- */-export function extractProps(content, componentName) {- const lines = content.split('\n');- const output = [];- let inPropsSection = false;- let sectionDepth = 0;-- for (const line of lines) {- // Detect Props section (## Props or ### XDSFoo Props)- if (/^#{2,3}\s+.*Props/.test(line)) {- inPropsSection = true;- sectionDepth = line.match(/^(#+)/)[1].length;- output.push(line);- continue;- }-- // Exit props section when hitting another section at same or higher level- if (inPropsSection && /^#{2,3}\s+/.test(line) && !line.includes('Props')) {- const depth = line.match(/^(#+)/)[1].length;- if (depth <= sectionDepth) {- inPropsSection = false;- continue;- }- }-- if (inPropsSection) {- output.push(line);- }- }-- if (output.length === 0) {- return `No props documentation found for ${componentName}.\n`;- }-- // Trim trailing blank lines- while (output.length > 0 && output[output.length - 1].trim() === '') {- output.pop();- }-- return output.join('\n') + '\n';-}--// ── Format functions ────────────────────────────────────────────────-// These operate on the typed ComponentDoc object directly.-// Used by the CLI action handler for .doc.mjs files.--/**- * Render a props array as a markdown table.- */\ No newline at end of filediff --git a/packages/cli/src/types/api.d.ts b/packages/cli/src/types/api.d.tsnew file mode 100644index 0000000000..0b8cd7b44d--- /dev/null+++ b/packages/cli/src/types/api.d.ts@@ -0,0 +1,98 @@+/**+ * Programmatic API types for @xds/cli/api.+ *+ * Every function returns the same { type, data } envelope as `xds --json`.+ * Errors throw XDSError.+ */++import type {+ ComponentListResponse,+ ComponentBriefResponse,+ ComponentDetailResponse,+ ComponentDetailPropsResponse,+ ComponentDetailSourceResponse,+} from './component';+import type {+ DocsListResponse,+ DocsDetailResponse,+ DocsDetailSectionResponse,+} from './docs';+import type {+ DiscoverListResponse,+ DiscoverDetailResponse,+ DiscoverDetailDocResponse,+ DiscoverSearchResponse,+} from './discover';++/** Structured API error with optional suggestions. */+export declare class XDSError extends Error {+ suggestions?: Array<{name: string; reason: string}>;+ constructor(+ message: string,+ suggestions?: Array<{name: string; reason: string}>,+ );+}++// ── Component ────────────────────────────────────────────────────────++export interface ComponentOptions {+ cwd?: string;+ list?: boolean;+ category?: string;+ props?: boolean;+ source?: boolean;+ detail?: 'full' | 'compact' | 'brief';+ lang?: string;+ zh?: boolean;+ dense?: boolean;+}++type ComponentResult =+ | ComponentListResponse+ | ComponentBriefResponse+ | ComponentDetailResponse+ | ComponentDetailPropsResponse+ | ComponentDetailSourceResponse;++export declare function component(+ name?: string,+ options?: ComponentOptions,+): Promise<ComponentResult>;++// ── Docs ─────────────────────────────────────────────────────────────++export interface DocsOptions {+ lang?: string;+ zh?: boolean;+ dense?: boolean;+}++type DocsResult =+ | DocsListResponse+ | DocsDetailResponse+ | DocsDetailSectionResponse;++export declare function docs(+ topic?: string,+ section?: string,+ options?: DocsOptions,+): Promise<DocsResult>;++// ── Discover ─────────────────────────────────────────────────────────++export interface DiscoverOptions {+ components?: boolean;+ lang?: string;+ zh?: boolean;+}++type DiscoverResult =+ | DiscoverListResponse+ | DiscoverDetailResponse+ | DiscoverDetailDocResponse+ | DiscoverSearchResponse;++export declare function discover(+ query?: string,+ options?: DiscoverOptions,+): Promise<DiscoverResult>;diff --git a/packages/cli/src/types/base.d.ts b/packages/cli/src/types/base.d.tsindex d527e833ec..f42e433755 100644--- a/packages/cli/src/types/base.d.ts+++ b/packages/cli/src/types/base.d.ts@@ -2,7 +2,6 @@* Shared types for the XDS CLI JSON API.** CLIError and CLIUnsupportedError are the two error shapes.- * CLIMarkdownResponse is the shared fallback for legacy .md files.* CLIAnyResponse is the union of all success response types.* CLIResult<T> wraps any response with possible errors.*/@@ -45,12 +44,6 @@ export interface CLIUnsupportedError {error: `JSON output is not supported for the '${string}' command`;}-/** Legacy markdown fallback envelope. */-export interface CLIMarkdownResponse {- type: 'markdown';- data: {name: string; format: 'markdown'; content: string};-}-/** Wrap any response type to include possible error shapes. */export type CLIResult<T> = T | CLIError | CLIUnsupportedError;@@ -76,8 +69,7 @@ export type CLIAnyResponse =| UpgradeListResponse| UpgradeRunResponse| GapReportCategoriesResponse- | GapReportFileResponse- | CLIMarkdownResponse;+ | GapReportFileResponse;/** Union of all type discriminator string literals. */export type CLIResponseType = CLIAnyResponse['type'];diff --git a/packages/cli/src/types/component.d.ts b/packages/cli/src/types/component.d.tsindex 90ae5efa23..bb5cb598e9 100644--- a/packages/cli/src/types/component.d.ts+++ b/packages/cli/src/types/component.d.ts@@ -10,7 +10,6 @@* xds --json component Button -> component.detail* xds --json component Button --props -> component.detail.props* xds --json component Button --source -> component.detail.source- * xds --json component Button (legacy .md) -> markdown (CLIMarkdownResponse)* (not found) -> CLIError*/diff --git a/packages/cli/src/types/docs.d.ts b/packages/cli/src/types/docs.d.tsindex d1478adaa1..b152eff814 100644--- a/packages/cli/src/types/docs.d.ts+++ b/packages/cli/src/types/docs.d.ts@@ -6,7 +6,6 @@* xds --json docs -> docs.list* xds --json docs <topic> -> docs.detail* xds --json docs <topic> <section> -> docs.detail.section- * xds --json docs <topic> (legacy .md) -> markdown (CLIMarkdownResponse)* (unknown topic/section) -> CLIError*/diff --git a/packages/core/src/FormLayout/README.md b/packages/core/src/FormLayout/README.mddeleted file mode 100644index a25fbc17c5..0000000000--- a/packages/core/src/FormLayout/README.md+++ /dev/null@@ -1,129 +0,0 @@-# FormLayout--A spatial layout container for arranging form fields with consistent spacing and direction.--<!-- SYNC: When files in this directory change, update this document. -->--## Features--- **Three Layout Modes**: Vertical (default), horizontal, and horizontal-labels-- **Direction Context**: Provides layout direction to children via React context-- **Responsive**: Horizontal-labels collapses to vertical on narrow viewports (≤480px)-- **Nestable**: FormLayout inside FormLayout works naturally — inner overrides context-- **Purely Spatial**: Does not manage form state or render `<form>` — form submission is separate-- **Styled with StyleX**: Uses XDS design tokens for consistent spacing--## Components--### XDSFormLayout--Arranges form fields with consistent spacing and direction.--```tsx-<XDSFormLayout direction="vertical">- <XDSTextInput label="Name" value={name} onChange={setName} />- <XDSTextInput label="Email" value={email} onChange={setEmail} />-</XDSFormLayout>-```--| Prop | Type | Default | Description |-| ------------- | --------------------------------------------------- | ------------ | -------------------------------------- |-| `direction` | `'vertical' \| 'horizontal' \| 'horizontal-labels'` | `'vertical'` | Direction of field arrangement |-| `children` | `ReactNode` | — | Form fields to arrange |-| `xstyle` | `StyleXStyles` | — | StyleX styles for the layout container |-| `data-testid` | `string` | — | Test ID for the root element |-| `ref` | `Ref<HTMLDivElement>` | — | Ref to the root div element |--Also accepts standard HTML `div` attributes (`id`, `role`, `aria-*`, etc.).--## Layout Modes--### Vertical (default)--Fields stack top-to-bottom with consistent gap. Most common pattern for simple forms and dialogs.--```tsx-<XDSFormLayout>- <XDSTextInput label="Name" ... />- <XDSTextInput label="Email" ... />-</XDSFormLayout>-```--### Horizontal--Fields arrange left-to-right, each getting equal flex-grow. Wraps when the container is too narrow. Used for related fields (first/last name, city/state/zip).--```tsx-<XDSFormLayout direction="horizontal">- <XDSTextInput label="First Name" ... />- <XDSTextInput label="Last Name" ... />-</XDSFormLayout>-```--### Horizontal Labels--CSS Grid layout with labels to the left of inputs. Collapses to vertical on narrow viewports (≤480px). Used for settings panels and admin forms.--```tsx-<XDSFormLayout direction="horizontal-labels">- <XDSTextInput label="Display Name" ... />- <XDSSelector label="Timezone" ... />-</XDSFormLayout>-```--## Composition Patterns--### Nesting--```tsx-<XDSFormLayout direction="vertical">- <XDSFormLayout direction="horizontal">- <XDSTextInput label="First Name" ... />- <XDSTextInput label="Last Name" ... />- </XDSFormLayout>- <XDSTextInput label="Email" ... />-</XDSFormLayout>-```--### With Custom Controls--Use `XDSField` to wrap custom controls that need labels:--```tsx-<XDSFormLayout>- <XDSTextInput label="Name" ... />- <XDSField label="Permissions" inputID="perms">- <CheckboxGroup id="perms" ... />- </XDSField>-</XDSFormLayout>-```--### Dialog Composition--FormLayout does not include buttons. In dialogs, connect buttons via the HTML `form` attribute:--```tsx-<XDSDialog>- <form id="edit-form" onSubmit={handleSubmit}>- <XDSFormLayout>- <XDSTextInput label="Name" ... />- </XDSFormLayout>- </form>- <XDSDialogFooter>- <XDSButton label="Save" type="submit" form="edit-form" />- </XDSDialogFooter>-</XDSDialog>-```--## Context--`XDSFormLayoutContext` provides `{ direction: XDSFormLayoutDirection }` to children. Import from `@xds/core/FormLayout` to read the current layout direction in custom components.--## Files--| File | Role | Purpose |-| ------------------------- | ------- | --------------------------- |-| `index.ts` | Entry | Exports component and types |-| `XDSFormLayout.tsx` | Core | Component implementation |-| `XDSFormLayoutContext.ts` | Context | Direction context |-| `XDSFormLayout.test.tsx` | Test | Unit tests |diff --git a/packages/core/src/MobileNav/README.md b/packages/core/src/MobileNav/README.mddeleted file mode 100644index 22c746de5a..0000000000--- a/packages/core/src/MobileNav/README.md+++ /dev/null@@ -1,170 +0,0 @@-# MobileNav--Slide-out drawer overlay for mobile navigation. The mobile counterpart to `XDSSideNav` — accepts the same children (`XDSSideNavSection`, `XDSSideNavItem`, or any ReactNode).--## Components--| Component | Description |-| -------------- | ----------------------------------------------------------------- |-| `XDSMobileNav` | Full-height drawer overlay with backdrop, close button, and title |--## Files--| File | Purpose |-| ----------------------- | ---------------- |-| `XDSMobileNav.tsx` | Drawer component |-| `XDSMobileNav.test.tsx` | Unit tests |-| `index.ts` | Public exports |--## Usage--```tsx-import {XDSMobileNav} from '@xds/core/MobileNav';-```--### Basic — hamburger menu with nav links--```tsx-const [isOpen, setIsOpen] = useState(false);--<XDSButton- label="Menu"- icon={<MenuIcon />}- variant="ghost"- onClick={() => setIsOpen(true)}-/>--<XDSMobileNav- isOpen={isOpen}- onOpenChange={(open) => setIsOpen(open)}- title="Navigation"->- <XDSSideNavSection title="Main">- <XDSSideNavItem label="Dashboard" href="/dashboard" isSelected />- <XDSSideNavItem label="Analytics" href="/analytics" />- <XDSSideNavItem label="Settings" href="/settings" />- </XDSSideNavSection>-</XDSMobileNav>-```--### Responsive — sidebar on desktop, drawer on mobile--Use a media query to show `XDSSideNav` on desktop and `XDSMobileNav` on mobile. The same nav items work in both:--```tsx-const isMobile = useMediaQuery('(max-width: 768px)');-const [drawerOpen, setDrawerOpen] = useState(false);--const navSections = (- <>- <XDSSideNavSection title="Main">- <XDSSideNavItem label="Dashboard" href="/" isSelected />- <XDSSideNavItem label="Projects" href="/projects" />- </XDSSideNavSection>- <XDSSideNavSection title="Settings">- <XDSSideNavItem label="General" href="/settings" />- <XDSSideNavItem label="Security" href="/security" />- </XDSSideNavSection>- </>-);--{- isMobile ? (- <>- <XDSButton- label="Menu"- icon={<MenuIcon />}- variant="ghost"- onClick={() => setDrawerOpen(true)}- />- <XDSMobileNav- isOpen={drawerOpen}- onOpenChange={open => setDrawerOpen(open)}- title="My App">- {navSections}- </XDSMobileNav>- </>- ) : (- <XDSSideNav>{navSections}</XDSSideNav>- );-}-```--### With top nav items moving to drawer--When top nav items need to collapse into the mobile drawer:--```tsx-const isMobile = useMediaQuery('(max-width: 768px)');-const [drawerOpen, setDrawerOpen] = useState(false);--<XDSTopNav- heading={<XDSTopNavHeading heading="My App" />}- startContent={- isMobile ? (- <XDSButton- label="Menu"- icon={<MenuIcon />}- variant="ghost"- onClick={() => setDrawerOpen(true)}- />- ) : (- <>- <XDSTopNavItem label="Home" href="/" isSelected />- <XDSTopNavItem label="Products" href="/products" />- <XDSTopNavItem label="Docs" href="/docs" />- </>- )- }-/>--<XDSMobileNav isOpen={drawerOpen} onOpenChange={(open) => setDrawerOpen(open)}>- <XDSSideNavSection title="Navigation">- <XDSSideNavItem label="Home" href="/" isSelected />- <XDSSideNavItem label="Products" href="/products" />- <XDSSideNavItem label="Docs" href="/docs" />- </XDSSideNavSection>-</XDSMobileNav>-```--## Props--| Prop | Type | Default | Description |-| -------------- | --------------------------- | ------- | ----------------------------------------------- |-| `isOpen` | `boolean` | — | Whether the drawer is open (required) |-| `onOpenChange` | `(isOpen: boolean) => void` | — | Called when drawer visibility changes |-| `children` | `ReactNode` | — | Drawer content (XDSSideNavSection, items, etc.) |-| `title` | `string` | — | Optional title at the top of the drawer |-| `width` | `number` | `280` | Drawer width in pixels (capped at 85vw) |-| `side` | `'start' \| 'end'` | `start` | Which side the drawer slides from |-| `data-testid` | `string` | — | Test ID for the root element |--## Accessibility--Uses the native `<dialog>` element with `showModal()` for top-layer rendering. The browser provides focus trapping, body scroll lock, and `::backdrop` — no manual z-index needed.--- Native `<dialog>` in top layer (no z-index stacking issues)-- `aria-label` set to title or "Navigation"-- Focus trapping via `showModal()` (browser-native)-- Escape key closes via native `cancel` event-- Backdrop click closes-- Body scroll locked while modal is open--## Composition with XDSSideNav--`XDSMobileNav` and `XDSSideNav` are designed to share children. Extract your nav sections into a variable and render them in both:--```tsx-const sections = (- <XDSSideNavSection title="Main">- <XDSSideNavItem label="Home" href="/" />- <XDSSideNavItem label="Settings" href="/settings" />- </XDSSideNavSection>-);--// Desktop: sidebar-<XDSSideNav>{sections}</XDSSideNav>--// Mobile: drawer-<XDSMobileNav isOpen={open} onOpenChange={(open) => { if (!open) close(); }}>{sections}</XDSMobileNav>-```diff --git a/packages/core/src/MoreMenu/README.md b/packages/core/src/MoreMenu/README.mddeleted file mode 100644index 99200516f4..0000000000--- a/packages/core/src/MoreMenu/README.md+++ /dev/null@@ -1,155 +0,0 @@-# MoreMenu--Overflow menu with a three-dot icon trigger. A convenience wrapper that composes an icon-only XDSButton with a dropdown menu, eliminating the boilerplate of wiring up state management, positioning, and accessibility attributes.--<!-- SYNC: When files in this directory change, update this document. -->--## Features--- **Zero-config defaults**: Three-dot icon, "More options" label, ghost variant — just pass `items`-- **Data-driven items**: Same `items` prop as XDSDropdownMenu (items, dividers, sections)-- **Icon-only trigger**: Always renders as a square icon button with aria-label-- **Keyboard navigation**: Full keyboard support (Arrow keys, Home, End, Enter, Space, Escape)-- **Accessibility**: Proper ARIA roles (`menu`, `menuitem`), `aria-haspopup`, `aria-expanded`-- **Tooltip**: Shows label on hover, hidden when menu is open-- **Custom rendering**: Optional `children` render function for custom item content--## Usage--```tsx-import {XDSMoreMenu} from '@xds/core/MoreMenu';--// Minimal — just actions-<XDSMoreMenu- items={[- { label: 'Edit', onClick: handleEdit },- { label: 'Delete', onClick: handleDelete },- ]}-/>--// With custom label and size (e.g., table row actions)-<XDSMoreMenu- label="Row actions"- size="sm"- items={[- { label: 'Edit', icon: PencilIcon, onClick: () => handleEdit(row) },- { type: 'divider' },- { label: 'Delete', icon: TrashIcon, onClick: () => handleDelete(row) },- ]}-/>--// With sections-<XDSMoreMenu- label="Document actions"- items={[- {- type: 'section',- title: 'Actions',- items: [- { label: 'Edit', onClick: handleEdit },- { label: 'Duplicate', onClick: handleDuplicate },- ],- },- {- type: 'section',- title: 'Danger zone',- items: [- { label: 'Delete', onClick: handleDelete },- ],- },- ]}-/>--// With custom item rendering-<XDSMoreMenu- label="User actions"- items={actions}->- {item => (- <XDSDropdownMenuItem- icon={item.icon}- label={item.label}- description={item.description}- />- )}-</XDSMoreMenu>-```--## Composition Stories--### Table row actions--```tsx-<td>- <XDSMoreMenu- size="sm"- label="Row actions"- items={[- {label: 'Edit', icon: PencilIcon, onClick: () => handleEdit(row)},- {type: 'divider'},- {label: 'Delete', icon: TrashIcon, onClick: () => handleDelete(row)},- ]}- />-</td>-```--### Card header--```tsx-<div- style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- }}>- <XDSHeading level={3}>Card Title</XDSHeading>- <XDSMoreMenu- items={[- {label: 'Edit', onClick: handleEdit},- {label: 'Duplicate', onClick: handleDuplicate},- {type: 'divider'},- {label: 'Delete', onClick: handleDelete},- ]}- />-</div>-```--### Toolbar (alongside other buttons)--```tsx-<div style={{display: 'flex', gap: 8}}>- <XDSButton label="Save" variant="primary" />- <XDSButton label="Preview" variant="secondary" />- <XDSMoreMenu label="More actions" items={overflowActions} />-</div>-```--## Props--### XDSMoreMenu--| Prop | Type | Default | Description |-| ------------- | ---------------------------------------------- | ---------------- | ---------------------------------------------- |-| `items` | `XDSDropdownMenuOption[]` | — | Menu items (items, dividers, or sections) |-| `label` | `string` | `'More options'` | Accessible label (aria-label) and tooltip text |-| `variant` | `XDSButtonVariant` | `'ghost'` | Visual style variant of the trigger button |-| `size` | `XDSButtonSize` | `'md'` | Size of the trigger button |-| `icon` | `ReactNode` | Three-dot icon | Override the default three-dot icon |-| `isDisabled` | `boolean` | `false` | Whether the menu trigger is disabled |-| `children` | `(item: XDSDropdownMenuItemData) => ReactNode` | — | Custom render function for items |-| `data-testid` | `string` | — | Test ID for testing frameworks |--## When to use XDSMoreMenu vs XDSDropdownMenu--- **XDSMoreMenu**: Icon-only trigger (three dots), no visible label. Best for overflow actions in tight spaces (table rows, card headers, list items).-- **XDSDropdownMenu**: Labeled trigger button with chevron. Best for primary dropdown selections (file menus, action selectors).--For full control over the trigger or menu content, compose `XDSButton` + `useXDSLayer` + `XDSDropdownMenuItem` directly.--## Files--| File | Role | Purpose |-| ---------------------- | ------- | ----------------------------- |-| `index.ts` | Entry | Exports component and types |-| `XDSMoreMenu.tsx` | Core | Main component implementation |-| `XDSMoreMenu.test.tsx` | Testing | Unit tests |diff --git a/packages/core/src/MultiSelector/README.md b/packages/core/src/MultiSelector/README.mddeleted file mode 100644index a1c99ba729..0000000000--- a/packages/core/src/MultiSelector/README.md+++ /dev/null@@ -1,70 +0,0 @@-# MultiSelector--Multi-select dropdown with checkboxes for choosing multiple items from a list.--<!-- SYNC: When files in this directory change, update this document. -->--## Overview--XDSMultiSelector is a checkbox dropdown for small, finite lists — column toggles, filter facets, permissions. For large/open sets with typeahead search, use XDSTokenizer instead.--- **Checkbox items** — real `XDSCheckboxInput` for each option-- **Select all** — optional toggle with indeterminate state-- **Search** — optional filter-in-place-- **Trigger display** — count, labels, or badge chips-- **Sections** — reuses `XDSSelector` option type model-- **Selected-first sort** — selected items sort to top on open (stable during interaction)--## Import--```tsx-import {XDSMultiSelector} from '@xds/core/MultiSelector';-```--## Usage--```tsx-<XDSMultiSelector- label="Columns"- options={['Name', 'Email', 'Role', 'Status']}- value={selected}- onChange={setSelected}- hasSelectAll-/>-```--## Key Props--| Prop | Type | Default | Description |-| ---------------- | --------------------------------- | --------- | ----------------------------------------------- |-| `label` | `string` | required | Accessible label |-| `options` | `XDSMultiSelectorOptionType[]` | required | Items — strings, objects, dividers, or sections |-| `value` | `string[]` | required | Currently selected values |-| `onChange` | `(value: string[]) => void` | required | Selection change callback |-| `hasSelectAll` | `boolean` | `false` | Show select-all toggle |-| `hasSearch` | `boolean` | `false` | Show search/filter input |-| `triggerDisplay` | `'count' \| 'labels' \| 'badges'` | `'count'` | How trigger shows selections |-| `maxBadges` | `number` | `3` | Max badges before "+N" |-| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Size variant |-| `status` | `{type, message?}` | — | Validation state |-| `isDisabled` | `boolean` | `false` | Disable the selector |-| `onChangeAction` | `(value) => Promise` | — | Async action with optimistic UI |--## Theming--The trigger renders `xdsClassName('multi-selector', {size, status})`. Theme authors-target these classes via `defineTheme({ components })`:--```ts-defineTheme({- name: 'custom',- components: {- 'multi-selector': {- base: {borderRadius: 'var(--radius-3)'},- 'size:sm': {fontSize: '12px'},- },- },-});-```--See the [Theming Infrastructure wiki](https://github.com/facebookexperimental/xds/wiki/Theming-Infrastructure).diff --git a/packages/core/src/Pagination/README.md b/packages/core/src/Pagination/README.mddeleted file mode 100644index 5b10521441..0000000000--- a/packages/core/src/Pagination/README.md+++ /dev/null@@ -1,114 +0,0 @@-# Pagination--Standalone pagination controls for navigating through pages of content.--## Files--| File | Purpose |-| ------------------------ | ----------------------------- |-| `XDSPagination.tsx` | Main component implementation |-| `XDSPagination.test.tsx` | Unit tests |-| `index.ts` | Public exports |-| `README.md` | This file |--## Exports--- `XDSPagination` — Main pagination component-- `generatePageRange` — Utility to compute visible page numbers with ellipsis-- `XDSPaginationProps` — Props type-- `XDSPaginationVariant` — Variant type (`'pages' | 'count' | 'compact' | 'dots' | 'none'`)-- `XDSPaginationSize` — Size type (`'sm' | 'md'`)--## Usage--```tsx-import {XDSPagination} from '@xds/core/Pagination';--// Page number buttons (default)-<XDSPagination- page={page}- onChange={setPage}- totalItems={200}- pageSize={20}-/>--// Count display with page size selector-<XDSPagination- page={page}- onChange={setPage}- totalItems={200}- variant="count"- pageSizeOptions={[10, 20, 50]}- onPageSizeChange={setPageSize}-/>--// Cursor-based (no total known)-<XDSPagination- page={page}- onChange={setPage}- hasMore={data.hasNextPage}-/>--// Carousel dots-<XDSPagination- page={slideIndex}- onChange={setSlideIndex}- totalPages={slides.length}- variant="dots"-/>-```--## Props--| Prop | Type | Default | Description |-| ------------------ | ----------------------------------------- | -------------- | -------------------------------------------- |-| `page` | `number` | — | Current page number (1-based, required) |-| `onChange` | `(page: number) => void` | — | Called when page changes (required) |-| `onChangeAction` | `(page: number) => void \| Promise<void>` | — | Async action on page change |-| `totalItems` | `number` | — | Total item count (calculates pages) |-| `totalPages` | `number` | — | Total page count (alternative to totalItems) |-| `hasMore` | `boolean` | — | Whether more pages exist (cursor-based) |-| `pageSize` | `number` | `10` | Items per page |-| `pageSizeOptions` | `number[]` | — | Shows page size selector when provided |-| `onPageSizeChange` | `(pageSize: number) => void` | — | Called when page size changes |-| `variant` | `XDSPaginationVariant` | `'pages'` | Visual variant |-| `siblingCount` | `number` | `1` | Pages shown around current (pages variant) |-| `size` | `XDSPaginationSize` | `'md'` | Size of controls |-| `isDisabled` | `boolean` | `false` | Whether the component is disabled |-| `label` | `string` | `'Pagination'` | Accessible label for nav landmark |-| `data-testid` | `string` | — | Test ID |-| `xstyle` | `StyleXStyles` | — | StyleX overrides |--## Variants--- **pages** — Clickable page number buttons with ellipsis truncation-- **count** — "1–20 of 200" text display-- **compact** — "Page 1 of 10" text display-- **dots** — Dot indicators (best for ≤10 pages)-- **none** — Just prev/next buttons--## Accessibility--- Root is `<nav>` with `aria-label`-- Current page has `aria-current="page"`-- Prev/next buttons have descriptive `aria-label`-- Ellipsis elements are `aria-hidden`-- All interactive elements are keyboard accessible--## Implementation Notes--- Page number buttons use `XDSButton` (`variant="ghost"` for inactive, `variant="primary"` for active page) for theming and swizzle compatibility.-- Prev/next buttons use `XDSButton` with `variant="ghost"` and icon-only mode.-- Dot indicators remain custom elements (intentionally different visual treatment from buttons).--## Theme Integration--```typescript-// Override via ComponentStyles-theme.components.pagination = {- root: {- /* root nav styles */- },-};-// Page buttons inherit theming from XDSButton's component styles-```diff --git a/packages/core/src/Tokenizer/README.md b/packages/core/src/Tokenizer/README.mddeleted file mode 100644index b38bd025c1..0000000000--- a/packages/core/src/Tokenizer/README.md+++ /dev/null@@ -1,71 +0,0 @@-# Tokenizer--Multi-select typeahead with token chips for selected items.--<!-- SYNC: When files in this directory change, update this document. -->--## Overview--XDSTokenizer combines XDSBaseTypeahead (search) with XDSToken (chips) for multi-item selection. It supports:--- **Token chips** for each selected item with remove buttons-- **Filtered search** that excludes already-selected items-- **Max entries** to limit selections-- **Clear all** button for bulk removal-- **Custom token and item rendering**-- **Backspace to remove** the last token--## Import--```tsx-import {XDSTokenizer} from '@xds/core/Tokenizer';-```--## Usage--```tsx-const source = {- search: query => users.filter(u => u.label.includes(query)),- bootstrap: () => users.slice(0, 5),-};--<XDSTokenizer- label="Team Members"- searchSource={source}- value={selected}- onChange={(items, change) => {- setSelected(items);- // change.type is 'add' | 'remove' | 'reorder'- }}- placeholder="Search people..."- hasClear- maxEntries={10}-/>;-```--## Key Props--| Prop | Type | Default | Description |-| -------------- | ------------------------------- | -------- | --------------------------------------- |-| `label` | `string` | required | Accessible label |-| `searchSource` | `XDSSearchSource` | required | Data source |-| `value` | `T[]` | required | Selected items |-| `onChange` | `(items, change) => void` | required | Selection callback with change metadata |-| `maxEntries` | `number` | — | Max number of selections |-| `hasClear` | `boolean` | `false` | Show "Clear all" button |-| `renderToken` | `(item, onRemove) => ReactNode` | — | Custom token renderer |-| `renderItem` | `(item) => ReactNode` | — | Custom dropdown item renderer |-| `placeholder` | `string` | — | Input placeholder |-| `isDisabled` | `boolean` | `false` | Disable input and tokens |-| `status` | `XDSInputStatus` | — | Validation status |--## Change Metadata--The `onChange` callback receives a second argument describing what changed:--```tsx-type XDSTokenizerChange<T> =- | {item: T; type: 'add'}- | {item: T; type: 'remove'}- | {type: 'reorder'};-```diff --git a/packages/core/src/Typeahead/README.md b/packages/core/src/Typeahead/README.mddeleted file mode 100644index 53b0c4dd1a..0000000000--- a/packages/core/src/Typeahead/README.md+++ /dev/null@@ -1,80 +0,0 @@-# Typeahead--Searchable dropdown components for single-item selection with keyboard navigation.--<!-- SYNC: When files in this directory change, update this document. -->--## Overview--The Typeahead module provides a search-as-you-type dropdown for selecting items from a data source. It supports:--- **Async and sync search** via a `searchSource` interface-- **Keyboard navigation** (arrow keys, Enter, Escape)-- **Bootstrap results** shown on focus before typing-- **Custom item rendering** for rich dropdown content-- **Combobox ARIA pattern** for full accessibility--## Import--```tsx-import {XDSTypeahead} from '@xds/core/Typeahead';-```--## Components--### XDSTypeahead--Styled typeahead with label, description, validation, and all field features. This is the primary component for most use cases.--```tsx-const source = {- search: query => fruits.filter(f => f.label.includes(query)),- bootstrap: () => fruits.slice(0, 5),-};--<XDSTypeahead- label="Fruit"- searchSource={source}- value={selected}- onChange={setSelected}- placeholder="Search fruits..."-/>;-```--### XDSBaseTypeahead--Unstyled typeahead for custom compositions (used by XDSTypeahead and XDSTokenizer). Provides the combobox input, dropdown, and keyboard handling without any field chrome.--### XDSTypeaheadItem--Default dropdown item renderer. Shows label with optional icon, secondary text, and avatar.--## Search Source Interface--```tsx-type XDSSearchSource<T> = {- search: (query: string) => T[] | Promise<T[]>;- bootstrap?: () => T[] | Promise<T[]>;-};--type XDSSearchableItem = {- id: string;- label: string;- [key: string]: unknown;-};-```--## Key Props--| Prop | Type | Default | Description |-| ------------------- | --------------------------- | -------- | ------------------------------- |-| `label` | `string` | required | Accessible label |-| `searchSource` | `XDSSearchSource` | required | Data source |-| `value` | `T \| null` | required | Selected item |-| `onChange` | `(item: T \| null) => void` | required | Selection callback |-| `placeholder` | `string` | — | Input placeholder |-| `hasEntriesOnFocus` | `boolean` | `false` | Show bootstrap results on focus |-| `hasClear` | `boolean` | `true` | Show clear button |-| `isDisabled` | `boolean` | `false` | Disable input |-| `maxMenuItems` | `number` | `10` | Max dropdown items |-| `status` | `XDSInputStatus` | — | Validation status |