An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): show import path in full component docs, clarify Table column shape (#2571)
Cindy Zhang1218a1747566
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjsindex a19e460fbf..fe5ee2655a 100644--- a/packages/cli/src/commands/component/index.mjs+++ b/packages/cli/src/commands/component/index.mjs@@ -146,7 +146,9 @@ export function registerComponent(program) {const importHint = resolveImportPath(coreDir, resolvedName);humanLog(formatCompact(result.data, resolvedName, importHint));} else {- humanLog(formatFull(result.data, {themeData}));+ const resolvedName = (name || '').replace(/^XDS/, '');+ const importHint = resolveImportPath(coreDir, resolvedName);+ humanLog(formatFull(result.data, {themeData, importHint}));}const compName = (name || '').replace(/^XDS/, '');const related = await findRelatedBlocks(compName);diff --git a/packages/cli/src/commands/import-hint-correctness.test.mjs b/packages/cli/src/commands/import-hint-correctness.test.mjsnew file mode 100644index 0000000000..1ce55f5f2e--- /dev/null+++ b/packages/cli/src/commands/import-hint-correctness.test.mjs@@ -0,0 +1,182 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Validates that every CLI-discoverable component produces a correct+ * import hint that matches an actual package.json export subpath.+ *+ * This guards against:+ * - Import paths pointing to non-existent exports+ * - Case mismatches (Theme vs theme)+ * - Group names leaking as import paths+ * - resolveImportPath regressions+ *+ * Runs against the real packages/core source, not mocks.+ */++import {describe, it, expect} from 'vitest';+import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {+ resolveImportPath,+ discoverComponents,+ findComponentSource,+} from './component/index.mjs';+import {findCoreDir} from '../utils/paths.mjs';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');+const REPO_ROOT = path.resolve(__dirname, '../../../..');++function runCli(args) {+ try {+ const out = execFileSync('node', [CLI_BIN, ...args], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {...process.env, FORCE_COLOR: '0'},+ });+ return {code: 0, stdout: out, stderr: ''};+ } catch (e) {+ return {+ code: e.status ?? 1,+ stdout: e.stdout?.toString() ?? '',+ stderr: e.stderr?.toString() ?? '',+ };+ }+}++describe('import hint correctness', () => {+ const coreDir = findCoreDir();+ const pkg = JSON.parse(+ fs.readFileSync(path.join(coreDir, 'package.json'), 'utf-8'),+ );+ const validExports = new Set(+ Object.keys(pkg.exports || {})+ .filter(k => k !== '.' && k !== './package.json')+ .map(k => k.replace('./', '')),+ );++ const componentMap = discoverComponents(coreDir);+ const groupNames = Object.keys(componentMap);++ // Collect all individual component names (non-group)+ const individualComponents = [];+ for (const [group, members] of Object.entries(componentMap)) {+ for (const member of members) {+ individualComponents.push(member);+ }+ }++ describe('every component resolves to a tree-shakeable subpath (not bare @xds/core)', () => {+ for (const name of individualComponents) {+ it(`${name} resolves to @xds/core/<subpath>, not bare @xds/core`, () => {+ const importPath = resolveImportPath(coreDir, name);++ // Must never be empty+ expect(importPath).toBeTruthy();++ // Must resolve to a specific subpath — bare @xds/core is not tree-shakeable+ expect(importPath).not.toBe('@xds/core');++ // The subpath must exist in package.json exports+ const subpath = importPath.replace('@xds/core/', '');+ expect(validExports.has(subpath)).toBe(true);+ });+ }+ });++ describe('import hint case matches package.json exports exactly', () => {+ for (const name of individualComponents) {+ it(`${name} import path has correct casing`, () => {+ const importPath = resolveImportPath(coreDir, name);+ if (importPath === '@xds/core') return; // skip bare fallback++ const subpath = importPath.replace('@xds/core/', '');++ // Must be an exact (case-sensitive) match to an export key+ const exportKeys = Object.keys(pkg.exports || {}).map(k =>+ k.replace('./', ''),+ );+ expect(exportKeys).toContain(subpath);+ });+ }+ });++ describe('CLI --detail brief shows correct import path', () => {+ // Test a representative set across different patterns+ const representative = [+ {name: 'Button', expected: '@xds/core/Button'},+ {name: 'Theme', expected: '@xds/core/theme'},+ {name: 'CheckboxInput', expected: '@xds/core/CheckboxInput'},+ {name: 'Table', expected: '@xds/core/Table'},+ {name: 'TextInput', expected: '@xds/core/TextInput'},+ {name: 'Layout', expected: '@xds/core/Layout'},+ {name: 'AppShell', expected: '@xds/core/AppShell'},+ {name: 'Card', expected: '@xds/core/Card'},+ {name: 'Dialog', expected: '@xds/core/Dialog'},+ {name: 'TabList', expected: '@xds/core/TabList'},+ ];++ for (const {name, expected} of representative) {+ it(`npx xds component ${name} --detail brief shows ${expected}`, () => {+ const result = runCli(['component', name, '--detail', 'brief']);+ expect(result.code).toBe(0);+ expect(result.stdout).toContain(expected);+ });+ }+ });++ describe('CLI --detail full shows import hint', () => {+ const representative = ['Button', 'Theme', 'Table', 'CheckboxInput'];++ for (const name of representative) {+ it(`npx xds component ${name} (full) includes import statement`, () => {+ const result = runCli(['component', name]);+ expect(result.code).toBe(0);+ // The PR adds: **Import:** `import {XDS...} from '...';`+ expect(result.stdout).toMatch(/import\s*\{/);+ expect(result.stdout).toContain('@xds/core');+ });+ }+ });++ describe('group names do NOT resolve to incorrect import paths', () => {+ const groups = ['Checkbox', 'Radio', 'Chat', 'Tabs', 'Resizable', 'Utilities'];++ for (const group of groups) {+ it(`group "${group}" does not produce a subpath import`, () => {+ // Groups should either fail to find a source file (returning bare @xds/core)+ // or correctly return the group-level export if one exists+ const importPath = resolveImportPath(coreDir, group);+ if (importPath !== '@xds/core') {+ // If it does resolve, it must be a valid export+ const subpath = importPath.replace('@xds/core/', '');+ expect(validExports.has(subpath)).toBe(true);+ }+ });+ }+ });++ describe('import path matches actual source file location', () => {+ for (const name of individualComponents) {+ it(`${name} import path leads to its source directory`, () => {+ const source = findComponentSource(coreDir, name);+ if (!source) return; // some sub-components don't have direct source++ const importPath = resolveImportPath(coreDir, name);+ if (importPath === '@xds/core') return;++ const subpath = importPath.replace('@xds/core/', '');+ const srcDir = path.join(coreDir, 'src');+ const relToSrc = path.relative(srcDir, source);+ const topDir = relToSrc.split(path.sep)[0];++ // The import subpath should match the top-level src directory+ // (case-insensitive check since theme/Theme is valid)+ expect(subpath.toLowerCase()).toBe(topDir.toLowerCase());+ });+ }+ });+});diff --git a/packages/cli/src/lib/component-format.mjs b/packages/cli/src/lib/component-format.mjsindex 2fd9521e55..b3d0f931a6 100644--- a/packages/cli/src/lib/component-format.mjs+++ b/packages/cli/src/lib/component-format.mjs@@ -103,6 +103,7 @@ function formatTargetsTable(docs, themeData) {* @param {object} docs - Component doc object* @param {object} [options] - Options* @param {object|null} [options.themeData] - Resolved theme data+ * @param {string|null} [options.importHint] - Import path hint (e.g. '@xds/core/Button')*/export function formatFull(docs, options = {}) {const sections = [];@@ -111,6 +112,11 @@ export function formatFull(docs, options = {}) {const desc = docs.usage?.description || docs.description || '';sections.push(desc + '\n');+ if (options.importHint) {+ const displayName = docs.components?.[0]?.name || `XDS${docs.name}`;+ sections.push(`**Import:** \`import {${displayName}} from '${options.importHint}';\`\n`);+ }+if (docs.usage?.anatomy?.length) {sections.push('## Anatomy\n');sections.push('| Element | Required | Description |');diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjsindex a87d641654..5b3a933559 100644--- a/packages/core/src/Table/Table.doc.mjs+++ b/packages/core/src/Table/Table.doc.mjs@@ -35,18 +35,18 @@ export const docs = {name: 'XDSTable',displayName: 'Table',description:- 'Styled, data-driven table with density, dividers, hover highlight, striped rows, and named plugin support.',+ 'Styled, data-driven table with density, dividers, hover highlight, striped rows, and named plugin support. T must extend Record<string, unknown>.',props: [{name: 'data',type: 'T[]',- description: 'Array of data items to render as rows.',+ description: 'Array of data items to render as rows. T must extend Record<string, unknown> (use `interface MyRow extends Record<string, unknown>` for custom types).',},{name: 'columns',type: 'XDSTableColumn<T>[]',description:- 'Column definitions. If omitted, columns are auto-generated from data object keys.',+ 'Column definitions — each column has {key, header, width?, align?, renderCell?}. The `header` field sets the column heading text. If omitted, columns are auto-generated from data object keys.',},{name: 'idKey',@@ -108,13 +108,13 @@ export const docs = {{name: 'data',type: 'T[]',- description: 'Array of data items to render as rows.',+ description: 'Array of data items to render as rows. T must extend Record<string, unknown>.',},{name: 'columns',type: 'XDSTableColumn<T>[]',description:- 'Column definitions. If omitted, columns are auto-generated from data object keys.',+ 'Column definitions — each column has {key, header, width?, renderCell?}. If omitted, columns are auto-generated from data object keys.',},{name: 'idKey',@@ -525,18 +525,18 @@ export const docsZh = {name: 'XDSTable',displayName: 'Table',description:- '带样式的数据驱动表格,支持密度、分隔线、悬停高亮、条纹行和命名插件。',+ '带样式的数据驱动表格,支持密度、分隔线、悬停高亮、条纹行和命名插件。T 需 extends Record<string, unknown>。',props: [{name: 'data',type: 'T[]',- description: '要渲染为行的数据项数组。',+ description: '要渲染为行的数据项数组。T 需 extends Record<string, unknown>。',},{name: 'columns',type: 'XDSTableColumn<T>[]',description:- '列定义。如果省略,将自动从数据对象键生成列。',+ '列定义 — 每列含 {key, header, width?, align?, renderCell?}。header 设置列标题文本。省略时自动从数据键生成。',},{name: 'idKey',@@ -599,13 +599,13 @@ export const docsZh = {{name: 'data',type: 'T[]',- description: '要渲染为行的数据项数组。',+ description: '要渲染为行的数据项数组。T 需 extends Record<string, unknown>。',},{name: 'columns',type: 'XDSTableColumn<T>[]',description:- '列定义。如果省略,将自动从数据对象键生成列。',+ '列定义 — 每列含 {key, header, width?, renderCell?}。省略时自动从数据键生成。',},{name: 'idKey',@@ -933,8 +933,8 @@ export const docsDense = {displayName: 'Table',description: 'Styled data-driven table w/ density, dividers, hover, striped rows, named plugin support.',propDescriptions: {- data: 'Array of data items to render as rows.',- columns: 'Column defs; auto-generated from data keys if omitted.',+ data: 'Array of data items to render as rows. T must extend Record<string, unknown>.',+ columns: 'Column defs {key, header, width?, align?, renderCell?}; auto-generated from data keys if omitted.',idKey: 'Row key for React reconciliation; property name or fn. Falls back to index.',density: 'Row density controlling cell padding + font size.',dividers: 'Divider style between cells.',@@ -951,8 +951,8 @@ export const docsDense = {displayName: 'Base Table',description: 'Unstyled structural table w/ plugin transform pipeline + components prop for custom row/cell renderers.',propDescriptions: {- data: 'Array of data items to render as rows.',- columns: 'Column defs; auto-generated from data keys if omitted.',+ data: 'Array of data items to render as rows. T must extend Record<string, unknown>.',+ columns: 'Column defs {key, header, width?, renderCell?}; auto-generated from data keys if omitted.',idKey: 'Row key for React reconciliation; property name or fn. Falls back to index.',plugins: 'Ordered plugin array applied as sequential transform pipeline.',components: 'Component overrides for row/cell elements; receive xstyle from plugin transforms.',