Skip to content

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

TypeScript

refactor(cli): split component into api/component leaf shape (#4489)

Joey6bb1277c7248
diff --git a/.changeset/cli-component-leaves.md b/.changeset/cli-component-leaves.md
new file mode 100644
index 0000000000..e6f6895e44
--- /dev/null
+++ b/.changeset/cli-component-leaves.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[refactor] CLI: `component` reorganized into the `api/component` leaf shape over a shared `_adapter` resolver — `component.mjs` is now a dispatcher + barrel that routes to per-type leaves (`list`, `detail`, `detail/props`, `detail/source`, `detail/showcase`, `detail/blocks`), each a thin projection of a subject the adapter resolves once (core/external/scoped/integration ownership, ambiguity handling, and fuzzy search, deduped). Pure reorg: every `--json` envelope and human output stays byte-identical across all modes.
+@josephfarina
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
new file mode 100644
index 0000000000..296dbca1e2
--- /dev/null
+++ b/packages/cli/api/component/_adapter.mjs
@@ -0,0 +1,408 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Shared resolver for the `component` command leaves.
+ *
+ * @input a component name (+ cwd / package scope) and doc-load options
+ * @output resolved subjects the leaves project into their one `{type, data}`
+ * envelope — owners across core/integration, the scoped/legacy/fuzzy
+ * resolution, and the doc-loading / prop-extraction / ownership shaping
+ * @position api/component (internal; NOT a response-type leaf, not exported
+ * from ./api). Every view of a component agrees because it resolves
+ * the subject HERE once; the leaves never re-resolve or do I/O of
+ * their own beyond fetching their single subject.
+ *
+ * This is a PURE REORG of the resolution that used to be inlined (and
+ * duplicated across branches) in component.mjs: the core/external/scoped/
+ * integration lookup, ambiguity handling, and fuzzy search now live here,
+ * deduped, so each leaf stays a thin projection.
+ */
+
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
+import {findCoreDir, discoverExternalPackages} from '../../utils/paths.mjs';
+import {
+ CORE_PACKAGE,
+ discoverComponents,
+ findComponentReadme,
+ findComponentSource,
+ findExternalComponentDoc,
+ findIntegrationComponentDoc,
+ findIntegrationComponentSource,
+ resolveImportPath,
+} from '../../lib/component-discovery.mjs';
+import {Project} from '../../lib/project.mjs';
+import {loadDocs} from '../../lib/component-loader.mjs';
+import {searchComponents} from '../../lib/string-utils.mjs';
+import {AstryxError} from '../error.mjs';
+
+export {CORE_PACKAGE};
+
+/**
+ * A loaded component doc. `loadDocs` returns the authored `.doc.mjs` shape,
+ * which is either a single-component or multi-component doc; this loose view
+ * captures the fields the API reads across both forms.
+ * @typedef {object} LoadedComponentDoc
+ * @property {string} [name]
+ * @property {string} [description]
+ * @property {any[]} [props]
+ * @property {any[]} [components]
+ * @property {{description?: string}} [usage]
+ * @property {any} [theming]
+ */
+
+/**
+ * Options object for `loadDocs`, matching its declared parameter shape (used
+ * as a cast target so `lang` (which the API may hold as `string|null`) type
+ * checks against `loadDocs`'s `lang?: string`).
+ * @typedef {{zh?: boolean, dense?: boolean, lang?: string}} LoadDocsOpts
+ */
+
+/**
+ * An OWNER package that provides a component with a given name: the doc/source
+ * paths and the issues URL a later integration-component swizzle needs.
+ * @typedef {object} ComponentOwner
+ * @property {string} package
+ * @property {string} docPath
+ * @property {string|null} sourcePath
+ * @property {string|undefined} issuesUrl
+ * @property {import('../../lib/integrations.mjs').LoadedIntegration|null} integration
+ */
+
+/**
+ * A back-compat external package discovered via `pkg.astryx.docs`.
+ * @typedef {{name: string, category: string, docsDir: string}} ExternalPackageRef
+ */
+
+/**
+ * The outcome of scoping a lookup to a specific `--package`.
+ * @typedef {(
+ * | {kind: 'core', owner: ComponentOwner}
+ * | {kind: 'integration', owner: ComponentOwner}
+ * | {kind: 'legacy', ext: ExternalPackageRef}
+ * )} ScopeResolution
+ */
+
+/**
+ * The result of resolving a bare (unscoped) name to a doc: which file, under
+ * which resolved name/owner, and where its swizzleable source lives.
+ * @typedef {object} ResolvedUnscopedDoc
+ * @property {string} readmePath
+ * @property {string} resolvedName
+ * @property {string} resolvedOwnerPackage
+ * @property {string|null} resolvedSourcePath
+ */
+
+/**
+ * Locate `@astryxdesign/core`, throwing the stable not-found error when absent.
+ * @param {string} cwd
+ * @returns {string}
+ */
+export function requireCoreDir(cwd) {
+ const coreDir = findCoreDir(cwd);
+ if (!coreDir) {
+ throw new AstryxError('Could not find @astryxdesign/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);
+ }
+ return coreDir;
+}
+
+/**
+ * Load the configured integrations for `cwd`, swallowing any config errors so
+ * component discovery never hard-fails on a malformed/absent integration. An
+ * empty list means "core only".
+ * @param {string} cwd
+ * @returns {Promise<import('../../lib/integrations.mjs').LoadedIntegration[]>}
+ */
+export async function loadIntegrationsSafely(cwd) {
+ try {
+ const project = await Project.load(cwd);
+ return /** @type {import('../../lib/integrations.mjs').LoadedIntegration[]} */ (
+ project.loadedIntegrations
+ );
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Resolve a loaded integration by package name.
+ * @param {import('../../lib/integrations.mjs').LoadedIntegration[]} loadedIntegrations
+ * @param {string} packageName
+ * @returns {import('../../lib/integrations.mjs').LoadedIntegration|null}
+ */
+function findLoadedIntegration(loadedIntegrations, packageName) {
+ return loadedIntegrations.find(i => i.name === packageName) ?? null;
+}
+
+/**
+ * Resolve an external package by name from the discovered externals list.
+ * @param {string} packageName - e.g. '@acme/xds-widgets'
+ * @param {string} cwd
+ * @returns {ExternalPackageRef | null}
+ */
+function resolveExternalPackage(packageName, cwd) {
+ const externals = discoverExternalPackages(cwd);
+ return externals.find(ext => ext.name === packageName) ?? null;
+}
+
+/**
+ * Build the set of OWNER packages that provide a component with this name
+ * across core + every loaded integration. This is what lets the CLI
+ * disambiguate by package and expose the owner's source + issuesUrl.
+ * @param {string} coreDir
+ * @param {string} dirName - bare component name (no `XDS` prefix)
+ * @param {import('../../lib/integrations.mjs').LoadedIntegration[]} loadedIntegrations
+ * @returns {ComponentOwner[]}
+ */
+export function resolveOwners(coreDir, dirName, loadedIntegrations) {
+ const coreDocPath = findComponentReadme(coreDir, dirName);
+ /** @type {ComponentOwner[]} */
+ const owners = [];
+ if (coreDocPath) {
+ owners.push({
+ package: CORE_PACKAGE,
+ docPath: coreDocPath,
+ sourcePath: findComponentSource(coreDir, dirName),
+ issuesUrl: undefined,
+ integration: null,
+ });
+ }
+ for (const integration of loadedIntegrations) {
+ const docPath = findIntegrationComponentDoc(integration, dirName);
+ if (!docPath) continue;
+ owners.push({
+ package: integration.name,
+ docPath,
+ sourcePath: findIntegrationComponentSource(integration, dirName),
+ issuesUrl: integration.issuesUrl,
+ integration,
+ });
+ }
+ return owners;
+}
+
+/**
+ * Classify a `--package`-scoped lookup. Searches the scoped package first so a
+ * component that exists in both core and an external package (e.g. AppShell,
+ * Button, SideNav) resolves to the package the caller asked for.
+ * @param {string} packageScope
+ * @param {{owners: ComponentOwner[], loadedIntegrations: import('../../lib/integrations.mjs').LoadedIntegration[], cwd: string, name: string}} ctx
+ * @returns {ScopeResolution}
+ */
+export function classifyScope(packageScope, {owners, loadedIntegrations, cwd, name}) {
+ // Core scope: resolve from core directly.
+ if (packageScope === CORE_PACKAGE) {
+ const owner = owners.find(o => o.package === CORE_PACKAGE);
+ if (!owner) {
+ throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
+ }
+ return {kind: 'core', owner};
+ }
+
+ // Integration scope (authoritative): resolve from the loaded integration.
+ const integration = findLoadedIntegration(loadedIntegrations, packageScope);
+ if (integration) {
+ const owner = owners.find(o => o.package === packageScope);
+ if (!owner) {
+ throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
+ }
+ return {kind: 'integration', owner};
+ }
+
+ // Legacy fallback: node_modules `pkg.astryx.docs` external package.
+ const ext = resolveExternalPackage(packageScope, cwd);
+ if (!ext) {
+ throw new AstryxError(`External package "${packageScope}" not found`, undefined, ERROR_CODES.ERR_UNKNOWN_PACKAGE);
+ }
+ return {kind: 'legacy', ext};
+}
+
+/**
+ * Refuse to guess when the name is owned by MORE THAN ONE package (core and/or
+ * integrations) and the caller did not scope with --package. Legacy
+ * `pkg.astryx.docs` externals are intentionally NOT part of this ambiguity set.
+ * @param {ComponentOwner[]} owners
+ * @param {string} dirName
+ * @returns {void}
+ */
+export function assertUnambiguousOwners(owners, dirName) {
+ if (owners.length > 1) {
+ throw new AstryxError(
+ `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,
+ owners.map(o => ({name: o.package, reason: 'provides this component'})),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+}
+
+/**
+ * Resolve a legacy external package's doc file for `dirName`, or null when the
+ * package ships no `.doc.mjs` for it.
+ * @param {ExternalPackageRef} ext
+ * @param {string} dirName
+ * @returns {string | null}
+ */
+export function resolveLegacyExternalDoc(ext, dirName) {
+ const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);
+ return extDocPath && extDocPath.endsWith('.doc.mjs') ? extDocPath : null;
+}
+
+/**
+ * The core source file for `dirName` (the no-scope `--source` path reads core
+ * directly — it does NOT fall back to externals or fuzzy search).
+ * @param {string} coreDir
+ * @param {string} dirName
+ * @returns {string | null}
+ */
+export function resolveCoreSourcePath(coreDir, dirName) {
+ return findComponentSource(coreDir, dirName);
+}
+
+/**
+ * Resolve a bare (unscoped) name to a `.doc.mjs`: core first, then back-compat
+ * externals, then a conservative fuzzy search. Throws ERR_UNKNOWN_COMPONENT
+ * (with candidate suggestions when close) or ERR_NO_DOC.
+ * @param {string} dirName - bare component name (no `XDS` prefix)
+ * @param {{coreDir: string, cwd: string, name: string}} ctx - `name` is the caller's original (prefixed) input, used in error text
+ * @returns {Promise<ResolvedUnscopedDoc>}
+ */
+export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {
+ let readmePath = findComponentReadme(coreDir, dirName);
+ let resolvedName = dirName;
+ // Track the resolving owner so the detail payload can carry ownership info.
+ // Defaults to core; the legacy-external fallback below may reassign it.
+ let resolvedOwnerPackage = CORE_PACKAGE;
+ let resolvedSourcePath = readmePath ? findComponentSource(coreDir, dirName) : null;
+
+ if (!readmePath) {
+ const externals = discoverExternalPackages(cwd);
+ for (const ext of externals) {
+ const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);
+ if (extDocPath) {
+ readmePath = extDocPath;
+ resolvedOwnerPackage = ext.name;
+ resolvedSourcePath = null;
+ 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);
+ resolvedOwnerPackage = CORE_PACKAGE;
+ resolvedSourcePath = findComponentSource(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 AstryxError(
+ `No component named "${name}"`,
+ candidates.map(c => ({name: c.name, reason: c.reason})),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+ } else {
+ throw new AstryxError(`No component named "${name}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
+ }
+ }
+
+ if (!readmePath || !readmePath.endsWith('.doc.mjs')) {
+ throw new AstryxError(`No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`, undefined, ERROR_CODES.ERR_NO_DOC);
+ }
+
+ return {readmePath, resolvedName, resolvedOwnerPackage, resolvedSourcePath};
+}
+
+/**
+ * Load a `.doc.mjs` through the shared loader, applying the API's doc-load
+ * options. Centralizes the `LoadedComponentDoc`/`LoadDocsOpts` casts so leaves
+ * get a typed doc without re-casting.
+ * @param {string} docPath
+ * @param {{zh?: boolean, dense?: boolean, lang?: string|null}} [opts]
+ * @returns {Promise<LoadedComponentDoc>}
+ */
+export async function loadComponentDoc(docPath, opts = {}) {
+ const {zh = false, dense = false, lang = null} = opts;
+ return /** @type {LoadedComponentDoc} */ (
+ await loadDocs(docPath, /** @type {LoadDocsOpts} */ ({zh, dense, lang}))
+ );
+}
+
+/**
+ * Project a loaded doc down to its props table, flattening a multi-component
+ * doc's members when the top-level doc has no direct props.
+ * @param {LoadedComponentDoc} docs
+ * @returns {any[]}
+ */
+export function extractProps(docs) {
+ return docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
+}
+
+/**
+ * Augment a loaded `component.detail` doc with ownership metadata. Adds
+ * `package`, the resolved `import` specifier, and `sourceAvailable` (whether a
+ * swizzleable source file exists for the owner). Existing doc fields (name,
+ * usage, props, …) are preserved.
+ * @param {LoadedComponentDoc} docs
+ * @param {{package: string, sourcePath: string|null}} owner
+ * @param {string} componentName
+ * @param {string} coreDir
+ * @returns {import('../../types/component').ComponentDetailResponse['data']}
+ */
+export function withOwnership(docs, owner, componentName, coreDir) {
+ const importSpec =
+ owner.package === CORE_PACKAGE
+ ? resolveImportPath(coreDir, componentName)
+ : `${owner.package}/${componentName}`;
+ return /** @type {any} */ ({
+ ...docs,
+ package: owner.package,
+ import: importSpec,
+ sourceAvailable: owner.sourcePath != null,
+ });
+}
+
+/**
+ * When the caller asked for "Code" but the resolved doc is for "CodeBlock"
+ * (parent), scope the response to just the matching sub-component. Returns the
+ * scoped doc (sans ownership) plus the matched member, or null when the doc is
+ * not a scopeable parent.
+ * @param {LoadedComponentDoc} docs
+ * @param {string} dirName
+ * @param {string} coreDir
+ * @returns {{scoped: LoadedComponentDoc & {parentDoc?: string, import?: string}, matchingComponent: any} | null}
+ */
+export function scopeSubComponent(docs, dirName, coreDir) {
+ const requestedXDS = `XDS${dirName}`;
+ const isParentDoc = docs.name && docs.name.toLowerCase() !== dirName.toLowerCase();
+ const matchingComponent = isParentDoc && docs.components
+ ? docs.components.find(c => c.name === requestedXDS || c.name === dirName)
+ : null;
+
+ if (!matchingComponent) return null;
+
+ /** @type {LoadedComponentDoc & {parentDoc?: string, import?: string}} */
+ const scoped = {
+ name: dirName,
+ description: matchingComponent.description,
+ props: matchingComponent.props,
+ // Keep parent context for reference
+ components: [matchingComponent],
+ parentDoc: docs.name,
+ import: resolveImportPath(coreDir, dirName),
+ };
+ if (docs.usage) scoped.usage = docs.usage;
+ if (docs.theming) scoped.theming = docs.theming;
+
+ return {scoped, matchingComponent};
+}
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index c6a9dd536c..8cb18fc5da 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -1,91 +1,47 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Programmatic API for the component command.
+ * @file Programmatic API for the component command — DISPATCHER + BARREL.
*
- * Returns the same typed envelope { type, data } that `astryx --json component` outputs.
- * The CLI command handler is a thin wrapper around this function.
+ * Returns the same typed envelope { type, data } that `astryx --json component`
+ * outputs. `component(name, opts)` parses the (name, options) pair, resolves the
+ * subject once via `_adapter`, and routes to the correct leaf
+ * (list · detail · detail.props/source/showcase/blocks), returning that leaf's
+ * envelope. The CLI command handler is a thin wrapper around this function.
+ *
+ * Every leaf is also re-exported for direct scripting use.
*/
-import * as fs from 'node:fs';
-import * as path from 'node:path';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
-import {findCoreDir, discoverExternalPackages} from '../../utils/paths.mjs';
+import {AstryxError} from '../error.mjs';
import {
CORE_PACKAGE,
- discoverComponents,
- discoverExternalComponentsGrouped,
- discoverIntegrationComponents,
- findComponentReadme,
- findComponentSource,
- findExternalComponentDoc,
- findIntegrationComponentDoc,
- findIntegrationComponentSource,
- resolveImportPath,
-} from '../../lib/component-discovery.mjs';
-import {Project} from '../../lib/project.mjs';
-import {loadDocs} from '../../lib/component-loader.mjs';
-import {searchComponents} from '../../lib/string-utils.mjs';
-import {AstryxError} from '../error.mjs';
-import {findShowcase, findRelatedBlocks} from '../template/template.mjs';
-
-/**
- * A loaded component doc. `loadDocs` returns the authored `.doc.mjs` shape,
- * which is either a single-component or multi-component doc; this loose view
- * captures the fields the API reads across both forms.
- * @typedef {object} LoadedComponentDoc
- * @property {string} [name]
- * @property {string} [description]
- * @property {any[]} [props]
- * @property {any[]} [components]
- * @property {{description?: string}} [usage]
- * @property {any} [theming]
- */
-
-/**
- * Options object for `loadDocs`, matching its declared parameter shape (used
- * as a cast target so `lang` (which the API may hold as `string|null`) type
- * checks against `loadDocs`'s `lang?: string`).
- * @typedef {{zh?: boolean, dense?: boolean, lang?: string}} LoadDocsOpts
- */
-
-/**
- * Load the configured integrations for `cwd`, swallowing any config errors so
- * component discovery never hard-fails on a malformed/absent integration. An
- * empty list means "core only".
- * @param {string} cwd
- * @returns {Promise<import('../../lib/integrations.mjs').LoadedIntegration[]>}
- */
-async function loadIntegrationsSafely(cwd) {
- try {
- const project = await Project.load(cwd);
- return /** @type {import('../../lib/integrations.mjs').LoadedIntegration[]} */ (
- project.loadedIntegrations
- );
- } catch {
- return [];
- }
-}
-
-/**
- * Resolve a loaded integration by package name.
- * @param {import('../../lib/integrations.mjs').LoadedIntegration[]} loadedIntegrations
- * @param {string} packageName
- */
-function findLoadedIntegration(loadedIntegrations, packageName) {
- return loadedIntegrations.find(i => i.name === packageName) ?? null;
-}
-
-/**
- * Resolve an external package by name from the discovered externals list.
- * @param {string} packageName - e.g. '@acme/xds-widgets'
- * @param {string} cwd
- * @returns {{ name: string, category: string, docsDir: string } | null}
- */
-function resolveExternalPackage(packageName, cwd) {
- const externals = discoverExternalPackages(cwd);
- return externals.find(ext => ext.name === packageName) ?? null;
-}
+ requireCoreDir,
+ loadIntegrationsSafely,
+ resolveOwners,
+ classifyScope,
+ assertUnambiguousOwners,
+ resolveLegacyExternalDoc,
+ resolveCoreSourcePath,
+ resolveUnscopedDoc,
+ loadComponentDoc,
+ scopeSubComponent,
+} from './_adapter.mjs';
+import {componentList} from './list/list.mjs';
+import {componentDetail} from './detail/detail.mjs';
+import {componentDetailProps} from './detail/props/props.mjs';
+import {componentDetailSource} from './detail/source/source.mjs';
+import {componentDetailShowcase} from './detail/showcase/showcase.mjs';
+import {componentDetailBlocks} from './detail/blocks/blocks.mjs';
+
+export {
+ componentList,
+ componentDetail,
+ componentDetailProps,
+ componentDetailSource,
+ componentDetailShowcase,
+ componentDetailBlocks,
+};
/**
* @param {string} [name]
@@ -102,7 +58,14 @@ function resolveExternalPackage(packageName, cwd) {
* @param {string} [options.lang]
* @param {boolean} [options.zh]
* @param {boolean} [options.dense]
- * @returns {Promise<{type: string, data: unknown}>}
+ * @returns {Promise<(
+ * import('../../types/component').ComponentListResponse
+ * | import('../../types/component').ComponentDetailResponse
+ * | import('../../types/component').ComponentDetailPropsResponse
+ * | import('../../types/component').ComponentDetailSourceResponse
+ * | import('../../types/component').ComponentDetailShowcaseResponse
+ * | import('../../types/component').ComponentDetailBlocksResponse
+ * )>}
*/
export async function component(name, options = {}) {
const {
@@ -127,183 +90,14 @@ export async function component(name, options = {}) {
const isListView = list || category != null || !name;
const detail = detailOption ?? (isListView ? 'brief' : 'full');
- const coreDir = findCoreDir(cwd);
- if (!coreDir) {
- throw new AstryxError('Could not find @astryxdesign/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);
- }
+ const coreDir = requireCoreDir(cwd);
// ── 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 AstryxError(
- `Unknown category "${category}"`,
- Object.keys(components).map(k => ({name: k, reason: 'valid category'})),
- ERROR_CODES.ERR_UNKNOWN_CATEGORY,
- );
- }
-
- if (detail === 'compact') {
- const entries = [];
- for (const comp of match[1]) {
- const readme = findComponentReadme(coreDir, comp);
- if (readme && readme.endsWith('.doc.mjs')) {
- try {
- const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang})));
- entries.push({name: comp, description: docs.usage?.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.list', data: {detail: 'compact', components: {[match[0]]: entries}}};
- }
-
- if (detail === 'full') {
- const entries = [];
- for (const comp of match[1]) {
- const readme = findComponentReadme(coreDir, comp);
- if (readme && readme.endsWith('.doc.mjs')) {
- try {
- entries.push(await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang, dense})));
- } catch {
- entries.push({name: `XDS${comp}`, description: ''});
- }
- } else {
- entries.push({name: `XDS${comp}`, description: ''});
- }
- }
- return {type: 'component.list', data: {detail: 'full', components: {[match[0]]: entries}}};
- }
-
- // Default: brief — package-qualified object list for the category.
- // Pre-1.0 JSON contract: members are {name, package} objects, not bare
- // strings, so consumers can disambiguate ownership.
- return {
- type: 'component.list',
- data: {detail: 'names', components: {[match[0]]: match[1].map(n => ({name: n, package: CORE_PACKAGE}))}},
- };
- }
-
- // All components — merge core + external packages with grouped subcategories
- if (detail === 'compact') {
- /** @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 = /** @type {LoadedComponentDoc} */ (await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang})));
- result[cat].push({name: comp, description: docs.usage?.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.list', data: {detail: 'compact', components: result}};
- }
-
- if (detail === 'full') {
- /** @type {Record<string, Array<unknown>>} */
- 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 {
- result[cat].push(await loadDocs(readme, /** @type {LoadDocsOpts} */ ({zh, lang, dense})));
- } catch {
- result[cat].push({name: `XDS${comp}`, description: ''});
- }
- } else {
- result[cat].push({name: `XDS${comp}`, description: ''});
- }
- }
- }
- return {type: 'component.list', data: {detail: 'full', components: result}};
- }
-
- // Default: brief — package-qualified object list (core + integrations).
- // Pre-1.0 JSON contract: each group's members are {name, package} objects.
- /** @type {Record<string, Array<{name: string, package: string}>>} */
- const listData = {};
- for (const [cat, comps] of Object.entries(components)) {
- listData[cat] = comps.map(n => ({name: n, package: CORE_PACKAGE}));
- }
-
- // Integration components (authoritative source: loadedIntegrations).
- const loadedIntegrations = await loadIntegrationsSafely(cwd);
- const seenIntegration = new Set();
- for (const integration of loadedIntegrations) {
- seenIntegration.add(integration.name);
- const owned = discoverIntegrationComponents(integration);
- // Group integration components by their doc `group`, falling back to the
- // package name. Keys are package-qualified so they never collide with
- // core groups or each other.
- /** @type {Map<string, Array<{name: string, package: string}>>} */
- const byGroup = new Map();
- for (const rec of owned) {
- const groupLabel = rec.group ?? integration.name;
- const key = `${groupLabel} (${integration.name})`;
- if (!byGroup.has(key)) byGroup.set(key, []);
- byGroup.get(key)?.push({name: rec.name, package: integration.name});
- }
- for (const [key, members] of byGroup) {
- members.sort((a, b) => a.name.localeCompare(b.name));
- listData[key] = members;
- }
- }
-
- // Back-compat: node_modules-scanned external packages (pkg.astryx.docs)
- // that are NOT configured integrations. Preserves existing discovery for
- // consumers that haven't adopted the config-integration flow.
- const externals = discoverExternalPackages(cwd);
- for (const ext of externals) {
- if (seenIntegration.has(ext.name)) continue;
- const grouped = discoverExternalComponentsGrouped(ext.docsDir);
- const groupKeys = Object.keys(grouped);
- if (groupKeys.length === 0) continue;
-
- const hasGroups = groupKeys.some(
- k => grouped[k].length > 1 || grouped[k][0] !== k,
- );
-
- if (hasGroups) {
- for (const [group, members] of Object.entries(grouped)) {
- listData[`${group} (${ext.name})`] = members.map(n => ({
- name: n,
- package: ext.name,
- }));
- }
- } else {
- const allComps = Object.values(grouped).flat().sort();
- if (allComps.length > 0) {
- listData[`${ext.category} (${ext.name})`] = allComps.map(n => ({
- name: n,
- package: ext.name,
- }));
- }
- }
- }
- return {type: 'component.list', data: {detail: 'names', components: listData}};
+ return componentList(coreDir, {cwd, category, detail, zh, dense, lang});
}
// ── Single component ───────────────────────────────────────────
-
if (typeof name !== 'string') {
throw new AstryxError(
`No component named "${String(name)}"`,
@@ -313,347 +107,100 @@ export async function component(name, options = {}) {
}
const dirName = name.replace(/^XDS/, '');
+ const docOpts = {zh, dense, lang};
- // Ownership-aware resolution. Build the set of OWNER packages that provide a
- // component with this name across core + every loaded integration. This is
- // what lets the CLI disambiguate by package and expose the owner's source +
- // issuesUrl (the inputs the future integration-component swizzle needs).
+ // Ownership-aware resolution: who provides `dirName` across core + every
+ // loaded integration. The scoped/ambiguity/fuzzy resolution below all read
+ // this set (built once, in the adapter).
const loadedIntegrations = await loadIntegrationsSafely(cwd);
- const coreDocPath = findComponentReadme(coreDir, dirName);
- /**
- * @type {Array<{
- * package: string,
- * docPath: string,
- * sourcePath: string|null,
- * issuesUrl: string|undefined,
- * integration: object|null,
- * }>}
- */
- const owners = [];
- if (coreDocPath) {
- owners.push({
- package: CORE_PACKAGE,
- docPath: coreDocPath,
- sourcePath: findComponentSource(coreDir, dirName),
- issuesUrl: undefined,
- integration: null,
- });
- }
- for (const integration of loadedIntegrations) {
- const docPath = findIntegrationComponentDoc(integration, dirName);
- if (!docPath) continue;
- owners.push({
- package: integration.name,
- docPath,
- sourcePath: findIntegrationComponentSource(integration, dirName),
- issuesUrl: integration.issuesUrl,
- integration,
- });
- }
+ const owners = resolveOwners(coreDir, dirName, loadedIntegrations);
- /**
- * Augment a loaded `component.detail` doc with ownership metadata. Adds
- * `package`, the resolved `import` specifier, and `sourceAvailable` (whether
- * a swizzleable source file exists for the owner). Existing doc fields
- * (name, usage, props, …) are preserved.
- * @param {LoadedComponentDoc} docs
- * @param {{package: string, sourcePath: string|null}} owner
- * @param {string} componentName
- */
- function withOwnership(docs, owner, componentName) {
- const importSpec =
- owner.package === CORE_PACKAGE
- ? resolveImportPath(/** @type {string} */ (coreDir), componentName)
- : `${owner.package}/${componentName}`;
- return {
- ...docs,
- package: owner.package,
- import: importSpec,
- sourceAvailable: owner.sourcePath != null,
- };
- }
-
- // When scoped to a specific package, search that package first.
- // This is critical for components that exist in both core and an external
- // package (e.g. AppShell, Button, SideNav) — the package scope ensures
- // the external package's docs are returned, not core's.
+ // ── Scoped to a specific package (--package) ───────────────────
+ // Searches that package first — critical for names that exist in both core
+ // and an external package (AppShell, Button, SideNav).
if (packageScope) {
- // Core scope: resolve from core directly.
- if (packageScope === CORE_PACKAGE) {
- const owner = owners.find(o => o.package === CORE_PACKAGE);
- if (!owner) {
- throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
- }
- if (source) {
- if (!owner.sourcePath) {
- throw new AstryxError(`Source for "${name}" not found`, undefined, ERROR_CODES.ERR_NO_SOURCE);
- }
- return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};
- }
- const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(owner.docPath, /** @type {LoadDocsOpts} */ ({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: withOwnership(docs, owner, dirName)};
- }
+ const scoped = classifyScope(packageScope, {owners, loadedIntegrations, cwd, name});
- // Integration scope (authoritative): resolve from the loaded integration.
- const integration = findLoadedIntegration(loadedIntegrations, packageScope);
- if (integration) {
- const owner = owners.find(o => o.package === packageScope);
- if (!owner) {
- throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
- }
+ if (scoped.kind === 'core' || scoped.kind === 'integration') {
+ const owner = scoped.owner;
if (source) {
- if (!owner.sourcePath) {
- throw new AstryxError(`Source for "${name}" not found in package "${packageScope}"`, undefined, ERROR_CODES.ERR_NO_SOURCE);
- }
- return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};
- }
- const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(owner.docPath, /** @type {LoadDocsOpts} */ ({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 componentDetailSource(dirName, owner.sourcePath, {
+ name,
+ notFoundInPackage: scoped.kind === 'integration' ? packageScope : null,
+ });
}
- return {type: 'component.detail', data: withOwnership(docs, owner, dirName)};
- }
-
- // Legacy fallback: node_modules `pkg.astryx.docs` external package.
- const ext = resolveExternalPackage(packageScope, cwd);
- if (!ext) {
- throw new AstryxError(`External package "${packageScope}" not found`, undefined, ERROR_CODES.ERR_UNKNOWN_PACKAGE);
+ const docs = await loadComponentDoc(owner.docPath, docOpts);
+ if (props) return componentDetailProps(docs);
+ return componentDetail(docs, owner, dirName, coreDir);
}
+ // Legacy `pkg.astryx.docs` external package.
if (showcase) {
- const match = await findShowcase(dirName, cwd, {package: packageScope});
- if (!match) {
- throw new AstryxError(`No showcase found for "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);
- }
- return {
- type: 'component.detail.showcase',
- data: {
- component: dirName,
- aspectRatio: match.aspectRatio,
- source: fs.readFileSync(match.filePath, 'utf-8'),
- },
- };
+ return componentDetailShowcase(dirName, {cwd, name, packageScope});
}
-
- const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);
- if (extDocPath && extDocPath.endsWith('.doc.mjs')) {
- const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(extDocPath, /** @type {LoadDocsOpts} */ ({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: withOwnership(docs, {package: ext.name, sourcePath: null}, dirName),
- };
+ const extDocPath = resolveLegacyExternalDoc(scoped.ext, dirName);
+ if (extDocPath) {
+ const docs = await loadComponentDoc(extDocPath, docOpts);
+ if (props) return componentDetailProps(docs);
+ return componentDetail(docs, {package: scoped.ext.name, sourcePath: null}, dirName, coreDir);
}
throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
}
- // Ambiguity: when the name is owned by MORE THAN ONE package (core and/or
- // integrations) and the caller did not scope with --package, refuse to guess.
- // NOTE: legacy `pkg.astryx.docs` externals are intentionally NOT part of this
- // ambiguity set — they retain their historical core-first fallback below so
- // existing consumers (and tests) keep working. Only config-driven integration
- // ownership participates here.
- if (owners.length > 1) {
- throw new AstryxError(
- `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,
- owners.map(o => ({name: o.package, reason: 'provides this component'})),
- ERROR_CODES.ERR_UNKNOWN_COMPONENT,
- );
- }
+ // ── Ambiguity: owned by MORE THAN ONE package, no --package ─────
+ assertUnambiguousOwners(owners, dirName);
- // Single non-core owner (an integration provides it, core does not) — resolve
- // from that integration so the integration component is authoritative.
+ // ── Single non-core owner (an integration provides it, core does not) ──
if (owners.length === 1 && owners[0].package !== CORE_PACKAGE) {
const owner = owners[0];
if (source) {
- if (!owner.sourcePath) {
- throw new AstryxError(`Source for "${name}" not found`, undefined, ERROR_CODES.ERR_NO_SOURCE);
- }
- return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};
+ return componentDetailSource(dirName, owner.sourcePath, {name});
}
if (showcase) {
- throw new AstryxError(`No showcase found for "${name}"`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);
- }
- const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(owner.docPath, /** @type {LoadDocsOpts} */ ({zh, dense, lang})));
- if (props) {
- const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
- return {type: 'component.detail.props', data: p};
+ // Integration components don't carry showcases — fail without scanning.
+ return componentDetailShowcase(dirName, {cwd, name, resolve: false});
}
- return {type: 'component.detail', data: withOwnership(docs, owner, dirName)};
+ const docs = await loadComponentDoc(owner.docPath, docOpts);
+ if (props) return componentDetailProps(docs);
+ return componentDetail(docs, owner, dirName, coreDir);
}
+ // ── No-scope core path ─────────────────────────────────────────
+ // `--source` reads core directly (no external/fuzzy fallback).
if (source) {
- const sourcePath = findComponentSource(coreDir, dirName);
- if (!sourcePath) {
- throw new AstryxError(`Source for "${name}" not found`, undefined, ERROR_CODES.ERR_NO_SOURCE);
- }
- return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(sourcePath, 'utf-8')}};
+ return componentDetailSource(dirName, resolveCoreSourcePath(coreDir, dirName), {name});
}
-
if (showcase) {
- const match = await findShowcase(dirName, cwd);
- if (!match) {
- throw new AstryxError(`No showcase found for "${name}"`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);
- }
- return {
- type: 'component.detail.showcase',
- data: {
- component: dirName,
- aspectRatio: match.aspectRatio,
- source: fs.readFileSync(match.filePath, 'utf-8'),
- },
- };
- }
-
- let readmePath = findComponentReadme(coreDir, dirName);
- let resolvedName = dirName;
- // Track the resolving owner so the detail payload can carry ownership info.
- // Defaults to core; the legacy-external fallback below may reassign it.
- let resolvedOwnerPackage = CORE_PACKAGE;
- let resolvedSourcePath = readmePath ? findComponentSource(coreDir, dirName) : null;
-
- if (!readmePath) {
- const externals = discoverExternalPackages(cwd);
- for (const ext of externals) {
- const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);
- if (extDocPath) {
- readmePath = extDocPath;
- resolvedOwnerPackage = ext.name;
- resolvedSourcePath = null;
- break;
- }
- }
+ return componentDetailShowcase(dirName, {cwd, name});
}
- 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);
- resolvedOwnerPackage = CORE_PACKAGE;
- resolvedSourcePath = findComponentSource(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 AstryxError(
- `No component named "${name}"`,
- candidates.map(c => ({name: c.name, reason: c.reason})),
- ERROR_CODES.ERR_UNKNOWN_COMPONENT,
- );
- }
- } else {
- throw new AstryxError(`No component named "${name}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
- }
- }
-
- if (!readmePath || !readmePath.endsWith('.doc.mjs')) {
- throw new AstryxError(`No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`, undefined, ERROR_CODES.ERR_NO_DOC);
- }
-
- const docs = /** @type {LoadedComponentDoc} */ (await loadDocs(readmePath, /** @type {LoadDocsOpts} */ ({zh, dense, lang})));
+ const resolved = await resolveUnscopedDoc(dirName, {coreDir, cwd, name});
+ const docs = await loadComponentDoc(resolved.readmePath, docOpts);
// ── Blocks mode ──────────────────────────────────────────────
if (blocks) {
- const allBlocks = await findRelatedBlocks(dirName);
- const toEntry = (/** @type {any} */ b) => ({
- name: b.dirName,
- displayName: b.name,
- description: b.description,
- isShowcase: b.isShowcase ?? false,
- category: b.category,
- });
-
- // Examples: blocks in the component's own directory, or
- // componentsUsed match for sub-components without a directory.
- const ownDir = allBlocks.filter((/** @type {any} */ b) => path.basename(b.category) === dirName);
- const examples = ownDir.length > 0
- ? ownDir
- : allBlocks.filter(b => b.componentsUsed?.some(c => c === dirName));
- const exampleSet = new Set(examples.map(b => b.dirName));
-
- // Showcase: the single hero example from the examples list.
- const showcaseBlock = examples.find(b => b.isShowcase) || null;
-
- // Related: everything else that uses this component but isn't
- // primarily about it (e.g. a Dialog block that has a Button).
- const related = allBlocks.filter(b => !exampleSet.has(b.dirName));
-
- return {
- type: 'component.detail.blocks',
- data: {
- component: dirName,
- showcase: showcaseBlock ? toEntry(showcaseBlock) : null,
- examples: examples.filter(b => b !== showcaseBlock).map(toEntry),
- related: related.map(toEntry),
- },
- };
+ return componentDetailBlocks(dirName);
}
// ── Sub-component scoping ────────────────────────────────────
// If the user asked for "Code" but the doc is for "CodeBlock" (parent),
// scope the response to just the matching sub-component.
- const requestedXDS = `XDS${dirName}`;
- const isParentDoc = docs.name && docs.name.toLowerCase() !== dirName.toLowerCase();
- const matchingComponent = isParentDoc && docs.components
- ? docs.components.find(c => c.name === requestedXDS || c.name === dirName)
- : null;
-
- if (matchingComponent) {
- /** @type {LoadedComponentDoc & {parentDoc?: string, import?: string}} */
- const scoped = {
- name: dirName,
- description: matchingComponent.description,
- props: matchingComponent.props,
- // Keep parent context for reference
- components: [matchingComponent],
- parentDoc: docs.name,
- import: resolveImportPath(coreDir, dirName),
- };
- if (docs.usage) scoped.usage = docs.usage;
- if (docs.theming) scoped.theming = docs.theming;
-
- if (props) {
- return {type: 'component.detail.props', data: matchingComponent.props || []};
- }
- return {
- type: 'component.detail',
- data: withOwnership(
- scoped,
- {package: resolvedOwnerPackage, sourcePath: resolvedSourcePath},
- dirName,
- ),
- };
- }
-
- if (props) {
- const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
- return {type: 'component.detail.props', data: p};
+ const sub = scopeSubComponent(docs, dirName, coreDir);
+ if (sub) {
+ if (props) return componentDetailProps({props: sub.matchingComponent.props});
+ return componentDetail(
+ sub.scoped,
+ {package: resolved.resolvedOwnerPackage, sourcePath: resolved.resolvedSourcePath},
+ dirName,
+ coreDir,
+ );
}
- return {
- type: 'component.detail',
- data: withOwnership(
- docs,
- {package: resolvedOwnerPackage, sourcePath: resolvedSourcePath},
- resolvedName,
- ),
- };
+ if (props) return componentDetailProps(docs);
+ return componentDetail(
+ docs,
+ {package: resolved.resolvedOwnerPackage, sourcePath: resolved.resolvedSourcePath},
+ resolved.resolvedName,
+ coreDir,
+ );
}
diff --git a/packages/cli/api/component/detail/blocks/blocks.mjs b/packages/cli/api/component/detail/blocks/blocks.mjs
new file mode 100644
index 0000000000..3be14b04c2
--- /dev/null
+++ b/packages/cli/api/component/detail/blocks/blocks.mjs
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `component.detail.blocks` leaf — a component's example/related blocks.
+ *
+ * @input a component name
+ * @output the `component.detail.blocks` envelope (showcase, examples, related)
+ * @position api/component/detail/blocks (projection leaf; routed by component.mjs)
+ */
+
+import * as path from 'node:path';
+import {findRelatedBlocks} from '../../../template/template.mjs';
+
+/**
+ * Project a component's related blocks into the `component.detail.blocks`
+ * envelope, splitting them into the hero showcase, component-specific examples,
+ * and broader related blocks.
+ * @param {string} componentName
+ * @returns {Promise<import('../../../../types/component').ComponentDetailBlocksResponse>}
+ */
+export async function componentDetailBlocks(componentName) {
+ const allBlocks = await findRelatedBlocks(componentName);
+ const toEntry = (/** @type {any} */ b) => ({
+ name: b.dirName,
+ displayName: b.name,
+ description: b.description,
+ isShowcase: b.isShowcase ?? false,
+ category: b.category,
+ });
+
+ // Examples: blocks in the component's own directory, or
+ // componentsUsed match for sub-components without a directory.
+ const ownDir = allBlocks.filter((/** @type {any} */ b) => path.basename(b.category) === componentName);
+ const examples = ownDir.length > 0
+ ? ownDir
+ : allBlocks.filter(b => b.componentsUsed?.some(c => c === componentName));
+ const exampleSet = new Set(examples.map(b => b.dirName));
+
+ // Showcase: the single hero example from the examples list.
+ const showcaseBlock = examples.find(b => b.isShowcase) || null;
+
+ // Related: everything else that uses this component but isn't
+ // primarily about it (e.g. a Dialog block that has a Button).
+ const related = allBlocks.filter(b => !exampleSet.has(b.dirName));
+
+ return {
+ type: 'component.detail.blocks',
+ data: {
+ component: componentName,
+ showcase: showcaseBlock ? toEntry(showcaseBlock) : null,
+ examples: examples.filter(b => b !== showcaseBlock).map(toEntry),
+ related: related.map(toEntry),
+ },
+ };
+}
diff --git a/packages/cli/api/component/detail/detail.mjs b/packages/cli/api/component/detail/detail.mjs
new file mode 100644
index 0000000000..a2dd34025f
--- /dev/null
+++ b/packages/cli/api/component/detail/detail.mjs
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `component.detail` leaf — a single component's full doc + ownership.
+ *
+ * @input a resolved (already-loaded) doc + its owner, from _adapter
+ * @output the `component.detail` envelope
+ * @position api/component/detail (projection leaf; routed by component.mjs)
+ */
+
+import {withOwnership} from '../_adapter.mjs';
+
+/**
+ * Project a resolved doc + owner into the `component.detail` envelope.
+ * @param {import('../_adapter.mjs').LoadedComponentDoc} docs
+ * @param {{package: string, sourcePath: string|null}} owner
+ * @param {string} componentName - name used for the import specifier
+ * @param {string} coreDir
+ * @returns {import('../../../types/component').ComponentDetailResponse}
+ */
+export function componentDetail(docs, owner, componentName, coreDir) {
+ return {type: 'component.detail', data: withOwnership(docs, owner, componentName, coreDir)};
+}
diff --git a/packages/cli/api/component/detail/props/props.mjs b/packages/cli/api/component/detail/props/props.mjs
new file mode 100644
index 0000000000..eae92f8c0c
--- /dev/null
+++ b/packages/cli/api/component/detail/props/props.mjs
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `component.detail.props` leaf — just a component's props table.
+ *
+ * @input a resolved (already-loaded) doc-like object, from _adapter
+ * @output the `component.detail.props` envelope
+ * @position api/component/detail/props (projection leaf; routed by component.mjs)
+ */
+
+import {extractProps} from '../../_adapter.mjs';
+
+/**
+ * Project a resolved doc into the `component.detail.props` envelope.
+ * @param {import('../../_adapter.mjs').LoadedComponentDoc} docs
+ * @returns {import('../../../../types/component').ComponentDetailPropsResponse}
+ */
+export function componentDetailProps(docs) {
+ return {type: 'component.detail.props', data: extractProps(docs)};
+}
diff --git a/packages/cli/api/component/detail/showcase/showcase.mjs b/packages/cli/api/component/detail/showcase/showcase.mjs
new file mode 100644
index 0000000000..a2ecff7069
--- /dev/null
+++ b/packages/cli/api/component/detail/showcase/showcase.mjs
@@ -0,0 +1,45 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `component.detail.showcase` leaf — a component's hero showcase source.
+ *
+ * @input a component name (+ cwd / package scope) or an explicit "no match"
+ * @output the `component.detail.showcase` envelope
+ * @position api/component/detail/showcase (projection leaf; routed by component.mjs)
+ */
+
+import * as fs from 'node:fs';
+import {AstryxError} from '../../../error.mjs';
+import {ERROR_CODES} from '../../../../lib/error-codes.mjs';
+import {findShowcase} from '../../../template/template.mjs';
+
+/**
+ * Resolve and read a component's showcase block into the
+ * `component.detail.showcase` envelope. Throws ERR_NO_SHOWCASE when none
+ * matches. Pass `resolve: false` for owners that never carry a showcase
+ * (integration components) so we throw without scanning blocks.
+ * @param {string} componentName - bare name, echoed back as `data.component`
+ * @param {object} ctx
+ * @param {string} ctx.cwd
+ * @param {string} ctx.name - the caller's original input, used in the error message
+ * @param {string|null} [ctx.packageScope] - scope block discovery + the error to a package
+ * @param {boolean} [ctx.resolve] - when false, skip discovery and treat as not found
+ * @returns {Promise<import('../../../../types/component').ComponentDetailShowcaseResponse>}
+ */
+export async function componentDetailShowcase(componentName, {cwd, name, packageScope = null, resolve = true}) {
+ const match = resolve
+ ? await findShowcase(componentName, cwd, packageScope ? {package: packageScope} : undefined)
+ : null;
+ if (!match) {
+ const suffix = packageScope ? ` in package "${packageScope}"` : '';
+ throw new AstryxError(`No showcase found for "${name}"${suffix}`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);
+ }
+ return {
+ type: 'component.detail.showcase',
+ data: {
+ component: componentName,
+ aspectRatio: /** @type {number} */ (match.aspectRatio),
+ source: fs.readFileSync(match.filePath, 'utf-8'),
+ },
+ };
+}
diff --git a/packages/cli/api/component/detail/source/source.mjs b/packages/cli/api/component/detail/source/source.mjs
new file mode 100644
index 0000000000..d73348fd01
--- /dev/null
+++ b/packages/cli/api/component/detail/source/source.mjs
@@ -0,0 +1,29 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `component.detail.source` leaf — a component's source code.
+ *
+ * @input a resolved source path (from _adapter / the owner) + error context
+ * @output the `component.detail.source` envelope
+ * @position api/component/detail/source (projection leaf; routed by component.mjs)
+ */
+
+import * as fs from 'node:fs';
+import {AstryxError} from '../../../error.mjs';
+import {ERROR_CODES} from '../../../../lib/error-codes.mjs';
+
+/**
+ * Read a resolved component source path into the `component.detail.source`
+ * envelope. Throws ERR_NO_SOURCE when the owner ships no source file.
+ * @param {string} componentName - bare name, echoed back as `data.component`
+ * @param {string|null} sourcePath - the resolved source path (null → not found)
+ * @param {{name: string, notFoundInPackage?: string|null}} ctx - `name` is the caller's original input; `notFoundInPackage` scopes the not-found message to a package
+ * @returns {import('../../../../types/component').ComponentDetailSourceResponse}
+ */
+export function componentDetailSource(componentName, sourcePath, {name, notFoundInPackage = null}) {
+ if (!sourcePath) {
+ const suffix = notFoundInPackage ? ` in package "${notFoundInPackage}"` : '';
+ throw new AstryxError(`Source for "${name}" not found${suffix}`, undefined, ERROR_CODES.ERR_NO_SOURCE);
+ }
+ return {type: 'component.detail.source', data: {component: componentName, source: fs.readFileSync(sourcePath, 'utf-8')}};
+}
diff --git a/packages/cli/api/component/list/list.mjs b/packages/cli/api/component/list/list.mjs
new file mode 100644
index 0000000000..bb87f41cfc
--- /dev/null
+++ b/packages/cli/api/component/list/list.mjs
@@ -0,0 +1,215 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `component.list` leaf — the grouped component listing.
+ *
+ * @input coreDir + list options (category filter, detail level, doc language)
+ * @output ONE `component.list` envelope whose `data.detail`
+ * ('names' | 'compact' | 'full') tags the payload depth and
+ * `data.components` holds the grouped map (core + integrations +
+ * back-compat externals).
+ * @position api/component/list (projection leaf; routed by component.mjs)
+ */
+
+import {
+ CORE_PACKAGE,
+ discoverComponents,
+ discoverExternalComponentsGrouped,
+ discoverIntegrationComponents,
+ findComponentReadme,
+ resolveImportPath,
+} from '../../../lib/component-discovery.mjs';
+import {discoverExternalPackages} from '../../../utils/paths.mjs';
+import {ERROR_CODES} from '../../../lib/error-codes.mjs';
+import {AstryxError} from '../../error.mjs';
+import {loadComponentDoc, loadIntegrationsSafely} from '../_adapter.mjs';
+
+/**
+ * @typedef {import('../../../types/component').ComponentListResponse} ComponentListResponse
+ * @typedef {import('../../../types/component').ComponentListEntry} ComponentListEntry
+ * @typedef {import('../../../types/component').ComponentBriefEntry} ComponentBriefEntry
+ */
+
+/**
+ * Build the `component.list` envelope. The list taxonomy is collapsed: all
+ * three detail levels emit ONE `component.list` type; the depth rides in
+ * `data.detail` and the grouped map in `data.components`.
+ * @param {string} coreDir
+ * @param {object} opts
+ * @param {string} opts.cwd
+ * @param {string} [opts.category] - Filter to a single category (group key).
+ * @param {'full'|'compact'|'brief'} opts.detail
+ * @param {boolean} opts.zh
+ * @param {boolean} opts.dense
+ * @param {string|null} opts.lang
+ * @returns {Promise<ComponentListResponse>}
+ */
+export async function componentList(coreDir, {cwd, category, detail, zh, dense, lang}) {
+ const components = discoverComponents(coreDir);
+
+ if (category) {
+ const match = Object.entries(components).find(
+ ([key]) => key.toLowerCase() === category.toLowerCase(),
+ );
+ if (!match) {
+ throw new AstryxError(
+ `Unknown category "${category}"`,
+ Object.keys(components).map(k => ({name: k, reason: 'valid category'})),
+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,
+ );
+ }
+
+ if (detail === 'compact') {
+ /** @type {ComponentBriefEntry[]} */
+ const entries = [];
+ for (const comp of match[1]) {
+ const readme = findComponentReadme(coreDir, comp);
+ if (readme && readme.endsWith('.doc.mjs')) {
+ try {
+ const docs = await loadComponentDoc(readme, {zh, lang});
+ entries.push({name: comp, description: docs.usage?.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.list', data: {detail: 'compact', components: {[match[0]]: entries}}};
+ }
+
+ if (detail === 'full') {
+ /** @type {any[]} */
+ const entries = [];
+ for (const comp of match[1]) {
+ const readme = findComponentReadme(coreDir, comp);
+ if (readme && readme.endsWith('.doc.mjs')) {
+ try {
+ entries.push(await loadComponentDoc(readme, {zh, lang, dense}));
+ } catch {
+ entries.push({name: `XDS${comp}`, description: ''});
+ }
+ } else {
+ entries.push({name: `XDS${comp}`, description: ''});
+ }
+ }
+ return {type: 'component.list', data: {detail: 'full', components: {[match[0]]: entries}}};
+ }
+
+ // Default: brief — package-qualified object list for the category.
+ // Pre-1.0 JSON contract: members are {name, package} objects, not bare
+ // strings, so consumers can disambiguate ownership.
+ return {
+ type: 'component.list',
+ data: {detail: 'names', components: {[match[0]]: match[1].map(n => ({name: n, package: CORE_PACKAGE}))}},
+ };
+ }
+
+ // All components — merge core + external packages with grouped subcategories
+ if (detail === 'compact') {
+ /** @type {Record<string, 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 loadComponentDoc(readme, {zh, lang});
+ result[cat].push({name: comp, description: docs.usage?.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.list', data: {detail: 'compact', components: result}};
+ }
+
+ if (detail === 'full') {
+ /** @type {Record<string, any[]>} */
+ 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 {
+ result[cat].push(await loadComponentDoc(readme, {zh, lang, dense}));
+ } catch {
+ result[cat].push({name: `XDS${comp}`, description: ''});
+ }
+ } else {
+ result[cat].push({name: `XDS${comp}`, description: ''});
+ }
+ }
+ }
+ return {type: 'component.list', data: {detail: 'full', components: result}};
+ }
+
+ // Default: brief — package-qualified object list (core + integrations).
+ // Pre-1.0 JSON contract: each group's members are {name, package} objects.
+ /** @type {Record<string, Array<{name: string, package: string}>>} */
+ const listData = {};
+ for (const [cat, comps] of Object.entries(components)) {
+ listData[cat] = comps.map(n => ({name: n, package: CORE_PACKAGE}));
+ }
+
+ // Integration components (authoritative source: loadedIntegrations).
+ const loadedIntegrations = await loadIntegrationsSafely(cwd);
+ const seenIntegration = new Set();
+ for (const integration of loadedIntegrations) {
+ seenIntegration.add(integration.name);
+ const owned = discoverIntegrationComponents(integration);
+ // Group integration components by their doc `group`, falling back to the
+ // package name. Keys are package-qualified so they never collide with
+ // core groups or each other.
+ /** @type {Map<string, Array<{name: string, package: string}>>} */
+ const byGroup = new Map();
+ for (const rec of owned) {
+ const groupLabel = rec.group ?? integration.name;
+ const key = `${groupLabel} (${integration.name})`;
+ if (!byGroup.has(key)) byGroup.set(key, []);
+ byGroup.get(key)?.push({name: rec.name, package: integration.name});
+ }
+ for (const [key, members] of byGroup) {
+ members.sort((a, b) => a.name.localeCompare(b.name));
+ listData[key] = members;
+ }
+ }
+
+ // Back-compat: node_modules-scanned external packages (pkg.astryx.docs)
+ // that are NOT configured integrations. Preserves existing discovery for
+ // consumers that haven't adopted the config-integration flow.
+ const externals = discoverExternalPackages(cwd);
+ for (const ext of externals) {
+ if (seenIntegration.has(ext.name)) continue;
+ const grouped = discoverExternalComponentsGrouped(ext.docsDir);
+ const groupKeys = Object.keys(grouped);
+ if (groupKeys.length === 0) continue;
+
+ const hasGroups = groupKeys.some(
+ k => grouped[k].length > 1 || grouped[k][0] !== k,
+ );
+
+ if (hasGroups) {
+ for (const [group, members] of Object.entries(grouped)) {
+ listData[`${group} (${ext.name})`] = members.map(n => ({
+ name: n,
+ package: ext.name,
+ }));
+ }
+ } else {
+ const allComps = Object.values(grouped).flat().sort();
+ if (allComps.length > 0) {
+ listData[`${ext.category} (${ext.name})`] = allComps.map(n => ({
+ name: n,
+ package: ext.name,
+ }));
+ }
+ }
+ }
+ return {type: 'component.list', data: {detail: 'names', components: listData}};
+}