Skip to content

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

TypeScript

Support batched component lookups (#6867)

Joey505e3d895f4a
diff --git a/.changeset/cli-component-batch-lookups.md b/.changeset/cli-component-batch-lookups.md
new file mode 100644
index 0000000000..2cf3a1147e
--- /dev/null
+++ b/.changeset/cli-component-batch-lookups.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx component` accepts several exact selectors in one call. The JSON response keeps one ordered row per selector, including missing and ambiguous components, and text mode prints every row before exiting nonzero when any lookup fails. The `component()` API accepts selector arrays and always returns `component.batch` for an array, including empty and one-item arrays. Batches accept up to 100 selectors and reject larger arrays before lookup. The public API also exports shared `BatchResponse` and `BatchRow` types for typed receipts.
+
+@josephfarina
diff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjs
index 48262f00d6..4949281f2d 100644
--- a/.github/scripts/cli-api-types-verify.mjs
+++ b/.github/scripts/cli-api-types-verify.mjs
@@ -113,7 +113,9 @@ import {
} from '@astryxdesign/cli/api';
import type {
ComponentOptions, SearchOptions, UpgradeOptions, GapReportOptions,
- ComponentDetailResponse, SearchResponse, UpgradeRunResponse,
+ BatchResponse, BatchRow, ComponentBatchCandidate, ComponentBatchResponse,
+ ComponentBatchResult, ComponentSingleResponse, ComponentDetailResponse,
+ SearchResponse, UpgradeRunResponse,
GapReportReceiptResponse, GapReportCategoriesResponse, Logger,
IntegrationAddComponentOptions, IntegrationAddDocOptions,
IntegrationAddTemplateOptions, IntegrationAddCodemodOptions,
@@ -125,6 +127,14 @@ import type {
async function main() {
const r = await component('Button');
if (r.type === 'component.detail') { const n: string = r.data.name; void n; }
+ const batch = await component(['Button']) as ComponentBatchResponse;
+ const sharedBatch: BatchResponse<
+ 'component.batch', ComponentSingleResponse, ComponentBatchCandidate
+ > = batch;
+ const sharedRow: BatchRow<ComponentSingleResponse, ComponentBatchCandidate> | undefined =
+ sharedBatch.data.results[0];
+ const componentRow: ComponentBatchResult | undefined = batch.data.results[0];
+ void [sharedBatch, sharedRow, componentRow];
const s: SearchOptions = { limit: 5, type: 'component' };
const l: Logger = logger; l.setSilent(false); l.log('x');
void ({} as ComponentOptions); void ({} as UpgradeOptions); void ({} as GapReportOptions);
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 9c8ae402d3..3045235408 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -418,65 +418,66 @@ Every response has a `type` discriminant. The full set is below (generated from
<!-- BEGIN GENERATED: response-types -->
-| Type | What `data` carries |
-| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
-| `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |
-| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries, or a full ComponentDoc per entry. |
-| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). |
-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |
-| `component.detail.source` | One component's source file, as {component, source}. |
-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |
-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |
-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
-| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, summary} (pass the id as the section argument; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). |
-| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
-| `discover.list` | The integrations the project loads (name, category, components, version, a list per other kind they add, and latest when a source knows it); with a discover source, meta.available lists what the project could add and meta.sources reports each source; when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |
-| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
-| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
-| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
-| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title, parent (the command that opens the level above), package (for a docs-tree hit), and, for a hit on one section, section (docs), or displayName and kind (templates). |
-| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
-| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, command, basis, reason, alternatives, ...}, pages (search's closest templates), blocks and domain as SearchResultEntry[], frame, foundation, and hint {reason, commands} when thin. |
-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |
-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |
-| `gap-report.categories` | The fixed gap category values and human-readable labels. |
-| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals. |
-| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
-| `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |
-| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |
-| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |
-| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |
-| `hook.detail` | One hook's full authored HookDoc. |
-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |
-| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
-| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
-| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
-| `theme.list` | Every bundled or installed integration theme as a ThemeListEntry[]: each with slug, displayName, description, maintained flag, and owner package. |
-| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, owner package, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |
-| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states, deprecatedFor?}, where props and states are its legal override keys and deprecatedFor names the canonical replacement key. |
-| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
-| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
-| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |
-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |
-| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
-| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message}]. |
-| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
-| `integration.template-conflicts` | The integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
-| `integration.component-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
-| `integration.doc-conflicts` | The integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
-| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |
-| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |
-| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |
+| Type | What `data` carries |
+| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
+| `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |
+| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries, or a full ComponentDoc per entry. |
+| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
+| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). |
+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |
+| `component.detail.source` | One component's source file, as {component, source}. |
+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |
+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |
+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
+| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, summary} (pass the id as the section argument; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). |
+| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
+| `discover.list` | The integrations the project loads (name, category, components, version, a list per other kind they add, and latest when a source knows it); with a discover source, meta.available lists what the project could add and meta.sources reports each source; when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |
+| `discover.detail` | One package, for an @scope/name or @scope/name@version query: what the shown version adds, whether the project has it, and, when a source knows the package, its versions, latest release, and the command that adds it. |
+| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
+| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
+| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title, parent (the command that opens the level above), package (for a docs-tree hit), and, for a hit on one section, section (docs), or displayName and kind (templates). |
+| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
+| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, command, basis, reason, alternatives, ...}, pages (search's closest templates), blocks and domain as SearchResultEntry[], frame, foundation, and hint {reason, commands} when thin. |
+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |
+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |
+| `gap-report.categories` | The fixed gap category values and human-readable labels. |
+| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals. |
+| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
+| `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |
+| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |
+| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |
+| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |
+| `hook.detail` | One hook's full authored HookDoc. |
+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |
+| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
+| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
+| `theme.list` | Every bundled or installed integration theme as a ThemeListEntry[]: each with slug, displayName, description, maintained flag, and owner package. |
+| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, owner package, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |
+| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
+| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states, deprecatedFor?}, where props and states are its legal override keys and deprecatedFor names the canonical replacement key. |
+| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
+| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
+| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |
+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |
+| `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
+| `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message}]. |
+| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
+| `integration.template-conflicts` | The integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
+| `integration.component-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
+| `integration.doc-conflicts` | The integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
+| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |
+| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |
+| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |
<!-- END GENERATED: response-types -->
<!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
index 456cb038f8..09d6ff119f 100644
--- a/packages/cli/api/component/_adapter.mjs
+++ b/packages/cli/api/component/_adapter.mjs
@@ -18,6 +18,8 @@
* deduped, so each leaf stays a thin projection.
*/
+import * as fs from 'node:fs';
+import * as path from 'node:path';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {
findCoreDir,
@@ -146,6 +148,34 @@ function findLoadedIntegration(loadedIntegrations, packageName) {
return loadedIntegrations.find(i => i.name === packageName) ?? null;
}
+/**
+ * Read the exact installed version available to a package-qualified component
+ * selector. Legacy docs packages do not expose a reliable version here, so a
+ * version-qualified lookup never falls through to them.
+ * @param {string} coreDir
+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrations
+ * @param {string} packageName
+ * @returns {string|null}
+ */
+export function installedComponentPackageVersion(
+ coreDir,
+ loadedIntegrations,
+ packageName,
+) {
+ if (packageName === CORE_PACKAGE) {
+ try {
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(coreDir, 'package.json'), 'utf8'),
+ );
+ return typeof pkg.version === 'string' ? pkg.version : null;
+ } catch {
+ return null;
+ }
+ }
+ const integration = findLoadedIntegration(loadedIntegrations, packageName);
+ return typeof integration?.version === 'string' ? integration.version : null;
+}
+
/**
* Resolve an external package by name from the discovered externals list.
* @param {string} packageName - e.g. '@acme/xds-widgets'
@@ -244,6 +274,34 @@ export function classifyScope(
return {kind: 'legacy', ext};
}
+/**
+ * Internal ambiguity marker. Single-component callers still receive the same
+ * AstryxError code, message, and suggestions; batch callers can additionally
+ * project every installed candidate without parsing prose.
+ */
+export class ComponentAmbiguityError extends AstryxError {
+ /** @type {import('./component.type.mjs').ComponentBatchCandidate[]} */
+ candidates;
+
+ /**
+ * @param {ComponentOwner[]} owners
+ * @param {string} dirName
+ */
+ constructor(owners, dirName) {
+ super(
+ `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,
+ );
+ this.candidates = owners.map(owner => ({
+ package: owner.package,
+ component: dirName,
+ kind: 'component',
+ installed: true,
+ }));
+ }
+}
+
/**
* 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
@@ -254,11 +312,7 @@ export function classifyScope(
*/
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,
- );
+ throw new ComponentAmbiguityError(owners, dirName);
}
}
diff --git a/packages/cli/api/component/component.doc.mjs b/packages/cli/api/component/component.doc.mjs
index 625e443cf8..15ce9c6f69 100644
--- a/packages/cli/api/component/component.doc.mjs
+++ b/packages/cli/api/component/component.doc.mjs
@@ -15,16 +15,16 @@ export const doc = {
namespace: 'cli/api',
displayName: 'component()',
summary:
- 'Resolve a component by name, or list the catalog, with optional focused slices (props, source, showcase, blocks).',
+ 'Resolve one or several components by name, or list the catalog, with optional focused slices (props, source, showcase, blocks).',
description:
- 'Routes on its arguments: a name resolves that component across core and ' +
- 'integration packages and returns its authored ComponentDoc plus ownership ' +
- 'metadata; no name (or `list`/`category`) returns the catalog grouped by ' +
- 'category. Boolean flags narrow a single component to just its props, ' +
- 'source, showcase, or example blocks.',
+ 'Routes on its arguments: one string resolves that component across core and ' +
+ 'integration packages; an array returns one ordered result row per selector at ' +
+ 'every array length; and no name returns the catalog grouped by category. ' +
+ 'Boolean flags narrow each resolved component to just its props, source, ' +
+ 'showcase, or example blocks.',
importPath: '@astryxdesign/cli/api',
signature:
- 'component(name?: string, options?: ComponentOptions): Promise<ComponentListResponse | ComponentDetailResponse | ComponentDetailPropsResponse | ComponentDetailSourceResponse | ComponentDetailShowcaseResponse | ComponentDetailBlocksResponse>',
+ 'component(name?: string | string[], options?: ComponentOptions): Promise<ComponentListResponse | ComponentBatchResponse | ComponentDetailResponse | ComponentDetailPropsResponse | ComponentDetailSourceResponse | ComponentDetailShowcaseResponse | ComponentDetailBlocksResponse>',
keywords: [
'component',
'components',
@@ -37,9 +37,9 @@ export const doc = {
params: [
{
name: 'name',
- type: 'string',
+ type: 'string | string[]',
description:
- "Component name to resolve (e.g. 'Button'). Omit to list the catalog.",
+ "Pass one selector string for the existing single-result response, or an array of at most 100 selectors for an ordered component.batch response. The limit counts duplicates in every projection mode. An array always requests a batch, including [] and ['Button']. Use 'Button', 'widgets/Button', '@acme/widgets/Button', or '@acme/[email protected]/Button'. A version applies to the package and must match the installed version. Omit the argument to list the catalog.",
},
{
name: 'options.cwd',
@@ -112,6 +112,11 @@ export const doc = {
description:
"The catalog grouped by category. data.detail is the level ('names' | 'compact' | 'full') and data.components is the grouped map: names entries with name, package, and an optional canonical import for integration and legacy package components; brief entries; or full ComponentDoc entries.",
},
+ {
+ type: 'component.batch',
+ description:
+ 'An explicit selector array returns one ordered receipt at every array length: count and one results row per selector, including duplicates. ComponentBatchResponse specializes the shared BatchResponse and BatchRow types. Each row carries selector and status (found, not_found, ambiguous, or error); found rows carry the single-selector result, ambiguous rows carry installed candidates ({package, component, kind, installed}), and failed rows carry code, error, and optional suggestions.',
+ },
{
type: 'component.detail',
description:
@@ -137,6 +142,10 @@ export const doc = {
},
],
throws: [
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: 'a selector array has more than 100 entries, a package-shaped selector has no component item, or its package conflicts with options.package',
+ },
{
code: 'ERR_INVALID_DETAIL',
when: "options.detail is not 'full', 'compact', or 'brief'",
@@ -159,7 +168,7 @@ export const doc = {
},
{
code: 'ERR_UNKNOWN_PACKAGE',
- when: 'options.package names a legacy external package that cannot be found',
+ when: 'options.package names a legacy external package that cannot be found, or a package-qualified selector requests a version that is not installed',
},
{
code: 'ERR_NO_DOC',
@@ -179,6 +188,10 @@ export const doc = {
label: 'Look up a component',
code: "const r = await component('Button');",
},
+ {
+ label: 'Look up several components',
+ code: "await component(['Button', 'Badge']);",
+ },
{label: 'Props only', code: "await component('Button', {props: true});"},
{
label: 'Browse a category',
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index b72b58a1d1..e8c867b6bf 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -4,10 +4,10 @@
* @file Programmatic API for the component command — DISPATCHER + BARREL.
*
* 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.
+ * outputs. `component(name, opts)` parses one selector or an ordered selector
+ * list, resolves each subject through `_adapter`, and routes to the correct leaf
+ * (list · detail · detail.props/source/showcase/blocks). The CLI command handler
+ * is a thin wrapper around this function.
*
* Every leaf is also re-exported for direct scripting use.
*/
@@ -26,6 +26,8 @@ import {
resolveUnscopedDoc,
loadComponentDoc,
scopeSubComponent,
+ ComponentAmbiguityError,
+ installedComponentPackageVersion,
} from './_adapter.mjs';
import {componentList} from './list/list.mjs';
import {componentDetail} from './detail/detail.mjs';
@@ -34,13 +36,199 @@ import {componentDetailSource} from './detail/source/source.mjs';
import {componentDetailShowcase} from './detail/showcase/showcase.mjs';
import {componentDetailBlocks} from './detail/blocks/blocks.mjs';
+/** Maximum selectors accepted before any component resolution starts. */
+export const COMPONENT_BATCH_SELECTOR_LIMIT = 100;
+
/** @type {ReadonlyArray<string>} */
const DETAIL_LEVELS = ['full', 'compact', 'brief'];
/** @type {ReadonlyArray<string>} */
const LANGS = ['en', 'zh', 'dense'];
+/** @type {Set<string>} */
+const NOT_FOUND_CODES = new Set([
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,
+ ERROR_CODES.ERR_NOT_FOUND,
+]);
+
+/**
+ * Discover-compatible package target grammar. Versions belong to the package
+ * head, never the item after the package slash.
+ * @param {string} selector
+ * @returns {{scoped: boolean, name: string, version?: string, item?: string}}
+ */
+function splitSelector(selector) {
+ const scoped = selector.startsWith('@');
+ const firstSlash = selector.indexOf('/');
+ let head = selector;
+ /** @type {string | undefined} */
+ let rest;
+ const split = scoped
+ ? firstSlash < 0
+ ? -1
+ : selector.indexOf('/', firstSlash + 1)
+ : firstSlash;
+ if (split > 0) {
+ head = selector.slice(0, split);
+ rest = selector.slice(split + 1) || undefined;
+ }
+ const at = head.indexOf('@', 1);
+ return {
+ scoped,
+ name: at > 0 ? head.slice(0, at) : head,
+ ...(at > 0 && head.slice(at + 1) ? {version: head.slice(at + 1)} : {}),
+ ...(rest ? {item: rest} : {}),
+ };
+}
+
+/**
+ * Resolve one component selector into the existing single-component API inputs.
+ * @param {unknown} value
+ * @param {string|undefined} packageScope
+ * @returns {{selector: string, name: string, package?: string, version?: string}}
+ */
+function parseComponentSelector(value, packageScope) {
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new AstryxError(
+ `Invalid component selector "${String(value)}"`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ const target = splitSelector(value);
+ const packageShaped =
+ target.scoped || target.item != null || target.version != null;
+ if (!packageShaped) {
+ return {selector: value, name: target.name, package: packageScope};
+ }
+ if (!target.item) {
+ throw new AstryxError(
+ `Component selector "${value}" names a package but no component`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (packageScope && packageScope !== target.name) {
+ throw new AstryxError(
+ `Component selector "${value}" conflicts with --package "${packageScope}"`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ return {
+ selector: value,
+ name: target.item,
+ package: target.name,
+ ...(target.version ? {version: target.version} : {}),
+ };
+}
+
+/**
+ * A version-qualified selector never falls through to another installed
+ * version. Its structured suggestion points at the command that can discover
+ * the requested package release.
+ * @param {{package?: string, version?: string}} target
+ * @param {string} coreDir
+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrations
+ * @returns {void}
+ */
+function requireInstalledSelectorVersion(target, coreDir, loadedIntegrations) {
+ if (!target.version) return;
+ const packageName = /** @type {string} */ (target.package);
+ const installed = installedComponentPackageVersion(
+ coreDir,
+ loadedIntegrations,
+ packageName,
+ );
+ if (installed === target.version) return;
+ const exact = `${packageName}@${target.version}`;
+ throw new AstryxError(
+ `Package "${exact}" is not installed`,
+ [
+ {
+ name: `astryx discover ${exact}`,
+ reason: 'look up this package version',
+ },
+ ],
+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,
+ );
+}
+
+/**
+ * Turn a single-lookup failure into one complete batch row.
+ * @param {string} selector
+ * @param {unknown} error
+ * @returns {import('./component.type.mjs').ComponentBatchResult}
+ */
+function batchFailure(selector, error) {
+ const err =
+ error instanceof AstryxError
+ ? error
+ : new AstryxError(
+ error instanceof Error ? error.message : String(error),
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN,
+ );
+ if (err instanceof ComponentAmbiguityError) {
+ return {
+ selector,
+ status: 'ambiguous',
+ code: err.code,
+ error: err.message,
+ candidates: err.candidates,
+ };
+ }
+ return {
+ selector,
+ status: NOT_FOUND_CODES.has(err.code) ? 'not_found' : 'error',
+ code: err.code,
+ error: err.message,
+ ...(err.suggestions ? {suggestions: err.suggestions} : {}),
+ };
+}
/**
- * @param {string} [name]
+ * @param {unknown[]} selectors
+ * @param {object} options
+ * @param {string} options.cwd
+ * @param {string} [options.package]
+ * @param {boolean} [options.props]
+ * @param {boolean} [options.source]
+ * @param {boolean} [options.showcase]
+ * @param {boolean} [options.blocks]
+ * @param {'full'|'compact'|'brief'} [options.detail]
+ * @param {string|null} [options.lang]
+ * @param {boolean} [options.zh]
+ * @param {boolean} [options.dense]
+ * @param {string} coreDir
+ * @returns {Promise<import('./component.type.mjs').ComponentBatchResponse>}
+ */
+async function componentBatch(selectors, options, coreDir) {
+ const loadedIntegrations = await loadIntegrationsSafely(options.cwd);
+ /** @type {import('./component.type.mjs').ComponentBatchResult[]} */
+ const results = [];
+ for (const value of selectors) {
+ const selector = typeof value === 'string' ? value : String(value);
+ try {
+ const target = parseComponentSelector(value, options.package);
+ requireInstalledSelectorVersion(target, coreDir, loadedIntegrations);
+ const result =
+ /** @type {import('./component.type.mjs').ComponentSingleResponse} */ (
+ await component(target.name, {
+ ...options,
+ lang: options.lang ?? undefined,
+ package: target.package,
+ })
+ );
+ results.push({selector, status: 'found', result});
+ } catch (error) {
+ results.push(batchFailure(selector, error));
+ }
+ }
+ return {type: 'component.batch', data: {count: results.length, results}};
+}
+
+/**
+ * @param {string|string[]} [name]
* @param {object} [options]
* @param {string} [options.cwd]
* @param {boolean} [options.list]
@@ -56,6 +244,7 @@ const LANGS = ['en', 'zh', 'dense'];
* @param {boolean} [options.dense]
* @returns {Promise<(
* import('./component.type.mjs').ComponentListResponse
+ * | import('./component.type.mjs').ComponentBatchResponse
* | import('./component.type.mjs').ComponentDetailResponse
* | import('./component.type.mjs').ComponentDetailPropsResponse
* | import('./component.type.mjs').ComponentDetailSourceResponse
@@ -79,11 +268,16 @@ export async function component(name, options = {}) {
dense = false,
} = options;
+ const selectorList = Array.isArray(name) ? name : null;
+ const noName = selectorList == null && !name;
+
// Default detail level mirrors the CLI (see commands/component/index.mjs):
// single-component views default to 'full', list-style views (--list,
// --category, or no name) default to 'brief' (scannable name lists).
- // Keeping this in sync with the CLI is what the API↔CLI parity test checks.
- const isListView = list || category != null || !name;
+ // An explicit array remains a batch even when it is empty or a caller also
+ // passes a list-only option.
+ const isListView =
+ selectorList == null && (list || category != null || noName);
const detail = detailOption ?? (isListView ? 'brief' : 'full');
// Same accepted values and codes as the CLI's --detail and --lang, checked
@@ -103,6 +297,14 @@ export async function component(name, options = {}) {
);
}
+ if (selectorList && selectorList.length > COMPONENT_BATCH_SELECTOR_LIMIT) {
+ throw new AstryxError(
+ `Component batch accepts at most ${COMPONENT_BATCH_SELECTOR_LIMIT} selectors; received ${selectorList.length}`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+
const coreDir = requireCoreDir(cwd);
// A public API caller could pass a non-string category; the list leaf does
@@ -116,11 +318,46 @@ export async function component(name, options = {}) {
);
}
+ // ── Explicit batch selector list ─────────────────────────────────
+ // Array shape owns cardinality even if a caller also supplies a list-only
+ // option. The aggregate limit above is checked before core or integrations
+ // are resolved, so an oversized request can never emit a partial receipt.
+ if (selectorList) {
+ return componentBatch(
+ selectorList,
+ {
+ cwd,
+ package: packageScope,
+ props,
+ source,
+ showcase,
+ blocks,
+ detail,
+ lang,
+ zh,
+ dense,
+ },
+ coreDir,
+ );
+ }
+
// ── List mode ──────────────────────────────────────────────────
- if (category || list || !name) {
+ if (category || list || noName) {
return componentList(coreDir, {cwd, category, detail, zh, dense, lang});
}
+ if (typeof name === 'string') {
+ const target = parseComponentSelector(name, packageScope);
+ if (target.version) {
+ const loadedIntegrations = await loadIntegrationsSafely(cwd);
+ requireInstalledSelectorVersion(target, coreDir, loadedIntegrations);
+ }
+ if (target.name !== name || target.package !== packageScope) {
+ return component(target.name, {...options, package: target.package});
+ }
+ name = target.name;
+ }
+
// ── Single component ───────────────────────────────────────────
if (typeof name !== 'string') {
throw new AstryxError(
@@ -186,7 +423,10 @@ export async function component(name, options = {}) {
if (extDocPath) {
// Legacy packages ship docs, never source.
if (source) {
- return componentDetailSource(dirName, null, {name, notFoundInPackage: packageScope});
+ return componentDetailSource(dirName, null, {
+ name,
+ notFoundInPackage: packageScope,
+ });
}
if (blocks) {
return componentDetailBlocks(dirName, cwd);
diff --git a/packages/cli/api/component/component.type.mjs b/packages/cli/api/component/component.type.mjs
index 02e6d03925..7246154d21 100644
--- a/packages/cli/api/component/component.type.mjs
+++ b/packages/cli/api/component/component.type.mjs
@@ -18,6 +18,9 @@
* astryx --json component --category Form -> component.list (filtered)
* astryx --json component --list --detail compact -> component.list (data.detail='compact')
* astryx --json component --list --detail full -> component.list (data.detail='full')
+ * component([]) -> component.batch (data.count=0)
+ * component(['Button']) -> component.batch (data.count=1)
+ * astryx --json component Button Badge -> component.batch
* astryx --json component Button -> component.detail
* astryx --json component Button --props -> component.detail.props
* astryx --json component Button --source -> component.detail.source
@@ -49,6 +52,47 @@
* )} ComponentListData
*/
+/**
+ * `component(string[])` always returns this type, including empty and one-item
+ * arrays. The CLI returns it for two or more positional selectors.
+ * @typedef {import('../../foundation/response/batch.type.mjs').BatchResponse<
+ * 'component.batch',
+ * ComponentSingleResponse,
+ * ComponentBatchCandidate
+ * >} ComponentBatchResponse
+ */
+
+/**
+ * One installed component that makes an unqualified selector ambiguous.
+ * Keys match a component row in `discover.search` so a caller does not learn a
+ * second candidate shape.
+ * @typedef {object} ComponentBatchCandidate
+ * @property {string} package
+ * @property {string} component
+ * @property {'component'} kind
+ * @property {true} installed
+ */
+
+/**
+ * The response a successful single selector would have returned.
+ * @typedef {(
+ * | ComponentDetailResponse
+ * | ComponentDetailPropsResponse
+ * | ComponentDetailSourceResponse
+ * | ComponentDetailShowcaseResponse
+ * | ComponentDetailBlocksResponse
+ * )} ComponentSingleResponse
+ */
+
+/**
+ * One row per requested selector, in argument order. Duplicate selectors keep
+ * duplicate rows.
+ * @typedef {import('../../foundation/response/batch.type.mjs').BatchRow<
+ * ComponentSingleResponse,
+ * ComponentBatchCandidate
+ * >} ComponentBatchResult
+ */
+
/**
* A single entry in a `component.list` group at `detail: 'names'`. Pre-1.0 the
* list moved from bare strings to package-qualified objects so consumers can
diff --git a/packages/cli/api/docs/docs.test.mjs b/packages/cli/api/docs/docs.test.mjs
index 7e815fb0f3..aaa22e2af2 100644
--- a/packages/cli/api/docs/docs.test.mjs
+++ b/packages/cli/api/docs/docs.test.mjs
@@ -146,6 +146,7 @@ describe('docs() dispatcher routing', () => {
// A guide moves across its namespace's slot, as any tree node does.
expect(index.data.links).toEqual({
up: 'astryx docs cli',
+ previous: 'astryx docs cli/component-lookups',
next: 'astryx docs cli/writing-docs',
});
const first = (await docs('cli/integrations', index.data.sections[0].id)).data;
@@ -209,6 +210,7 @@ describe('docs() dispatcher routing', () => {
expect(err).toBeInstanceOf(AstryxError);
expect(err.code).toBe('ERR_UNKNOWN_SECTION');
expect(err.suggestions.map(s => s.name)).toEqual([
+ 'cli/component-lookups',
'cli/integrations',
'cli/writing-docs',
'cli/commands',
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index 460c0e5abb..f3e5514489 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -73,10 +73,12 @@ export {logger} from './logger.mjs';
* @typedef {import('./logger.mjs').Logger} Logger
*/
-// ── Types (re-exported from each command's colocated `.type.mjs`) ─────
+// ── Types (re-exported from the shared response foundation and each command's
+// colocated `.type.mjs`) ──────────────────────────────────────────────────
// Runtime no-ops (the .type.mjs files are `export {}`); tsc carries these
// through to the generated api/index.d.mts so the public type surface exposes
-// every command's Options + response types by name.
+// the shared receipt vocabulary and every command's Options + response types.
+export * from '../foundation/response/batch.type.mjs';
export * from './component/component.type.mjs';
export * from './docs/docs.type.mjs';
export * from './blog/blog.type.mjs';
diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjs
index aa041c642c..9f113c177c 100644
--- a/packages/cli/api/search/search.test.mjs
+++ b/packages/cli/api/search/search.test.mjs
@@ -127,6 +127,24 @@ describe('search leaf — docs at the grain a reader reads them', () => {
SLOW,
);
+ it(
+ 'finds the component batch guide from task language',
+ async () => {
+ const result = await search('look up several components', {
+ cwd,
+ type: 'doc',
+ });
+ expect(result.data.results).toContainEqual(
+ expect.objectContaining({
+ name: 'cli/component-lookups',
+ section: 'several',
+ command: 'astryx docs cli/component-lookups several',
+ }),
+ );
+ },
+ SLOW,
+ );
+
it(
'gives a top-level namespace hit the topic list as its parent',
async () => {
diff --git a/packages/cli/assets/docs/tree/component-lookups.doc.mjs b/packages/cli/assets/docs/tree/component-lookups.doc.mjs
new file mode 100644
index 0000000000..35024e4063
--- /dev/null
+++ b/packages/cli/assets/docs/tree/component-lookups.doc.mjs
@@ -0,0 +1,149 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs cli/component-lookups`: exact single and batch component
+ * lookup through the CLI and programmatic API.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
+export const docs = {
+ type: 'generic',
+ name: 'component-lookups',
+ placement: {parent: 'namespace:cli', slot: 'guides', order: 5},
+ title: 'Looking up components',
+ category: 'guide',
+ description:
+ 'Look up one or several exact component identities, choose a focused projection, and handle complete batch receipts.',
+ sections: [
+ {
+ id: 'several',
+ title: 'Look up several components',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: '`astryx component` accepts exact selectors as a variadic positional argument. With no selector it browses the catalog. With one selector it keeps the normal single-component response. With two or more it prints one complete ordered batch receipt.',
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ label: 'Several component docs',
+ code: 'astryx component Button Badge Text\nastryx --json component Button Badge Text',
+ },
+ {
+ type: 'prose',
+ text: 'Every selector gets one row in input order. Duplicate selectors stay duplicate rows. A missing or ambiguous component does not hide successful neighbors or stop later selectors from resolving.',
+ },
+ {
+ type: 'prose',
+ text: 'A batch accepts at most 100 selectors, including duplicates, in every projection mode. A larger request returns a top-level `ERR_INVALID_ARGUMENT` before any component resolves. It emits no `component.batch` receipt and no partial results.',
+ },
+ {
+ type: 'prose',
+ text: 'Focused component controls apply to every found row. Use the same control you use for one component:',
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ label: 'Focused batch lookups',
+ code: 'astryx --json component Button Card --props\nastryx component Button Card --source\nastryx component Button Card --showcase\nastryx component Button Card --blocks\nastryx component Button Card --detail compact\nastryx component Button Card --lang dense\nastryx component Button Card --package @astryxdesign/core',
+ },
+ ],
+ },
+ {
+ id: 'selectors',
+ title: 'Selector forms',
+ category: 'reference',
+ content: [
+ {
+ type: 'prose',
+ text: 'A selector is an exact component identity, not free-text search. Use one of these forms:',
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ '`Button` for an unqualified component name.',
+ '`widgets/Button` for a component in an unscoped package.',
+ '`@acme/widgets/Button` for a component in a scoped package.',
+ '`@acme/[email protected]/Button` to require that exact installed package version.',
+ ],
+ },
+ {
+ type: 'prose',
+ text: 'A version qualifies the package, never the component. The lookup does not fall through to another installed version. An unqualified name owned by several installed packages is `ambiguous` and lists every candidate. Use a package-qualified selector or `--package` to choose one.',
+ },
+ {
+ type: 'prose',
+ text: '`astryx discover` remains free-text package discovery. Its words form one query; they are not component batch selectors.',
+ },
+ ],
+ },
+ {
+ id: 'output',
+ title: 'Batch output and exit status',
+ category: 'reference',
+ content: [
+ {
+ type: 'prose',
+ text: 'JSON uses `component.batch` with `{count, results}`. Each row echoes `selector` and has one status: `found`, `not_found`, `ambiguous`, or `error`. A found row carries the normal single-component `{type, data}` under `result`. Failed rows carry `code` and `error`, plus `suggestions` or `candidates` when available.',
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ label: 'Outcome and duplicate examples',
+ code: 'astryx --json component Button Badge # all found, exit 0\nastryx --json component Button MissingWidget # mixed, exit 1\nastryx --json component MissingWidget MissingPanel # all failed, exit 1\nastryx --json component Button Button # two ordered rows, exit 0',
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ label: 'A complete failed JSON receipt',
+ code: 'astryx --json component MissingWidget MissingPanel',
+ },
+ {
+ type: 'code',
+ lang: 'json',
+ code: '{\n "apiVersion": 1,\n "type": "component.batch",\n "data": {\n "count": 2,\n "results": [\n {\n "selector": "MissingWidget",\n "status": "not_found",\n "code": "ERR_UNKNOWN_COMPONENT",\n "error": "No component named \\"MissingWidget\\""\n },\n {\n "selector": "MissingPanel",\n "status": "not_found",\n "code": "ERR_UNKNOWN_COMPONENT",\n "error": "No component named \\"MissingPanel\\""\n }\n ]\n }\n}',
+ },
+ {
+ type: 'code',
+ lang: 'text',
+ label: 'The same receipt in text mode',
+ code: 'Component batch\n\ncount: 2\n\nResults\n\nMissingWidget\n\nselector: MissingWidget\nstatus: not_found\ncode: ERR_UNKNOWN_COMPONENT\nerror: No component named "MissingWidget"\n\nMissingPanel\n\nselector: MissingPanel\nstatus: not_found\ncode: ERR_UNKNOWN_COMPONENT\nerror: No component named "MissingPanel"',
+ },
+ {
+ type: 'prose',
+ text: 'The CLI emits every row first, then exits 1 when any row is not `found`. This includes mixed receipts and receipts where every row failed. JSON and text use the same exit status. A batch where every row is `found` exits 0.',
+ },
+ ],
+ },
+ {
+ id: 'api',
+ title: 'Programmatic API',
+ category: 'reference',
+ content: [
+ {
+ type: 'prose',
+ text: 'The argument shape chooses the response shape. Omit the argument for the catalog, pass a string for the existing single-component response, and pass an array for `component.batch`. An array always means batch, including empty and one-item arrays, so filtering a selector list cannot silently change the response type. The published `ComponentBatchResponse` specializes the shared `BatchResponse` and `BatchRow` types.',
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ code: "import {component} from '@astryxdesign/cli/api';\n\nconst catalog = await component(); // component.list\nconst button = await component('Button'); // component.detail\nconst empty = await component([]); // component.batch, count 0\nconst oneRow = await component(['Button']); // component.batch, count 1\nconst batch = await component(['Button', 'Badge']); // component.batch, count 2\nawait component(Array(101).fill('Button')); // ERR_INVALID_ARGUMENT before lookup",
+ },
+ {
+ type: 'code',
+ lang: 'json',
+ label: 'Exact empty-array response',
+ code: '{\n "type": "component.batch",\n "data": {\n "count": 0,\n "results": []\n }\n}',
+ },
+ {
+ type: 'code',
+ lang: 'javascript',
+ label: 'Handle every row without losing partial results',
+ code: "const receipt = await component(['Button', 'MissingWidget']);\n\nfor (const row of receipt.data.results) {\n if (row.status === 'found') {\n useComponentDoc(row.selector, row.result);\n } else if (row.status === 'ambiguous') {\n choosePackage(row.selector, row.candidates);\n } else {\n reportLookupFailure(row.selector, row.code, row.error);\n }\n}",
+ },
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/clients/cli/commands/component-batch.test.mjs b/packages/cli/clients/cli/commands/component-batch.test.mjs
new file mode 100644
index 0000000000..a9c601cef9
--- /dev/null
+++ b/packages/cli/clients/cli/commands/component-batch.test.mjs
@@ -0,0 +1,341 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Multi-selector component lookup contract: one ordered batch envelope,
+ * complete per-selector states, unchanged single-selector responses, and matching
+ * text/JSON exit behavior.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as path from 'node:path';
+import {
+ component,
+ COMPONENT_BATCH_SELECTOR_LIMIT,
+} from '../../../api/component/component.mjs';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+const REPO_ROOT = path.resolve(import.meta.dirname, '../../../../..');
+const SLOW = 60_000;
+
+describe('component() batch lookup', () => {
+ it(
+ 'keeps one found row per selector, in order, including duplicates',
+ async () => {
+ const result = await component(['Button', 'Badge', 'Button'], {
+ cwd: REPO_ROOT,
+ detail: 'brief',
+ });
+
+ expect(result.type).toBe('component.batch');
+ expect(result.data.count).toBe(3);
+ expect(result.data.results.map(row => row.selector)).toEqual([
+ 'Button',
+ 'Badge',
+ 'Button',
+ ]);
+ expect(result.data.results.map(row => row.status)).toEqual([
+ 'found',
+ 'found',
+ 'found',
+ ]);
+ expect(
+ result.data.results.map(row =>
+ row.status === 'found' ? row.result.type : null,
+ ),
+ ).toEqual(['component.detail', 'component.detail', 'component.detail']);
+ },
+ SLOW,
+ );
+
+ it(
+ 'applies every focused projection to each found row',
+ async () => {
+ const projections = [
+ {options: {props: true}, expectedType: 'component.detail.props'},
+ {options: {source: true}, expectedType: 'component.detail.source'},
+ {options: {showcase: true}, expectedType: 'component.detail.showcase'},
+ {options: {blocks: true}, expectedType: 'component.detail.blocks'},
+ ];
+ for (const projection of projections) {
+ const result = await component(['Button', 'Card'], {
+ cwd: REPO_ROOT,
+ ...projection.options,
+ });
+ expect(result.type).toBe('component.batch');
+ expect(
+ result.data.results.map(row =>
+ row.status === 'found' ? row.result.type : null,
+ ),
+ ).toEqual([projection.expectedType, projection.expectedType]);
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'uses input shape to distinguish catalog, single, and batch calls',
+ async () => {
+ expect((await component(undefined, {cwd: REPO_ROOT})).type).toBe(
+ 'component.list',
+ );
+ expect((await component('Button', {cwd: REPO_ROOT})).type).toBe(
+ 'component.detail',
+ );
+
+ const emptyBatch = await component([], {cwd: REPO_ROOT});
+ expect(emptyBatch).toEqual({
+ type: 'component.batch',
+ data: {count: 0, results: []},
+ });
+ expect(
+ await component([], {
+ cwd: REPO_ROOT,
+ list: true,
+ category: 'Form',
+ }),
+ ).toEqual(emptyBatch);
+
+ const oneRowBatch = await component(['Button'], {
+ cwd: REPO_ROOT,
+ detail: 'brief',
+ });
+ expect(oneRowBatch).toMatchObject({
+ type: 'component.batch',
+ data: {
+ count: 1,
+ results: [
+ {
+ selector: 'Button',
+ status: 'found',
+ result: {type: 'component.detail'},
+ },
+ ],
+ },
+ });
+ },
+ SLOW,
+ );
+
+ it('rejects an oversized array before component resolution starts', async () => {
+ const selectors = Array.from(
+ {length: COMPONENT_BATCH_SELECTOR_LIMIT + 1},
+ () => 'Button',
+ );
+ await expect(
+ component(selectors, {
+ cwd: path.join(REPO_ROOT, 'missing-batch-cwd'),
+ }),
+ ).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ message: `Component batch accepts at most ${COMPONENT_BATCH_SELECTOR_LIMIT} selectors; received ${selectors.length}`,
+ });
+ });
+
+ it(
+ 'keeps receipt invariants across a deterministic selector chaos matrix',
+ async () => {
+ const found = new Set(['Button', 'Card']);
+ const selectorCases = [
+ [],
+ ['Button'],
+ ['ZzzNope99'],
+ ['Button', 'Button'],
+ ['ZzzNope98', 'ZzzNope99'],
+ ['Button', 'ZzzNope99', 'Card'],
+ ['ZzzNope99', 'Button', 'ZzzNope99', 'Button'],
+ ['Card', 'Button', 'Card', 'ZzzNope98', 'Button'],
+ ];
+
+ for (const selectors of selectorCases) {
+ const result = await component(selectors, {
+ cwd: REPO_ROOT,
+ detail: 'brief',
+ });
+ expect(result.type).toBe('component.batch');
+ expect(result.data.count).toBe(selectors.length);
+ expect(result.data.results.map(row => row.selector)).toEqual(selectors);
+ expect(result.data.results.map(row => row.status)).toEqual(
+ selectors.map(selector =>
+ found.has(selector) ? 'found' : 'not_found',
+ ),
+ );
+ for (const row of result.data.results) {
+ if (row.status === 'found') {
+ expect(row.result.type).toBe('component.detail');
+ } else {
+ expect(row.code).toBe('ERR_UNKNOWN_COMPONENT');
+ }
+ }
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'composes every detail and language control over a batch',
+ async () => {
+ /** @type {Array<{detail?: 'full'|'compact'|'brief'; lang?: string; zh?: boolean; dense?: boolean}>} */
+ const controls = [
+ {detail: 'brief'},
+ {detail: 'compact'},
+ {detail: 'full'},
+ {lang: 'en'},
+ {lang: 'dense'},
+ {zh: true},
+ {dense: true},
+ ];
+ for (const control of controls) {
+ const result = await component(['Button', 'Card'], {
+ cwd: REPO_ROOT,
+ ...control,
+ });
+ expect(result.type).toBe('component.batch');
+ expect(result.data.results).toHaveLength(2);
+ expect(
+ result.data.results.every(
+ row =>
+ row.status === 'found' && row.result.type === 'component.detail',
+ ),
+ ).toBe(true);
+ }
+ },
+ SLOW,
+ );
+});
+
+describe('astryx component batch lookup', () => {
+ it('documents variadic selector grammar in --help', async () => {
+ const run = await runCli(['component', '--help'], REPO_ROOT);
+ expect(run.code).toBe(0);
+ expect(run.stdout).toContain(
+ 'Usage: astryx component [options] [names...]',
+ );
+ expect(run.stdout).toContain('@scope/package@version/Name');
+ expect(run.stdout).toContain('Two or more return one ordered batch');
+ expect(run.stdout).toContain('At most 100 selectors');
+ });
+
+ it(
+ 'keeps catalog and single-result CLI envelopes at zero and one selectors',
+ async () => {
+ const catalog = await runCli(['--json', 'component'], REPO_ROOT);
+ expect(catalog.code).toBe(0);
+ expect(JSON.parse(catalog.stdout).type).toBe('component.list');
+
+ const single = await runCli(
+ ['--json', '--detail', 'brief', 'component', 'Button'],
+ REPO_ROOT,
+ );
+ expect(single.code).toBe(0);
+ expect(JSON.parse(single.stdout).type).toBe('component.detail');
+ },
+ SLOW,
+ );
+
+ it(
+ 'emits one component.batch JSON envelope for several found selectors',
+ async () => {
+ const run = await runCli(
+ ['--json', '--detail', 'brief', 'component', 'Button', 'Badge'],
+ REPO_ROOT,
+ );
+ expect(run.code).toBe(0);
+ const envelope = JSON.parse(run.stdout);
+ expect(envelope.type).toBe('component.batch');
+ expect(envelope.data.count).toBe(2);
+ expect(envelope.data.results.map(row => row.selector)).toEqual([
+ 'Button',
+ 'Badge',
+ ]);
+ expect(envelope.data.results.every(row => row.status === 'found')).toBe(
+ true,
+ );
+ },
+ SLOW,
+ );
+
+ it(
+ 'rejects an oversized batch before emitting JSON or text results',
+ async () => {
+ const selectors = Array.from(
+ {length: COMPONENT_BATCH_SELECTOR_LIMIT + 1},
+ () => 'Button',
+ );
+ const json = await runCli(
+ ['--json', 'component', ...selectors],
+ REPO_ROOT,
+ );
+ expect(json.code).toBe(1);
+ expect(JSON.parse(json.stdout)).toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ error: `Component batch accepts at most ${COMPONENT_BATCH_SELECTOR_LIMIT} selectors; received ${selectors.length}`,
+ });
+ expect(JSON.parse(json.stdout).type).toBeUndefined();
+
+ const text = await runCli(['component', ...selectors], REPO_ROOT);
+ expect(text.code).toBe(1);
+ expect(text.stdout + text.stderr).toContain(
+ `accepts at most ${COMPONENT_BATCH_SELECTOR_LIMIT} selectors`,
+ );
+ },
+ SLOW,
+ );
+
+ it(
+ 'emits every row and exits 1 when one selector is not found',
+ async () => {
+ const run = await runCli(
+ ['--json', '--detail', 'brief', 'component', 'Button', 'ZzzNope99'],
+ REPO_ROOT,
+ );
+ expect(run.code).toBe(1);
+ const envelope = JSON.parse(run.stdout);
+ expect(envelope.type).toBe('component.batch');
+ expect(envelope.data.results).toMatchObject([
+ {selector: 'Button', status: 'found'},
+ {
+ selector: 'ZzzNope99',
+ status: 'not_found',
+ code: 'ERR_UNKNOWN_COMPONENT',
+ },
+ ]);
+ },
+ SLOW,
+ );
+
+ it(
+ 'emits every failed row and exits 1 when no selector resolves',
+ async () => {
+ const run = await runCli(
+ ['--json', 'component', 'ZzzNope98', 'ZzzNope99'],
+ REPO_ROOT,
+ );
+ expect(run.code).toBe(1);
+ const envelope = JSON.parse(run.stdout);
+ expect(envelope.type).toBe('component.batch');
+ expect(envelope.data.count).toBe(2);
+ expect(envelope.data.results).toMatchObject([
+ {selector: 'ZzzNope98', status: 'not_found'},
+ {selector: 'ZzzNope99', status: 'not_found'},
+ ]);
+ },
+ SLOW,
+ );
+
+ it(
+ 'projects every row in text and keeps the same failing exit status',
+ async () => {
+ const run = await runCli(
+ ['--detail', 'brief', 'component', 'Button', 'ZzzNope99'],
+ REPO_ROOT,
+ );
+ expect(run.code).toBe(1);
+ expect(run.stdout).toContain('count: 2');
+ expect(run.stdout).toMatch(/selector: Button\nstatus:\s+found/);
+ expect(run.stdout).toMatch(
+ /selector: ZzzNope99\nstatus:\s+not_found\ncode:\s+ERR_UNKNOWN_COMPONENT/,
+ );
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/clients/cli/commands/component-ownership.test.mjs b/packages/cli/clients/cli/commands/component-ownership.test.mjs
index c66a2a12b2..400ddff3ce 100644
--- a/packages/cli/clients/cli/commands/component-ownership.test.mjs
+++ b/packages/cli/clients/cli/commands/component-ownership.test.mjs
@@ -277,6 +277,95 @@ describe('component() — integration ownership via config', () => {
expect(result.data.import).toBe(`${INTEGRATION_NAME}/Toolbar/Search`);
});
+ it('reports every installed candidate for an ambiguous batch selector', async () => {
+ createFixture({extraComponent: 'AppShell'});
+ const result = await component(['MetaAppShell', 'AppShell'], {cwd: tmpDir});
+ expect(result.type).toBe('component.batch');
+ expect(result.data.results[0]).toMatchObject({
+ selector: 'MetaAppShell',
+ status: 'found',
+ });
+ expect(result.data.results[1]).toMatchObject({
+ selector: 'AppShell',
+ status: 'ambiguous',
+ code: 'ERR_UNKNOWN_COMPONENT',
+ });
+ expect(result.data.results[1].candidates).toEqual(
+ expect.arrayContaining([
+ {
+ package: CORE_PACKAGE,
+ component: 'AppShell',
+ kind: 'component',
+ installed: true,
+ },
+ {
+ package: INTEGRATION_NAME,
+ component: 'AppShell',
+ kind: 'component',
+ installed: true,
+ },
+ ]),
+ );
+ });
+
+ it('keeps the single-result envelope for one package-qualified selector', async () => {
+ createFixture();
+ const result = await component('@test/[email protected]/MetaAppShell', {
+ cwd: tmpDir,
+ });
+ expect(result.type).toBe('component.detail');
+ expect(result.data).toMatchObject({
+ name: 'MetaAppShell',
+ package: INTEGRATION_NAME,
+ });
+ });
+
+ it('resolves an exact installed package version and refuses another version', async () => {
+ createFixture();
+ const result = await component(
+ [
+ '@test/[email protected]/MetaAppShell',
+ '@test/[email protected]/MetaAppShell',
+ ],
+ {cwd: tmpDir},
+ );
+ expect(result.type).toBe('component.batch');
+ expect(result.data.results[0]).toMatchObject({
+ selector: '@test/[email protected]/MetaAppShell',
+ status: 'found',
+ result: {type: 'component.detail'},
+ });
+ expect(result.data.results[1]).toMatchObject({
+ selector: '@test/[email protected]/MetaAppShell',
+ status: 'not_found',
+ code: 'ERR_UNKNOWN_PACKAGE',
+ suggestions: [
+ {
+ name: 'astryx discover @test/[email protected]',
+ reason: 'look up this package version',
+ },
+ ],
+ });
+ });
+
+ it('reports a package-qualified selector that conflicts with --package', async () => {
+ createFixture();
+ const result = await component(
+ ['@test/meta/MetaAppShell', 'Button'],
+ {cwd: tmpDir, package: CORE_PACKAGE},
+ );
+ expect(result.type).toBe('component.batch');
+ expect(result.data.results[0]).toMatchObject({
+ selector: '@test/meta/MetaAppShell',
+ status: 'error',
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ expect(result.data.results[1]).toMatchObject({
+ selector: 'Button',
+ status: 'found',
+ });
+ });
+
it('JSON list includes integration components as {name, package} objects', async () => {
createFixture();
const result = await component(undefined, {cwd: tmpDir, list: true});
diff --git a/packages/cli/clients/cli/commands/component.doc.mjs b/packages/cli/clients/cli/commands/component.doc.mjs
index 1fe7bf266f..59f8b15b09 100644
--- a/packages/cli/clients/cli/commands/component.doc.mjs
+++ b/packages/cli/clients/cli/commands/component.doc.mjs
@@ -16,11 +16,23 @@ export const doc = {
namespace: 'cli/commands',
summary: 'List components or print component docs',
description:
- 'Resolves a component by name across core and integration packages and prints ' +
- 'its authored doc, or lists the catalog grouped by category. Boolean flags narrow ' +
- 'a single component to just its props, source, showcase, or example blocks.',
+ 'Resolves one or several components by exact selector across core and integration ' +
+ 'packages and prints each authored doc, or lists the catalog grouped by category. ' +
+ "Use 'Button', 'widgets/Button', '@acme/widgets/Button', or " +
+ "'@acme/[email protected]/Button'. A version applies to the package and must match the " +
+ 'installed version. Boolean flags narrow every resolved component to just its props, ' +
+ 'source, showcase, or example blocks.',
fn: 'component',
- args: [{name: 'name', param: 'name', required: false}],
+ args: [
+ {
+ name: 'names',
+ param: 'name',
+ description:
+ 'One or more exact selectors. Use Name, package/Name, @scope/package/Name, or @scope/package@version/Name. Two or more return one ordered batch. At most 100 selectors are accepted.',
+ required: false,
+ variadic: true,
+ },
+ ],
options: [
{
flag: '--list',
@@ -55,11 +67,16 @@ export const doc = {
{
flag: '--package <name>',
param: 'options.package',
- description: 'Scope lookup to an external package (e.g. @acme/xds-widgets)',
+ description:
+ 'Scope lookup to an external package (e.g. @acme/xds-widgets)',
},
],
examples: [
{label: 'Browse the catalog', cli: 'astryx component --list'},
+ {
+ label: 'Look up several components',
+ cli: 'astryx component Button Badge Text',
+ },
{
label: 'Props table as JSON',
cli: 'astryx component XDSButton --props --json',
@@ -69,7 +86,7 @@ export const doc = {
{code: 0, when: 'success'},
{
code: 1,
- when: 'unknown component, category, or package, or @astryxdesign/core cannot be resolved',
+ when: 'unknown component, category, or package; more than 100 selectors; any batch row is unresolved; or @astryxdesign/core cannot be resolved',
},
],
related: ['search', 'hook', 'docs', 'template', 'swizzle'],
diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjs
index 5d38329a42..a649703809 100644
--- a/packages/cli/clients/cli/commands/component/index.mjs
+++ b/packages/cli/clients/cli/commands/component/index.mjs
@@ -38,6 +38,7 @@ import {doc as componentFn} from '../../../../api/component/component.doc.mjs';
*
* @typedef {(
* | import('../../../../api/component/component.type.mjs').ComponentListResponse
+ * | import('../../../../api/component/component.type.mjs').ComponentBatchResponse
* | import('../../../../api/component/component.type.mjs').ComponentDetailResponse
* | import('../../../../api/component/component.type.mjs').ComponentDetailPropsResponse
* | import('../../../../api/component/component.type.mjs').ComponentDetailSourceResponse
@@ -67,6 +68,11 @@ function summarize(result) {
);
return resultSet({count, resultKind: 'component'});
}
+ case 'component.batch':
+ return resultSet({
+ count: result.data.results.filter(row => row.status === 'found').length,
+ resultKind: 'component',
+ });
case 'component.detail':
case 'component.detail.props':
case 'component.detail.source':
@@ -82,19 +88,103 @@ function summarize(result) {
}
}
+/**
+ * Project one single-component API result through the existing formatter kit.
+ * @param {import('../../../../api/component/component.type.mjs').ComponentSingleResponse} result
+ * @param {string} requestedName
+ * @param {'full'|'compact'|'brief'} detail
+ * @param {ReturnType<typeof resolveTheme>} themeData
+ * @returns {import('../../formatters/index.mjs').Block[]}
+ */
+function componentDetailBlocks(result, requestedName, detail, themeData) {
+ const resolvedName = (requestedName.split('/').pop() ?? requestedName).replace(
+ /^XDS/,
+ '',
+ );
+ switch (result.type) {
+ case 'component.detail': {
+ /** @type {import('../../formatters/index.mjs').Block[]} */
+ const out = [];
+ if (result.data.parentDoc) {
+ out.push(record(result.data, {fields: ['parentDoc']}));
+ }
+ out.push(
+ detail === 'brief'
+ ? code(
+ formatBrief(result.data, resolvedName, result.data.import, {
+ themeData,
+ }),
+ )
+ : detail === 'compact'
+ ? code(
+ formatCompact(result.data, resolvedName, result.data.import),
+ )
+ : code(
+ formatFull(result.data, {
+ themeData,
+ importHint: result.data.import,
+ }),
+ ),
+ );
+ return out;
+ }
+ case 'component.detail.props':
+ return [code(formatProps({props: result.data}, resolvedName))];
+ case 'component.detail.source':
+ case 'component.detail.showcase':
+ return [code(result.data.source)];
+ case 'component.detail.blocks': {
+ const {showcase, examples, related} = result.data;
+ /** @type {import('../../formatters/index.mjs').Block[]} */
+ const out = [];
+ if (showcase) {
+ out.push(
+ section('Showcase'),
+ record(showcase, {fields: ['displayName', 'description']}),
+ );
+ }
+ if (examples.length > 0) {
+ out.push(
+ section('Examples'),
+ records(examples, {fields: ['name', 'description']}),
+ );
+ }
+ if (related.length > 0) {
+ out.push(
+ section(
+ `Related: ${related.length} blocks that use ${result.data.component}`,
+ ),
+ list(related.map(block => block.name)),
+ );
+ }
+ if (!showcase && examples.length === 0 && related.length === 0) {
+ out.push(text(`No blocks found for ${result.data.component}`));
+ }
+ return out;
+ }
+ default:
+ return [];
+ }
+}
+
/**
* @param {import('commander').Command} program
*/
export function registerComponent(program) {
defineCommand(program, componentCommand, {
fn: componentFn,
- action: async (/** @type {string | undefined} */ name, /** @type {{list?: boolean, category?: string, props?: boolean, source?: boolean, showcase?: boolean, blocks?: boolean, package?: string}} */ options) => {
+ action: async (
+ /** @type {string[] | undefined} */ names,
+ /** @type {{list?: boolean, category?: string, props?: boolean, source?: boolean, showcase?: boolean, blocks?: boolean, package?: string}} */ options,
+ ) => {
const run = getCliInvocation();
+ const name = names?.length === 1 ? names[0] : undefined;
+ const apiInput = !names?.length ? undefined : name ?? names;
const zh = program.opts().zh || false;
const dense = program.opts().dense || false;
const lang = program.opts().lang || null;
const detailSource = program.getOptionValueSource('detail');
- const isListView = options.list || options.category || !name;
+ const isListView = options.list || options.category || !names?.length;
// Default detail level is full for single-component view, brief for list views.
// (List views are scannable name lists; users can opt into compact/full.)
let detail = program.opts().detail || 'full';
@@ -119,7 +209,7 @@ export function registerComponent(program) {
/** @type {ComponentResult} */
let result;
try {
- result = /** @type {ComponentResult} */ (await componentApi(name, {
+ result = /** @type {ComponentResult} */ (await componentApi(apiInput, {
cwd: process.cwd(),
list: options.list,
category: options.category,
@@ -137,6 +227,12 @@ export function registerComponent(program) {
}
const answered = summarize(result);
+ if (
+ result.type === 'component.batch' &&
+ result.data.results.some(row => row.status !== 'found')
+ ) {
+ process.exitCode = 1;
+ }
if (json) {
jsonOut(result);
return answered;
@@ -152,7 +248,7 @@ export function registerComponent(program) {
const listFooter = text(
[
`Import from the path shown (e.g. import {Button} from '@astryxdesign/core/Button')`,
- `Usage: ${run} component <name>`,
+ `Usage: ${run} component <name> [name...]`,
].join('\n'),
);
@@ -231,64 +327,65 @@ export function registerComponent(program) {
break;
}
- case 'component.detail': {
- const resolvedName = (name || '').replace(/^XDS/, '');
- const importHint = result.data.import;
- if (result.data.parentDoc) emit(record(result.data, {fields: ['parentDoc']}));
- const doc =
- detail === 'brief'
- ? code(formatBrief(result.data, resolvedName, importHint, {themeData}))
- : detail === 'compact'
- ? code(formatCompact(result.data, resolvedName, importHint))
- : code(formatFull(result.data, {themeData, importHint}));
- emit(doc);
- break;
- }
-
- case 'component.detail.props': {
- const resolvedName = (name || '').replace(/^XDS/, '');
- emit(code(formatProps({props: result.data}, resolvedName)));
- break;
- }
-
- case 'component.detail.source': {
- emit(code(result.data.source));
- break;
- }
-
- case 'component.detail.showcase': {
- emit(code(result.data.source));
- break;
- }
-
- case 'component.detail.blocks': {
- const {showcase, examples, related} = result.data;
+ case 'component.batch': {
/** @type {import('../../formatters/index.mjs').Block[]} */
- const out = [];
- if (showcase) {
- out.push(
- section('Showcase'),
- record(showcase, {fields: ['displayName', 'description']}),
- );
- }
- if (examples.length > 0) {
- out.push(
- section('Examples'),
- records(examples, {fields: ['name', 'description']}),
- );
- }
- if (related.length > 0) {
+ const out = [
+ section('Component batch'),
+ record({count: result.data.count}),
+ section('Results'),
+ ];
+ for (const row of result.data.results) {
+ out.push(section(row.selector));
+ if (row.status === 'found') {
+ out.push(
+ record(row, {fields: ['selector', 'status']}),
+ section('Result'),
+ ...componentDetailBlocks(
+ row.result,
+ row.selector,
+ detail,
+ themeData,
+ ),
+ );
+ continue;
+ }
out.push(
- section(`Related: ${related.length} blocks that use ${result.data.component}`),
- list(related.map(b => b.name)),
+ record(row, {
+ fields: ['selector', 'status', 'code', 'error'],
+ }),
);
- }
- if (!showcase && examples.length === 0 && related.length === 0) {
- out.push(text(`No blocks found for ${result.data.component}`));
+ if (row.status === 'ambiguous') {
+ out.push(
+ section('Candidates'),
+ records(row.candidates, {
+ fields: ['package', 'component', 'kind', 'installed'],
+ }),
+ );
+ } else if (row.suggestions?.length) {
+ out.push(
+ section('Suggestions'),
+ records(row.suggestions, {fields: ['name', 'reason']}),
+ );
+ }
}
emit(...out);
break;
}
+
+ case 'component.detail':
+ case 'component.detail.props':
+ case 'component.detail.source':
+ case 'component.detail.showcase':
+ case 'component.detail.blocks':
+ emit(
+ ...componentDetailBlocks(
+ result,
+ name ?? '',
+ detail,
+ themeData,
+ ),
+ );
+ break;
}
return answered;
},
diff --git a/packages/cli/clients/cli/commands/docs.test.mjs b/packages/cli/clients/cli/commands/docs.test.mjs
index 05133acc43..f350598bbd 100644
--- a/packages/cli/clients/cli/commands/docs.test.mjs
+++ b/packages/cli/clients/cli/commands/docs.test.mjs
@@ -216,6 +216,34 @@ describe('the docs tree, one level at a time', () => {
expect(JSON.parse(both.stdout).code).toBe('ERR_INVALID_ARGUMENT');
}, SLOW);
+ it('reads the component lookup guide and its output/API examples', async () => {
+ const index = await runCli([
+ 'docs',
+ 'cli/component-lookups',
+ '--index',
+ ]);
+ expect(index.status).toBe(0);
+ expect(index.stdout).toContain('several');
+ expect(index.stdout).toContain('selectors');
+ expect(index.stdout).toContain('output');
+ expect(index.stdout).toContain('api');
+
+ const output = await runCli([
+ 'docs',
+ 'cli/component-lookups',
+ 'output',
+ ]);
+ expect(output.status).toBe(0);
+ expect(output.stdout).toContain('component.batch');
+ expect(output.stdout).toContain('ERR_UNKNOWN_COMPONENT');
+ expect(output.stdout).toContain('exits 1');
+
+ const api = await runCli(['docs', 'cli/component-lookups', 'api']);
+ expect(api.status).toBe(0);
+ expect(api.stdout).toContain('component([])');
+ expect(api.stdout).toContain("component(['Button'])");
+ }, SLOW);
+
it('reads the integration guide by its route, and not by its old name', async () => {
const guide = await runCli(['docs', 'cli/integrations', '--index']);
expect(guide.status).toBe(0);
@@ -252,6 +280,7 @@ describe('the docs tree, one level at a time', () => {
const error = JSON.parse(section.stdout);
expect(error).toMatchObject({code: 'ERR_UNKNOWN_SECTION'});
expect(error.suggestions.map(s => s.name)).toEqual([
+ 'cli/component-lookups',
'cli/integrations',
'cli/writing-docs',
'cli/commands',
diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjs
index 3ee37c17c5..4c8649d89b 100644
--- a/packages/cli/clients/cli/lib/manifest.mjs
+++ b/packages/cli/clients/cli/lib/manifest.mjs
@@ -51,6 +51,7 @@ export const RESPONSE_TYPES = {
init: ['init.run', 'init.remove'],
component: [
'component.list',
+ 'component.batch',
'component.detail',
'component.detail.props',
'component.detail.source',
@@ -112,6 +113,7 @@ const EXAMPLES = {
component: [
'astryx component',
'astryx component XDSButton',
+ 'astryx component Button Badge Text',
'astryx component XDSButton --props --json',
],
docs: [
diff --git a/packages/cli/clients/cli/lib/manifest.test.mjs b/packages/cli/clients/cli/lib/manifest.test.mjs
index 42fbc50451..4be526bab0 100644
--- a/packages/cli/clients/cli/lib/manifest.test.mjs
+++ b/packages/cli/clients/cli/lib/manifest.test.mjs
@@ -156,7 +156,10 @@ describe('manifest: shape', () => {
it('derives arguments from Commander metadata', () => {
const component = allEntries.find((c) => c.name === 'component');
- expect(component.arguments.map((a) => a.name)).toContain('name');
+ const names = component.arguments.find((a) => a.name === 'names');
+ expect(names.required).toBe(false);
+ expect(names.variadic).toBe(true);
+ expect(names.description).toContain('Two or more return one ordered batch');
const themeBuild = allEntries.find((c) => c.name === 'theme build');
expect(themeBuild.arguments.map((a) => a.name)).toContain('files');
const files = themeBuild.arguments.find((a) => a.name === 'files');
@@ -193,7 +196,7 @@ describe('manifest: e2e', () => {
// Enriched: the full structured manifest is embedded.
expect(parsed.data.manifest).toBeDefined();
expect(parsed.data.manifest.commands.find((c) => c.name === 'component').responseTypes)
- .toContain('component.list');
+ .toEqual(expect.arrayContaining(['component.list', 'component.batch']));
});
});
diff --git a/packages/cli/foundation/doc-compiler/tree.test.mjs b/packages/cli/foundation/doc-compiler/tree.test.mjs
index e2bb130df2..64e0bfe2df 100644
--- a/packages/cli/foundation/doc-compiler/tree.test.mjs
+++ b/packages/cli/foundation/doc-compiler/tree.test.mjs
@@ -497,7 +497,14 @@ describe("the CLI's own docs tree", () => {
expect(
tree.get('cli')?.slots.map(slot => [slot.name, slot.children]),
).toEqual([
- ['guides', ['cli/integrations', 'cli/writing-docs']],
+ [
+ 'guides',
+ [
+ 'cli/component-lookups',
+ 'cli/integrations',
+ 'cli/writing-docs',
+ ],
+ ],
['reference', ['cli/commands', 'cli/api']],
]);
expect(tree.get('cli/api')?.slots[0].children).toEqual([
@@ -566,6 +573,7 @@ describe("the CLI's own docs tree", () => {
'commands',
]);
expect(inputs.docs.map(d => [d.name, d.placement?.parent])).toEqual([
+ ['component-lookups', 'namespace:cli'],
['integrations', 'namespace:cli'],
['writing-docs', 'namespace:cli'],
]);
diff --git a/packages/cli/foundation/response/batch.type.mjs b/packages/cli/foundation/response/batch.type.mjs
new file mode 100644
index 0000000000..27e93fec00
--- /dev/null
+++ b/packages/cli/foundation/response/batch.type.mjs
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Shared published types for complete multi-selector lookup receipts.
+ * Adopting API subjects specialize these types with their single-result and
+ * ambiguity-candidate types instead of defining command-specific row shapes.
+ *
+ * @input One exact selector, its single-result response, and its candidate shape.
+ * @output BatchRow and BatchResponse for every AST-053 lookup adopter.
+ * @position packages/cli/foundation/response — shared JSON response types
+ */
+
+/**
+ * One complete row for an accepted selector.
+ * @template TResult
+ * @template TCandidate
+ * @typedef {(
+ * | {selector: string; status: 'found'; result: TResult}
+ * | {selector: string; status: 'ambiguous'; code: string; error: string; candidates: TCandidate[]}
+ * | {selector: string; status: 'not_found' | 'error'; code: string; error: string; suggestions?: import('./base').Suggestion[]}
+ * )} BatchRow
+ */
+
+/**
+ * One ordered batch receipt inside the shared `{type, data}` success envelope.
+ * @template {string} TType
+ * @template TResult
+ * @template TCandidate
+ * @typedef {object} BatchResponse
+ * @property {TType} type
+ * @property {{count: number; results: BatchRow<TResult, TCandidate>[]}} data
+ */
+
+export {};
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 16b94d7bc7..dc32137f60 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -37,6 +37,11 @@ export const doc = {
description:
'The component catalog grouped by category: `detail` (the level: names | compact | full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries, or a full ComponentDoc per entry.',
},
+ {
+ value: 'component.batch',
+ description:
+ 'The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found | not_found | ambiguous | error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}).',
+ },
{
value: 'component.detail',
description:
diff --git a/packages/cli/foundation/response/response-types.doc.test.mjs b/packages/cli/foundation/response/response-types.doc.test.mjs
index c5cf1953fe..e9abd92f97 100644
--- a/packages/cli/foundation/response/response-types.doc.test.mjs
+++ b/packages/cli/foundation/response/response-types.doc.test.mjs
@@ -53,6 +53,29 @@ function expectNamed(type, fields) {
}
describe('response-types EnumDoc names every field', () => {
+ it('component.batch names every row field and state', async () => {
+ const res = await data(['component', 'Button', 'Badge']);
+ expect(res.type).toBe('component.batch');
+ expect(describedAs('component.batch')).toMatch(/BatchResponse.*BatchRow/);
+ expectNamed('component.batch', [
+ 'count',
+ 'results',
+ 'selector',
+ 'status',
+ 'result',
+ 'code',
+ 'error',
+ 'candidates',
+ 'package',
+ 'component',
+ 'kind',
+ 'installed',
+ 'suggestions',
+ 'name',
+ 'reason',
+ ]);
+ });
+
it('component.detail: the ownership fields and parentDoc', async () => {
const res = await data(['component', 'HStack']);
expect(res.type).toBe('component.detail');
diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.json
index f455e2ea76..c9d54e7876 100644
--- a/packages/cli/test/doc-routes.json
+++ b/packages/cli/test/doc-routes.json
@@ -394,6 +394,61 @@
"rationale": "Stays a section of browser-support under the same key.",
"status": "proposed"
},
+ {
+ "kind": "topic",
+ "id": "cli/component-lookups",
+ "oldCliRoute": "astryx docs cli/component-lookups",
+ "oldDocsiteUrl": "/docs/cli-component-lookups",
+ "placement": "namespace:cli/component-lookups",
+ "aliasNeeded": false,
+ "evidence": "It places itself: placement {parent: 'namespace:cli', slot: 'guides'}. Its four sections document the component command's exact selectors, batch receipt, exit status and programmatic API.",
+ "rationale": "Caller guide for exact single and batch component lookup. This is a new route, so no previous CLI or docsite identity needs an alias.",
+ "status": "proposed"
+ },
+ {
+ "kind": "section",
+ "id": "cli/component-lookups#several",
+ "oldCliRoute": "astryx docs cli/component-lookups several",
+ "oldDocsiteUrl": "/docs/cli-component-lookups#look-up-several-components",
+ "placement": "namespace:cli/component-lookups",
+ "aliasNeeded": false,
+ "evidence": "Moves with cli/component-lookups.",
+ "rationale": "Stays a section of cli/component-lookups under the stable key several.",
+ "status": "proposed"
+ },
+ {
+ "kind": "section",
+ "id": "cli/component-lookups#selectors",
+ "oldCliRoute": "astryx docs cli/component-lookups selectors",
+ "oldDocsiteUrl": "/docs/cli-component-lookups#selector-forms",
+ "placement": "namespace:cli/component-lookups",
+ "aliasNeeded": false,
+ "evidence": "Moves with cli/component-lookups.",
+ "rationale": "Stays a section of cli/component-lookups under the stable key selectors.",
+ "status": "proposed"
+ },
+ {
+ "kind": "section",
+ "id": "cli/component-lookups#output",
+ "oldCliRoute": "astryx docs cli/component-lookups output",
+ "oldDocsiteUrl": "/docs/cli-component-lookups#batch-output-and-exit-status",
+ "placement": "namespace:cli/component-lookups",
+ "aliasNeeded": false,
+ "evidence": "Moves with cli/component-lookups.",
+ "rationale": "Stays a section of cli/component-lookups under the stable key output.",
+ "status": "proposed"
+ },
+ {
+ "kind": "section",
+ "id": "cli/component-lookups#api",
+ "oldCliRoute": "astryx docs cli/component-lookups api",
+ "oldDocsiteUrl": "/docs/cli-component-lookups#programmatic-api",
+ "placement": "namespace:cli/component-lookups",
+ "aliasNeeded": false,
+ "evidence": "Moves with cli/component-lookups.",
+ "rationale": "Stays a section of cli/component-lookups under the stable key api.",
+ "status": "proposed"
+ },
{
"kind": "topic",
"id": "cli/integrations",