Skip to content

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

TypeScript

feat(cli): astryx discover browses the integrations you have and could add (#6802)

Joey9c4d44d88a32
diff --git a/.changeset/discover-integration-manager.md b/.changeset/discover-integration-manager.md
new file mode 100644
index 0000000000..69a586868a
--- /dev/null
+++ b/.changeset/discover-integration-manager.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx discover` browses integrations: the ones a project has and, through discover sources, the ones it could add, with every version and what each one adds. It searches every kind of item and filters with `--type`, `--installed`, `--available`, and `--limit`. A project sets a source as `discover` in `astryx.config`, and an integration exports one as a `discover` named export. Discover only reads: it prints the command that adds a package and never runs it. Existing `--json` fields keep their meaning. A free-text query now always lists its matches, even an exact component name, and `astryx discover <package>/<Name>` opens one.
+
+@josephfarina
diff --git a/docs/specs/AST-051-discover-integration-manager/spec.md b/docs/specs/AST-051-discover-integration-manager/spec.md
new file mode 100644
index 0000000000..d19fe04a7c
--- /dev/null
+++ b/docs/specs/AST-051-discover-integration-manager/spec.md
@@ -0,0 +1,226 @@
+---
+schema_version: 4
+template_version: 1
+kind: system-spec
+id: spec:AST-051
+authority: current
+archive_reason: null
+superseded_by: null
+approved_by: josephfarina
+approved_at: 2026-09-30
+phase: accepted
+owners: [josephfarina]
+affects_architecture: [architecture:cli-surface]
+affects_families: []
+affects_contributing: []
+affects_consumer_docs: [cli/integrations]
+---
+
+# Discover integration manager system spec
+
+## Intent
+
+A person or agent building an Astryx app wants to know which integrations
+exist, what each one adds, which ones the app already has, and which versions
+are published, without leaving the terminal. `astryx discover` answers that. It
+is the read-only manager for integrations: it lists what the project has and
+what its sources offer, shows each package's versions and what they add, and
+searches and filters all of it. The project's package manager installs,
+updates, and removes packages.
+
+This record owns what discover shows, where the list of available integrations
+comes from, and what happens when a source cannot be reached. `spec:AST-031`
+owns how named-export features compose; discover sources follow it except where
+this record says otherwise.
+
+## Non-goals
+
+- Installing, updating, or removing packages. The package manager does that,
+ and autolink loads a newly installed integration with no discover step.
+- Hosting a catalog, or choosing a built-in public source (OQ1).
+- How a source signs in. A source runs as the person running the CLI and uses
+ whatever credentials its host already has. The CLI never prompts
+ (`architecture:cli-surface` INV1) and reads no Astryx-owned environment
+ variable for a source (`spec:AST-017` FR14).
+- `astryx search`, which stays on installed content.
+- Equivalent internal implementations remain valid when they satisfy this
+ contract.
+
+## Requirements
+
+- **FR1 — The list shows what the project has and what it could add.** With no
+ query, discover MUST list every integration the project loads, configured or
+ autolinked, with its version, what it adds as one list per kind, and the
+ latest release a source knows. It MUST then list, once per integration, every
+ package its sources offer that the project neither loads nor declares as a
+ dependency, and MUST NOT offer a package whose integration the project has
+ under another name. An integration that failed to load is left out; the
+ integration-issues warning and Doctor report it.
+- **FR2 — A package page shows its versions and what they add.** `discover
+<package>` MUST show what the shown version adds, grouped by kind, whether
+ the project has the package, its latest release, and its releases newest
+ first with their dates and any unreadable status, and MUST count its
+ prereleases. `discover <package>@<version>` shows any version, prerelease
+ included; the default is the installed version, else the latest release. A
+ version no source lists MUST fail with `ERR_NOT_FOUND` and suggest releases.
+ For a package the project does not have, discover MUST print the
+ package-manager command that adds it, as text, and MUST NOT run it; for an
+ alias of a package the project has, it names that package instead.
+- **FR3 — An item page shows one item.** `discover <package>/<Component>` for an
+ installed component keeps printing its doc. Any other item a package adds,
+ installed or listed by a source, MUST resolve to its kind, name, package,
+ version, and whether the project has it.
+- **FR4 — Search covers every kind and every source.** `discover <words>` MUST
+ match installed components, the project's other installed items, package
+ names and descriptions, and every item a source lists for a package the
+ project could add, by name, title, summary, and keywords. It MUST answer with
+ the list of matches, even when one name matches exactly or only one item
+ matches, so the response type depends on the form of the query and never on
+ what the project has. Matches are ranked by how closely the name matches,
+ with installed items first among equals. Each match states its kind and
+ whether the project has its package. One item opens by its package path
+ (FR3).
+- **FR5 — Filters follow the CLI's existing options.** `--type <kind>` keeps one
+ kind (`component`, `template`, `doc`, `theme`, `codemod`, `agent-doc`): in the
+ list, packages that add it; in a search, items of that kind. `--installed`
+ and `--available` keep one side and MUST be refused together with
+ `ERR_INVALID_OPTION`. `--limit <n>` caps search results (default 20) and the
+ response reports the total when it cut the list. An unknown kind or a limit
+ that is not a positive integer MUST fail with `ERR_INVALID_OPTION`.
+- **FR6 — Sources are functions a project or integration provides.** A source is
+ an async function that receives `{signal, package?, version?}` and resolves
+ to a catalog; `package` asks for one package with every version, and
+ `version` asks for that version's items. A project MAY set one as the
+ `discover` field of `astryx.config`, and each loaded integration MAY export
+ one as its `discover` named export. Every source is called, the project's
+ first and then each integration's in load order, and the same function runs
+ once. A source that throws, exceeds 30 seconds (signalled on `signal`), or
+ returns an invalid catalog fails alone: the others still count, and discover
+ reports which source failed and why. Sources only read, so `spec:AST-031`'s
+ consent gate does not apply to them.
+- **FR7 — The catalog shape is versioned.** A catalog is `{schemaVersion: 1,
+source, packages}`. `source` has `name`, `generatedAt`, and `complete`. Each
+ package has `package`, `integration` (shared by every package name that
+ publishes the same integration), `aliases`, an optional `description`,
+ `latest`, `versions` (each with `version`, `publishedAt`, `prerelease`, and
+ `status`), and the `contributions` of the requested or latest version (each
+ with `kind`, `name`, and optional `title`, `summary`, and `keywords`). The CLI
+ MUST validate every answer, MUST ignore fields and kinds it does not know,
+ MUST refuse any other `schemaVersion`, and MUST show versions newest first by
+ publish time whatever order the source returned them in. When two sources
+ list the same package, the earlier source's entry is used.
+- **FR8 — A saved copy covers an unreachable source.** After a source answers,
+ discover MUST save that answer, per source and per request, in the per-user
+ cache directory of the platform, never in the project. When the source later
+ fails, discover MUST use the saved answer for the same request and say when
+ it was saved. With no saved answer, the source adds nothing and discover says
+ so. Installed integrations always appear, with or without a source.
+- **FR9 — JSON stays compatible.** Existing response types and fields keep their
+ meaning; new information is additive. `discover.list` `data` lists installed
+ integrations, now every loaded one, with optional per-kind lists and
+ `latest`; `meta.available` lists what the project could add and
+ `meta.sources` reports each source. `discover.detail` gains `installed` and,
+ with a source, `latest`, `aliases`, `source`, `versions`, and `install` or
+ `installedAs`. Items other than installed components use the new
+ `discover.item` type. `discover.search` matches gain `kind` and `installed`,
+ `component` holds the item name for every kind, and `data.total` appears when
+ `--limit` cut the list. A free-text query that used to return
+ `discover.detail.doc` now returns `discover.search` (FR4).
+
+### Platform support
+
+- Supported feature/engine floor: every supported CLI runtime.
+- Unsupported behavior: none. What a source needs from its machine is its
+ author's responsibility; a source that cannot run there fails under FR6.
+- Browser evidence: not applicable.
+
+## Current-state impact
+
+- `astryx discover` listed only configured integrations with a components root
+ and matched component names only; its `description` and `displayName` fields
+ were never filled. This record replaces that behavior additively (FR9).
+- `discover <Name>` opened an installed component's doc when the name matched
+ exactly or was the only match. It now lists the matches, and
+ `discover <package>/<Name>` opens the doc (FR4, DEC-4).
+- `architecture:cli-surface`: the discover adapter calls sources and keeps the
+ saved copy (INV21); the saved copy's path passes `assertWithin` under the
+ cache directory (INV10).
+- `spec:AST-031`: `discover` is a second named-export feature, without the
+ consent gate (FR6).
+- Consumer docs: `cli/integrations` gains the `discover` named export and config
+ field, and `astryx docs authoring` gains the `discover-source` section.
+
+## Verification
+
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| -------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
+| FR1 | list leaf, catalog view, command tests | installed only; available only; both; latest known; alias of an installed package; declared dependency | an available package is missing, an alias or declared package is offered, or latest is absent |
+| FR2 | detail leaf and command tests | installed; not installed; `@version`; prerelease; unpublished version; alias | a version is dropped, the default is wrong, the add command runs, or an alias is offered |
+| FR3 | item leaf and dispatcher tests | installed component; installed template; listed item; unknown item | an installed component loses its doc, or a listed item is not found |
+| FR4 | search leaf and command tests | components, templates, docs, packages; installed and available; title and summary matches; an exact installed name; a single match | a kind is not searched, installed state is wrong, a weak match ranks first, or a free-text query returns a doc instead of the list |
+| FR5 | dispatcher, leaf, and command tests | each kind; `--installed`; `--available`; both; `--limit`; bad values | a filter is ignored, the pair is accepted, or a bad value passes |
+| FR6 | adapter source tests | project and two integrations; a shared function; a throw; a timeout; invalid data | a failure hides other sources, a function runs twice, order changes, or the signal never aborts |
+| FR7 | catalog schema tests | unknown field; unknown kind; `schemaVersion: 2`; duplicate package across sources; misordered versions | an unknown field fails, another version is accepted, the later source wins, or versions keep the source order |
+| FR8 | adapter saved-copy and command tests | fresh answer; failure with a saved copy; failure with none; another request | a stale copy hides a fresh answer, the saved date is missing, or a project file is written |
+| FR9 | existing discover JSON tests | each response type with and without a source | an existing field changes type or meaning |
+
+## Decision log
+
+### DEC-1 — Discover shows; the package manager installs
+
+**Reference:** `spec:AST-051/DEC-1`
+**Decider:** `josephfarina`, `2026-09-30`
+
+Installing is the package manager's job, and autolink already loads a newly
+installed integration, so discover only reads. For a package the project does
+not have, it prints the command that adds it.
+
+Rejected: `discover add`, `update`, and `remove` subcommands; running the
+package manager from discover.
+
+### DEC-2 — Available integrations come from sources, not from the CLI
+
+**Reference:** `spec:AST-051/DEC-2`
+**Decider:** `josephfarina`, `2026-09-30`
+
+A project or an integration provides a source as a function, and discover
+merges every source. A catalog host that needs sign-in works through the
+function, which runs with the credentials its host already has, and a project
+can add or replace what it reads without a CLI release.
+
+Rejected: a catalog URL built into the CLI, which ties the public CLI to one
+host; a source given as a URL for the CLI to fetch, which cannot sign in to a
+private host without the CLI handling credentials.
+
+### DEC-3 — Discover has its own search and filters, in the CLI's existing terms
+
+**Reference:** `spec:AST-051/DEC-3`
+**Decider:** `josephfarina`, `2026-09-30`
+
+Discover lists, shows one package, version, or item, and searches with filters,
+using the option names the CLI already has (`--type`, `--limit`) plus
+`--installed` and `--available`. Its responses follow the existing discover
+types, so a reader of `--json` learns nothing new to use it.
+
+Rejected: sending discover's searches through `astryx search`, which answers
+about installed content only.
+
+### DEC-4 — A free-text query always answers with a list
+
+**Reference:** `spec:AST-051/DEC-4`
+**Decider:** `josephfarina`, `2026-09-30`
+
+`discover <words>` is a search, so it lists every match across all packages,
+the ones the project has and the ones it could add, even when a component's
+name matches exactly or only one item matches. The response type then depends
+only on the form of the query. One item opens by its package path.
+
+Rejected: keeping the earlier shortcut, where an exact or only
+installed-component match opened that component's doc. The same query then
+returned a doc or a list depending on what the project and its sources held.
+
+## Open questions
+
+- **OQ1 — A built-in public source** (`human-design`). Whether discover ships a
+ built-in source for a public catalog, and whether a project source adds to it
+ or replaces it. Until this is decided, discover has no built-in source.
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 94e4dd3a83..9c8ae402d3 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -82,7 +82,7 @@ Options:
| `blog` | Read the Astryx blog from the published feed |
| `build` | Build a page: the template to start from, or the workflow playbook (no query) |
| `component` | List components or print component docs |
-| `discover` | Discover external packages and components |
+| `discover` | Browse and search integrations: the ones you have and the ones you could add |
| `docs` | Print reference docs |
| `doctor` | Diagnose Astryx projects and integration packages |
| `gap-report` | Route a design-system gap to its owning package |
@@ -435,10 +435,11 @@ Every response has a `type` discriminant. The full set is below (generated from
| `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 configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |
-| `discover.detail` | A single external package entry, for an @scope/name query. |
-| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |
-| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |
+| `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. |
diff --git a/packages/cli/api/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjs
index b8be0a0933..e1c830e917 100644
--- a/packages/cli/api/discover/_adapter.mjs
+++ b/packages/cli/api/discover/_adapter.mjs
@@ -1,31 +1,81 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Shared external-package adapter for the discover leaves.
+ * @file Shared adapter for the discover leaves: the one place discover reaches
+ * the environment.
*
* Every `discover.*` leaf projects already-resolved data into a typed response;
- * none of them touch the integration system or the filesystem directly. This
- * adapter is the single place that does: it discovers the configured external
- * packages, locates a component's doc file within them, and loads + validates a
- * component's docs. Keeping that I/O here (rather than duplicated across leaves)
- * is what lets `list`, `detail`, `detail/doc`, and `search` stay pure
- * projections.
+ * none of them touch the integration system, the filesystem, or a source. This
+ * adapter does: it resolves the project's installed integrations and what each
+ * one adds, calls every discover source and keeps a saved copy of each answer,
+ * locates and loads a component's doc, and names the package manager's add
+ * command. Keeping that I/O here (INV21) is what lets `list`, `detail`,
+ * `detail/doc`, `detail/item`, and `search` stay pure projections.
*
- * @position api/discover — orchestration over lib/project, lib/package-scanner,
- * and lib/component-loader; the discover dispatcher + leaves consume it.
+ * @position api/discover — orchestration over foundation/config/project,
+ * foundation/integrations, the discovery loaders, and discover sources.
*/
+import {createHash} from 'node:crypto';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
import {Project} from '../../foundation/config/project.mjs';
import {
scanAllPackages,
findComponentInPackages,
} from './_package-scanner.mjs';
import {loadDocs} from '../../foundation/discovery/component-loader.mjs';
+import {collectIdentities} from '../../foundation/integrations/contribution-inventory.mjs';
+import {detectPackageManager} from '../../foundation/env/package-manager.mjs';
+import {assertWithin} from '../../foundation/fs/path-safety.mjs';
+import {parseDiscoverCatalog} from '../../authoring/discover/parse.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
+const SOURCE_TIMEOUT_MS = 30_000;
+
+const DEPENDENCY_FIELDS = [
+ 'dependencies',
+ 'devDependencies',
+ 'optionalDependencies',
+ 'peerDependencies',
+];
+
/**
* @typedef {import('./_package-scanner.mjs').ScannedPackage} ScannedPackage
+ * @typedef {import('../../authoring/discover/type').DiscoverPackage} DiscoverPackage
+ * @typedef {import('../../authoring/discover/type').DiscoverSource} DiscoverSource
+ */
+
+/**
+ * An installed integration with what it adds, per kind. `components` is the
+ * scanned component list the discover leaves have always used.
+ * @typedef {ScannedPackage & {
+ * templates?: string[],
+ * docs?: string[],
+ * themes?: string[],
+ * codemods?: string[],
+ * }} InstalledPackage
+ */
+
+/**
+ * What one source did on this run.
+ * @typedef {object} SourceState
+ * @property {string} name the source's own name, or where it came from when it
+ * gave none
+ * @property {string} from `astryx.config`, or the integration that exports it
+ * @property {'fresh' | 'saved' | 'failed'} status
+ * @property {string} [generatedAt]
+ * @property {boolean} [complete]
+ * @property {string} [savedAt] when the saved copy in use was written
+ * @property {string} [error] why the live call failed
+ */
+
+/**
+ * Everything every source returned, merged. When two sources list the same
+ * package, the earlier source's entry is kept.
+ * @typedef {{sources: SourceState[], packages: Array<DiscoverPackage & {source: string}>}} CatalogResult
*/
/**
@@ -68,7 +118,7 @@ function validateDocs(docs) {
* configured" (`false`) from "configured but nothing discovered" (`true`),
* which the list leaf surfaces as `meta`.
*
- * @returns {Promise<{packages: ScannedPackage[], configured: boolean}>}
+ * @returns {Promise<{packages: ScannedPackage[], configured: boolean, project: Project}>}
*/
export async function discoverPackages() {
const project = await Project.load();
@@ -86,25 +136,323 @@ export async function discoverPackages() {
docsDir: integration.components,
}));
if (explicitPackages.length === 0) {
- return {packages: [], configured: loadedIntegrations.length > 0};
+ return {packages: [], configured: loadedIntegrations.length > 0, project};
}
const packages = scanAllPackages(
[],
/** @type {ScannedPackage[]} */ (/** @type {unknown} */ (explicitPackages)),
);
- return {packages, configured: true};
+ return {packages, configured: true, project};
+}
+
+/**
+ * Every integration the project loads, with what it adds. An integration with
+ * no components root is included with `components: []`; one that failed to
+ * load is left out (the integration-issues nudge and Doctor report it).
+ *
+ * @param {Project | undefined} project
+ * @param {ScannedPackage[]} scanned the packages {@link discoverPackages} found
+ * @returns {Promise<InstalledPackage[]>}
+ */
+export async function describeInstalled(project, scanned) {
+ if (project == null) return scanned;
+ const byName = new Map(scanned.map(pkg => [pkg.name, pkg]));
+ /** @type {InstalledPackage[]} */
+ const installed = [];
+ for (const integration of project.loadedIntegrations) {
+ if (integration.__loadError) continue;
+ const base =
+ byName.get(integration.name) ??
+ /** @type {ScannedPackage} */ (
+ /** @type {unknown} */ ({
+ name: integration.name,
+ category: integration.name,
+ version: integration.version,
+ components: [],
+ })
+ );
+ // Components come from the scan above; loading every component doc again
+ // here would only slow the list down.
+ const {identities} = await collectIdentities({
+ ...integration,
+ components: undefined,
+ });
+ installed.push({
+ ...base,
+ templates: identities.templates.map(t => t.id),
+ docs: identities.docs,
+ themes: identities.themes.map(t => t.slug),
+ codemods: identities.codemods.map(c => `${c.version}/${c.id}`),
+ });
+ }
+ return installed;
}
/**
- * Project a scanned package into the discover list/detail entry shape. Shared
- * by the list and detail leaves so the entry keys (and their order) stay in one
- * place.
- * @param {ScannedPackage} pkg
+ * Whether the project has any discover source: its own `discover` config field,
+ * or an integration's `discover` named export (valid or not).
+ * @param {Project | undefined} project
+ * @returns {boolean}
+ */
+export function hasSources(project) {
+ if (project == null) return false;
+ if (typeof project.config?.discover === 'function') return true;
+ return project.loadedIntegrations.some(
+ i => i.__discover != null || i.__discoverError != null,
+ );
+}
+
+/**
+ * Package names the project's package.json declares in any dependency field.
+ * @param {Project | undefined} project
+ * @returns {Set<string>}
+ */
+export function declaredDependencies(project) {
+ /** @type {Set<string>} */
+ const names = new Set();
+ if (project == null) return names;
+ try {
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(project.cwd, 'package.json'), 'utf8'),
+ );
+ for (const field of DEPENDENCY_FIELDS) {
+ for (const name of Object.keys(pkg?.[field] ?? {})) names.add(name);
+ }
+ } catch {
+ // No readable package.json: nothing is declared.
+ }
+ return names;
+}
+
+/**
+ * The command that adds a package with the project's package manager. Discover
+ * only prints it; it never runs it.
+ * @param {Project | undefined} project
+ * @returns {(name: string, version?: string) => string}
+ */
+export function addCommand(project) {
+ const pm = detectPackageManager(project?.cwd ?? process.cwd());
+ const verb =
+ pm === 'pnpm'
+ ? 'pnpm add'
+ : pm === 'yarn'
+ ? 'yarn add'
+ : pm === 'bun'
+ ? 'bun add'
+ : 'npm install';
+ return (name, version) => `${verb} ${version ? `${name}@${version}` : name}`;
+}
+
+/**
+ * The per-user cache directory the saved copies live in, never inside a
+ * project. Standard platform locations only.
+ * @returns {string}
+ */
+export function defaultCacheDir() {
+ const home = os.homedir();
+ if (process.platform === 'win32') {
+ return path.join(
+ process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'),
+ 'astryx',
+ 'Cache',
+ );
+ }
+ if (process.platform === 'darwin') {
+ return path.join(home, 'Library', 'Caches', 'astryx');
+ }
+ return path.join(
+ process.env.XDG_CACHE_HOME || path.join(home, '.cache'),
+ 'astryx',
+ );
+}
+
+/**
+ * @param {string} cacheDir
+ * @param {string} from
+ * @param {{package?: string, version?: string}} request
+ */
+function savedCopyPath(cacheDir, from, request) {
+ const key = createHash('sha256')
+ .update(`${from}\n${request.package ?? ''}\n${request.version ?? ''}`)
+ .digest('hex')
+ .slice(0, 32);
+ const dir = path.join(cacheDir, 'discover');
+ return assertWithin(`${key}.json`, dir, {label: 'discover saved copy'});
+}
+
+/**
+ * @param {string} file
+ * @param {string} label
+ */
+function readSavedCopy(file, label) {
+ try {
+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
+ return {
+ savedAt: String(saved.savedAt),
+ catalog: parseDiscoverCatalog(saved.catalog, label),
+ };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * @param {string} file
+ * @param {import('../../authoring/discover/type').DiscoverCatalog} catalog
+ */
+function writeSavedCopy(file, catalog) {
+ try {
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ const tmp = `${file}.${process.pid}.tmp`;
+ fs.writeFileSync(
+ tmp,
+ JSON.stringify({savedAt: new Date().toISOString(), catalog}),
+ );
+ fs.renameSync(tmp, file);
+ } catch {
+ // An unwritable cache only costs the offline copy.
+ }
+}
+
+/**
+ * @param {DiscoverSource} source
+ * @param {{package?: string, version?: string}} request
+ * @param {string} label
+ * @param {number} timeoutMs
+ */
+async function callSource(source, request, label, timeoutMs) {
+ const controller = new AbortController();
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
+ let timer;
+ const timedOut = new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ controller.abort();
+ reject(
+ new Error(`${label} did not answer within ${timeoutMs / 1000} seconds`),
+ );
+ }, timeoutMs);
+ });
+ try {
+ const answer = await Promise.race([
+ Promise.resolve().then(() =>
+ source({signal: controller.signal, ...request}),
+ ),
+ timedOut,
+ ]);
+ return parseDiscoverCatalog(answer, label);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * Call every discover source — the project's `discover` first, then each
+ * integration's in load order — once per distinct function. A source that
+ * throws, times out, or returns an invalid catalog falls back to its saved copy;
+ * with none, it is reported and adds nothing. The others always count.
+ *
+ * @param {Project | undefined} project
+ * @param {{package?: string, version?: string}} [request] ask for one package,
+ * and optionally one version's contributions
+ * @param {{cacheDir?: string, timeoutMs?: number}} [options]
+ * @returns {Promise<CatalogResult>}
+ */
+export async function callSources(project, request = {}, options = {}) {
+ const {cacheDir = defaultCacheDir(), timeoutMs = SOURCE_TIMEOUT_MS} = options;
+ /** @type {CatalogResult} */
+ const result = {sources: [], packages: []};
+ if (project == null) return result;
+
+ /** @type {Array<{from: string, source?: DiscoverSource, error?: string}>} */
+ const origins = [];
+ if (typeof project.config?.discover === 'function') {
+ origins.push({from: 'astryx.config', source: project.config.discover});
+ }
+ for (const integration of project.loadedIntegrations) {
+ if (integration.__discoverError) {
+ origins.push({from: integration.name, error: integration.__discoverError});
+ } else if (integration.__discover) {
+ origins.push({from: integration.name, source: integration.__discover});
+ }
+ }
+
+ /** @type {Set<unknown>} */
+ const called = new Set();
+ /** @type {Set<string>} */
+ const seen = new Set();
+ const ask = request.package
+ ? {package: request.package, ...(request.version ? {version: request.version} : {})}
+ : {};
+ for (const {from, source, error} of origins) {
+ if (source == null) {
+ result.sources.push({name: from, from, status: 'failed', error});
+ continue;
+ }
+ if (called.has(source)) continue;
+ called.add(source);
+
+ const label = `the discover source from ${from}`;
+ const file = savedCopyPath(cacheDir, from, ask);
+ /** @type {import('../../authoring/discover/type').DiscoverCatalog} */
+ let catalog;
+ try {
+ catalog = await callSource(source, ask, label, timeoutMs);
+ writeSavedCopy(file, catalog);
+ result.sources.push({
+ name: catalog.source.name,
+ from,
+ status: 'fresh',
+ generatedAt: catalog.source.generatedAt,
+ complete: catalog.source.complete,
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ const saved = readSavedCopy(file, label);
+ if (saved == null) {
+ result.sources.push({name: from, from, status: 'failed', error: message});
+ continue;
+ }
+ catalog = saved.catalog;
+ result.sources.push({
+ name: catalog.source.name,
+ from,
+ status: 'saved',
+ generatedAt: catalog.source.generatedAt,
+ complete: catalog.source.complete,
+ savedAt: saved.savedAt,
+ error: message,
+ });
+ }
+ for (const pkg of catalog.packages) {
+ if (seen.has(pkg.package)) continue;
+ seen.add(pkg.package);
+ result.packages.push({...pkg, source: catalog.source.name});
+ }
+ }
+ return result;
+}
+
+/** The list and detail entry fields for each item kind, in display order. */
+export const KIND_FIELDS = /** @type {const} */ ([
+ ['component', 'components'],
+ ['template', 'templates'],
+ ['doc', 'docs'],
+ ['theme', 'themes'],
+ ['codemod', 'codemods'],
+ ['agent-doc', 'agentDocs'],
+]);
+
+/**
+ * Project a scanned or installed package into the discover list/detail entry
+ * shape. Shared by the list and detail leaves so the entry keys (and their
+ * order) stay in one place. A kind list appears only when it is not empty.
+ * @param {InstalledPackage & {latest?: string}} pkg
* @returns {import('./discover.type.mjs').DiscoverListEntry}
*/
export function toEntry(pkg) {
- return {
+ /** @type {Record<string, unknown>} */
+ const entry = {
name: pkg.name,
category: pkg.category,
components: pkg.components,
@@ -112,6 +460,13 @@ export function toEntry(pkg) {
description: pkg.description,
displayName: pkg.displayName,
};
+ for (const [, field] of KIND_FIELDS) {
+ if (field === 'components') continue;
+ const values = /** @type {Record<string, unknown>} */ (pkg)[field];
+ if (Array.isArray(values) && values.length > 0) entry[field] = values;
+ }
+ if (pkg.latest) entry.latest = pkg.latest;
+ return /** @type {import('./discover.type.mjs').DiscoverListEntry} */ (entry);
}
/**
diff --git a/packages/cli/api/discover/_adapter.test.mjs b/packages/cli/api/discover/_adapter.test.mjs
new file mode 100644
index 0000000000..44f7b0cd05
--- /dev/null
+++ b/packages/cli/api/discover/_adapter.test.mjs
@@ -0,0 +1,215 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for how the discover adapter calls discover sources: order,
+ * failure isolation, timeouts, and the saved copy. Sources are plain functions
+ * on a stand-in project, and the saved copies go to a temp directory.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {callSources} from './_adapter.mjs';
+
+/**
+ * @param {string} name
+ * @param {object[]} packages
+ */
+function catalog(name, packages) {
+ return {
+ schemaVersion: 1,
+ source: {name, generatedAt: '2026-09-30T00:00:00.000Z', complete: true},
+ packages,
+ };
+}
+
+/**
+ * @param {string} name
+ * @param {object} [extra]
+ */
+function pkg(name, extra = {}) {
+ return {
+ package: name,
+ integration: name,
+ aliases: [],
+ latest: '1.0.0',
+ versions: [
+ {version: '1.0.0', publishedAt: null, prerelease: false, status: 'ok'},
+ ],
+ contributions: [],
+ ...extra,
+ };
+}
+
+/**
+ * @param {{config?: object, integrations?: object[]}} parts
+ * @returns {any}
+ */
+function project({config = {}, integrations = []}) {
+ return {config, loadedIntegrations: integrations, cwd: '/virtual/project'};
+}
+
+let cacheDir;
+
+beforeEach(() => {
+ cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), 'discover-cache-'));
+});
+
+afterEach(() => {
+ fs.rmSync(cacheDir, {recursive: true, force: true});
+});
+
+describe('callSources', () => {
+ it('asks the project source first, then each integration in load order, once per function', async () => {
+ /** @type {string[]} */
+ const calls = [];
+ const shared = vi.fn(async () => {
+ calls.push('shared');
+ return catalog('Shared', [pkg('@a/one')]);
+ });
+ const own = vi.fn(async () => {
+ calls.push('own');
+ return catalog('Own', [pkg('@a/one', {latest: '9.9.9'}), pkg('@a/two')]);
+ });
+
+ const result = await callSources(
+ project({
+ config: {discover: own},
+ integrations: [
+ {name: '@x/first', __discover: shared},
+ {name: '@x/second', __discover: shared},
+ ],
+ }),
+ {},
+ {cacheDir},
+ );
+
+ expect(calls).toEqual(['own', 'shared']);
+ expect(result.sources.map(s => [s.name, s.from, s.status])).toEqual([
+ ['Own', 'astryx.config', 'fresh'],
+ ['Shared', '@x/first', 'fresh'],
+ ]);
+ expect(result.packages.map(p => [p.package, p.latest, p.source])).toEqual([
+ ['@a/one', '9.9.9', 'Own'],
+ ['@a/two', '1.0.0', 'Own'],
+ ]);
+ });
+
+ it('passes the package and version it wants, with an abort signal', async () => {
+ const source = vi.fn(async () => catalog('S', []));
+
+ await callSources(
+ project({integrations: [{name: '@x/src', __discover: source}]}),
+ {package: '@a/one', version: '1.0.0'},
+ {cacheDir},
+ );
+
+ expect(source).toHaveBeenCalledWith({
+ signal: expect.any(globalThis.AbortSignal),
+ package: '@a/one',
+ version: '1.0.0',
+ });
+ });
+
+ it('keeps every other source when one throws, returns bad data, or is not a function', async () => {
+ const result = await callSources(
+ project({
+ integrations: [
+ {
+ name: '@x/throws',
+ __discover: async () => {
+ throw new Error('offline');
+ },
+ },
+ {name: '@x/bad', __discover: async () => ({schemaVersion: 2})},
+ {
+ name: '@x/broken',
+ __discoverError: 'named export "discover" must be a function',
+ },
+ {
+ name: '@x/good',
+ __discover: async () => catalog('Good', [pkg('@a/one')]),
+ },
+ ],
+ }),
+ {},
+ {cacheDir},
+ );
+
+ expect(result.sources.map(s => [s.from, s.status])).toEqual([
+ ['@x/throws', 'failed'],
+ ['@x/bad', 'failed'],
+ ['@x/broken', 'failed'],
+ ['@x/good', 'fresh'],
+ ]);
+ expect(result.sources[0].error).toContain('offline');
+ expect(result.sources[1].error).toContain('schemaVersion 2');
+ expect(result.sources[2].error).toContain('must be a function');
+ expect(result.packages.map(p => p.package)).toEqual(['@a/one']);
+ });
+
+ it('gives up on a source after the timeout and aborts its signal', async () => {
+ /** @type {AbortSignal | undefined} */
+ let seen;
+ const slow = ({signal}) => {
+ seen = signal;
+ return new Promise(() => {});
+ };
+
+ const result = await callSources(
+ project({integrations: [{name: '@x/slow', __discover: slow}]}),
+ {},
+ {cacheDir, timeoutMs: 20},
+ );
+
+ expect(result.sources[0]).toMatchObject({
+ status: 'failed',
+ error: expect.stringContaining('did not answer'),
+ });
+ expect(seen?.aborted).toBe(true);
+ });
+
+ it('uses the copy saved for the same request when a source fails, and says when it was saved', async () => {
+ let online = true;
+ const source = async () => {
+ if (!online) throw new Error('offline');
+ return catalog('S', [pkg('@a/one')]);
+ };
+ const p = project({integrations: [{name: '@x/src', __discover: source}]});
+
+ await callSources(p, {}, {cacheDir});
+ online = false;
+ const offline = await callSources(p, {}, {cacheDir});
+
+ expect(offline.sources[0]).toMatchObject({
+ name: 'S',
+ status: 'saved',
+ error: 'offline',
+ savedAt: expect.any(String),
+ });
+ expect(offline.packages.map(x => x.package)).toEqual(['@a/one']);
+
+ const otherRequest = await callSources(p, {package: '@a/one'}, {cacheDir});
+ expect(otherRequest.sources[0].status).toBe('failed');
+ });
+
+ it('keeps the saved copy in the cache directory, not in the project', async () => {
+ await callSources(
+ project({
+ integrations: [
+ {name: '@x/src', __discover: async () => catalog('S', [])},
+ ],
+ }),
+ {},
+ {cacheDir},
+ );
+
+ expect(fs.readdirSync(path.join(cacheDir, 'discover'))).toHaveLength(1);
+ expect(fs.existsSync('/virtual/project')).toBe(false);
+ });
+
+ it('returns nothing when there is no project', async () => {
+ expect(await callSources(undefined)).toEqual({sources: [], packages: []});
+ });
+});
diff --git a/packages/cli/api/discover/_catalog-view.mjs b/packages/cli/api/discover/_catalog-view.mjs
new file mode 100644
index 0000000000..b97f665099
--- /dev/null
+++ b/packages/cli/api/discover/_catalog-view.mjs
@@ -0,0 +1,203 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Pure views over discover sources' catalogs: which catalog packages the
+ * project already has, what it could add, and the items search looks through.
+ * No I/O; the adapter supplies every input.
+ *
+ * @position api/discover — shared by the list, detail, item, and search leaves.
+ */
+
+import {KIND_FIELDS} from './_adapter.mjs';
+
+/**
+ * @typedef {import('./_adapter.mjs').InstalledPackage} InstalledPackage
+ * @typedef {import('./_adapter.mjs').CatalogResult} CatalogResult
+ * @typedef {CatalogResult['packages'][number]} CatalogPackage
+ * @typedef {import('../../authoring/discover/type').DiscoverKind} DiscoverKind
+ */
+
+/**
+ * An item search looks through. `kind: 'package'` is a package itself.
+ * @typedef {object} SearchItem
+ * @property {string} package
+ * @property {DiscoverKind | 'package'} kind
+ * @property {string} name
+ * @property {boolean} installed
+ * @property {string} [title]
+ * @property {string} [summary]
+ * @property {string[]} [keywords]
+ * @property {string} [description]
+ */
+
+/**
+ * Group a version's contributions into the entry fields, one list per kind.
+ * `components` is always present, like on an installed entry.
+ * @param {CatalogPackage['contributions']} contributions
+ * @returns {Record<string, string[]>}
+ */
+export function kindLists(contributions) {
+ /** @type {Record<string, string[]>} */
+ const lists = {components: []};
+ for (const [kind, field] of KIND_FIELDS) {
+ const names = contributions.filter(c => c.kind === kind).map(c => c.name);
+ if (names.length > 0 || field === 'components') lists[field] = names;
+ }
+ return lists;
+}
+
+/**
+ * Whether an entry adds at least one item of `kind`.
+ * @param {Record<string, unknown>} entry
+ * @param {DiscoverKind} kind
+ * @returns {boolean}
+ */
+export function hasKind(entry, kind) {
+ const field = KIND_FIELDS.find(([k]) => k === kind)?.[1];
+ const values = field == null ? undefined : entry[field];
+ return Array.isArray(values) && values.length > 0;
+}
+
+/**
+ * Where a catalog package stands against the project.
+ * @param {CatalogPackage} pkg
+ * @param {Set<string>} installedNames
+ * @param {Set<string>} declared
+ * @returns {{state: 'installed' | 'declared' | 'alias' | 'available', installedAs?: string}}
+ */
+export function catalogState(pkg, installedNames, declared) {
+ if (installedNames.has(pkg.package)) return {state: 'installed'};
+ if (declared.has(pkg.package)) return {state: 'declared'};
+ const installedAs = pkg.aliases.find(
+ name => installedNames.has(name) || declared.has(name),
+ );
+ if (installedAs != null) return {state: 'alias', installedAs};
+ return {state: 'available'};
+}
+
+/**
+ * The version a catalog package shows by default.
+ * @param {CatalogPackage} pkg
+ * @returns {string | undefined}
+ */
+export function defaultVersion(pkg) {
+ return pkg.latest ?? pkg.versions[0]?.version;
+}
+
+/**
+ * Project a catalog package into the entry shape installed packages use.
+ * @param {CatalogPackage} pkg
+ * @param {string | undefined} version
+ */
+export function catalogEntry(pkg, version) {
+ const {components, ...others} = kindLists(pkg.contributions);
+ return {
+ name: pkg.package,
+ category: pkg.package,
+ components,
+ ...(version ? {version} : {}),
+ ...(pkg.description ? {description: pkg.description} : {}),
+ ...others,
+ };
+}
+
+/**
+ * What the project could add: every catalog package it does not have, once per
+ * integration (the first name a source lists), never an alias of one it has.
+ * @param {CatalogResult} catalog
+ * @param {InstalledPackage[]} installed
+ * @param {Set<string>} declared
+ */
+export function availableEntries(catalog, installed, declared) {
+ const installedNames = new Set(installed.map(p => p.name));
+ /** @type {Set<string>} */
+ const integrations = new Set();
+ const entries = [];
+ for (const pkg of catalog.packages) {
+ if (catalogState(pkg, installedNames, declared).state !== 'available')
+ continue;
+ if (integrations.has(pkg.integration)) continue;
+ integrations.add(pkg.integration);
+ const version = defaultVersion(pkg);
+ const {category: _category, ...entry} = catalogEntry(pkg, version);
+ entries.push({
+ ...entry,
+ ...(pkg.aliases.length > 0 ? {aliases: pkg.aliases} : {}),
+ source: pkg.source,
+ });
+ }
+ return entries;
+}
+
+/**
+ * Installed packages with the latest release a source knows for each.
+ * @param {InstalledPackage[]} installed
+ * @param {CatalogResult} catalog
+ * @returns {Array<InstalledPackage & {latest?: string}>}
+ */
+export function withLatest(installed, catalog) {
+ const byName = new Map(catalog.packages.map(p => [p.package, p]));
+ return installed.map(pkg => {
+ const latest = byName.get(pkg.name)?.latest;
+ return latest ? {...pkg, latest} : pkg;
+ });
+}
+
+/**
+ * Everything search looks through besides installed components (which the
+ * search leaf keeps resolving the way it always has): installed packages and
+ * their other items, and every package the project could add with its items.
+ * @param {InstalledPackage[]} installed
+ * @param {CatalogResult} catalog
+ * @param {Set<string>} declared
+ * @returns {SearchItem[]}
+ */
+export function searchItems(installed, catalog, declared) {
+ /** @type {SearchItem[]} */
+ const items = [];
+ for (const pkg of installed) {
+ items.push({
+ package: pkg.name,
+ kind: 'package',
+ name: pkg.name,
+ installed: true,
+ ...(pkg.description ? {description: pkg.description} : {}),
+ });
+ for (const [kind, field] of KIND_FIELDS) {
+ if (kind === 'component') continue;
+ const names = /** @type {Record<string, unknown>} */ (pkg)[field];
+ if (!Array.isArray(names)) continue;
+ for (const name of names) {
+ items.push({package: pkg.name, kind, name, installed: true});
+ }
+ }
+ }
+ const installedNames = new Set(installed.map(p => p.name));
+ /** @type {Set<string>} */
+ const integrations = new Set();
+ for (const pkg of catalog.packages) {
+ if (catalogState(pkg, installedNames, declared).state !== 'available')
+ continue;
+ if (integrations.has(pkg.integration)) continue;
+ integrations.add(pkg.integration);
+ items.push({
+ package: pkg.package,
+ kind: 'package',
+ name: pkg.package,
+ installed: false,
+ ...(pkg.description ? {description: pkg.description} : {}),
+ });
+ for (const c of pkg.contributions) {
+ items.push({
+ package: pkg.package,
+ kind: c.kind,
+ name: c.name,
+ installed: false,
+ ...(c.title ? {title: c.title} : {}),
+ ...(c.summary ? {summary: c.summary} : {}),
+ ...(c.keywords ? {keywords: c.keywords} : {}),
+ });
+ }
+ }
+ return items;
+}
diff --git a/packages/cli/api/discover/_catalog-view.test.mjs b/packages/cli/api/discover/_catalog-view.test.mjs
new file mode 100644
index 0000000000..1d3ad2be55
--- /dev/null
+++ b/packages/cli/api/discover/_catalog-view.test.mjs
@@ -0,0 +1,128 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the pure views over discover sources' catalogs.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ availableEntries,
+ catalogState,
+ kindLists,
+ searchItems,
+ withLatest,
+} from './_catalog-view.mjs';
+
+/**
+ * @param {string} name
+ * @param {string} integration
+ * @param {object} [extra]
+ * @returns {any}
+ */
+function entry(name, integration, extra = {}) {
+ return {
+ package: name,
+ integration,
+ aliases: [],
+ latest: '1.0.0',
+ versions: [],
+ contributions: [{kind: 'component', name: 'A'}],
+ source: 'S',
+ ...extra,
+ };
+}
+
+const CATALOG = {
+ sources: [],
+ packages: [
+ entry('@acme/ui', 'acme-ui', {aliases: ['@acme/ui-classic']}),
+ entry('@acme/ui-classic', 'acme-ui', {aliases: ['@acme/ui']}),
+ entry('@acme/charts', 'charts', {
+ latest: '2.0.0',
+ contributions: [{kind: 'theme', name: 'ocean'}],
+ }),
+ ],
+};
+
+/** @param {string} name @returns {any} */
+const installed = name => ({name, category: name, components: []});
+
+describe('availableEntries', () => {
+ it('offers each integration once, under the first name a source lists', () => {
+ expect(
+ availableEntries(CATALOG, [], new Set()).map(e => [e.name, e.aliases]),
+ ).toEqual([
+ ['@acme/ui', ['@acme/ui-classic']],
+ ['@acme/charts', undefined],
+ ]);
+ });
+
+ it('never offers an integration the project has under another name', () => {
+ expect(
+ availableEntries(CATALOG, [installed('@acme/ui-classic')], new Set()).map(
+ e => e.name,
+ ),
+ ).toEqual(['@acme/charts']);
+ });
+
+ it('does not offer a package the project declares, even when it did not load', () => {
+ expect(
+ availableEntries(CATALOG, [], new Set(['@acme/charts'])).map(e => e.name),
+ ).toEqual(['@acme/ui']);
+ });
+
+ it('describes an entry the way an installed one is described', () => {
+ expect(availableEntries(CATALOG, [], new Set())[1]).toEqual({
+ name: '@acme/charts',
+ components: [],
+ version: '2.0.0',
+ themes: ['ocean'],
+ source: 'S',
+ });
+ });
+});
+
+describe('catalogState', () => {
+ it('names the package the project has instead', () => {
+ expect(
+ catalogState(CATALOG.packages[0], new Set(['@acme/ui-classic']), new Set()),
+ ).toEqual({state: 'alias', installedAs: '@acme/ui-classic'});
+ });
+});
+
+describe('withLatest', () => {
+ it('adds the latest release a source knows to an installed package', () => {
+ expect(withLatest([installed('@acme/charts')], CATALOG)[0]).toMatchObject({
+ latest: '2.0.0',
+ });
+ });
+});
+
+describe('kindLists', () => {
+ it('groups items by kind, always with components', () => {
+ expect(
+ kindLists([
+ {kind: 'theme', name: 'ocean'},
+ {kind: 'component', name: 'A'},
+ ]),
+ ).toEqual({components: ['A'], themes: ['ocean']});
+ });
+});
+
+describe('searchItems', () => {
+ it('covers installed packages and their other items, then what could be added', () => {
+ const items = searchItems(
+ [{...installed('@acme/widgets'), templates: ['pages/Home']}],
+ CATALOG,
+ new Set(),
+ );
+ expect(items.map(i => [i.package, i.kind, i.name, i.installed])).toEqual([
+ ['@acme/widgets', 'package', '@acme/widgets', true],
+ ['@acme/widgets', 'template', 'pages/Home', true],
+ ['@acme/ui', 'package', '@acme/ui', false],
+ ['@acme/ui', 'component', 'A', false],
+ ['@acme/charts', 'package', '@acme/charts', false],
+ ['@acme/charts', 'theme', 'ocean', false],
+ ]);
+ });
+});
diff --git a/packages/cli/api/discover/detail/detail.mjs b/packages/cli/api/discover/detail/detail.mjs
index 3ea135e2f2..e23123e140 100644
--- a/packages/cli/api/discover/detail/detail.mjs
+++ b/packages/cli/api/discover/detail/detail.mjs
@@ -1,33 +1,87 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file discover.detail leaf — browse one external package (@scope/name).
+ * @file discover.detail leaf — one package: what it adds, and, when a discover
+ * source knows it, every version and the latest one.
*
- * @position api/discover/detail — pure projection over the packages resolved by
- * ../_adapter; throws AstryxError (ERR_UNKNOWN_PACKAGE) for an unknown scope.
+ * @position api/discover/detail — pure projection over the packages and catalog
+ * entry resolved by ../_adapter; throws AstryxError (ERR_UNKNOWN_PACKAGE) for
+ * a package neither the project nor any source knows.
*/
import {toEntry} from '../_adapter.mjs';
+import {catalogEntry, defaultVersion} from '../_catalog-view.mjs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
/**
- * Build the discover.detail response for a scoped package name. Throws
- * AstryxError (ERR_UNKNOWN_PACKAGE) — with the available packages as
- * suggestions — when no package matches.
+ * Build the discover.detail response for one package. The project's installed
+ * copy describes itself; any other version is described by its source. For a
+ * package the project does not have, `install` is the package-manager command
+ * that adds it — printed, never run.
*
- * @param {import('../_package-scanner.mjs').ScannedPackage[]} packages
- * @param {string} query scoped package name, e.g. `@scope/name`
+ * @param {import('../_adapter.mjs').InstalledPackage[]} packages
+ * @param {string} name package name, e.g. `@scope/name`
+ * @param {{
+ * catalog?: import('../_catalog-view.mjs').CatalogPackage,
+ * version?: string,
+ * add?: (name: string, version?: string) => string,
+ * installedAs?: string,
+ * }} [options]
* @returns {import('../discover.type.mjs').DiscoverDetailResponse}
*/
-export function detail(packages, query) {
- const pkg = packages.find(p => p.name === query);
- if (!pkg) {
+export function detail(packages, name, options = {}) {
+ const {catalog, version, add, installedAs} = options;
+ const pkg = packages.find(p => p.name === name);
+ if (!pkg && !catalog) {
throw new AstryxError(
- `Package "${query}" not found`,
+ `Package "${name}" not found`,
packages.map(p => ({name: p.name, reason: 'available package'})),
ERROR_CODES.ERR_UNKNOWN_PACKAGE,
);
}
- return {type: 'discover.detail', data: toEntry(pkg)};
+
+ const known = new Set([
+ ...(catalog?.versions.map(v => v.version) ?? []),
+ ...(pkg?.version ? [pkg.version] : []),
+ ]);
+ if (version && !known.has(version)) {
+ const releases = catalog?.versions.filter(v => !v.prerelease) ?? [];
+ throw new AstryxError(
+ `Version "${version}" of ${name} not found`,
+ (releases.length > 0 ? releases.map(v => v.version) : [...known])
+ .slice(0, 5)
+ .map(v => ({name: `${name}@${v}`, reason: 'published version'})),
+ ERROR_CODES.ERR_NOT_FOUND,
+ );
+ }
+
+ const local = pkg != null && (!version || version === pkg.version);
+ /** @type {Record<string, unknown>} */
+ const data = local
+ ? {...toEntry(pkg), installed: true}
+ : {
+ ...catalogEntry(
+ /** @type {NonNullable<typeof catalog>} */ (catalog),
+ version ?? defaultVersion(/** @type {NonNullable<typeof catalog>} */ (catalog)),
+ ),
+ installed: pkg != null,
+ ...(pkg?.version ? {installedVersion: pkg.version} : {}),
+ };
+ if (catalog) {
+ if (catalog.latest) data.latest = catalog.latest;
+ if (catalog.aliases.length > 0) data.aliases = catalog.aliases;
+ data.source = catalog.source;
+ }
+ if (!pkg) {
+ if (installedAs) data.installedAs = installedAs;
+ else if (add) data.install = add(name, version);
+ }
+ if (catalog) data.versions = catalog.versions;
+ return {
+ type: 'discover.detail',
+ data: /** @type {import('../discover.type.mjs').DiscoverDetailResponse['data']} */ (
+ data
+ ),
+ };
}
diff --git a/packages/cli/api/discover/detail/detail.test.mjs b/packages/cli/api/discover/detail/detail.test.mjs
index 05c0ce89e7..ba50809764 100644
--- a/packages/cli/api/discover/detail/detail.test.mjs
+++ b/packages/cli/api/discover/detail/detail.test.mjs
@@ -36,6 +36,7 @@ describe('discover.detail leaf', () => {
category: '@acme/widgets',
components: ['Alpha', 'Beta'],
version: '1.2.3',
+ installed: true,
});
});
@@ -55,3 +56,87 @@ describe('discover.detail leaf', () => {
]);
});
});
+
+describe('discover.detail leaf with a discover source', () => {
+ /** @type {any} */
+ const catalog = {
+ package: '@acme/charts',
+ integration: 'acme-charts',
+ aliases: ['@acme/charts-legacy'],
+ latest: '2.0.0',
+ source: 'Acme',
+ versions: [
+ {version: '2.1.0-beta.1', publishedAt: '2026-09-30T00:00:00.000Z', prerelease: true, status: 'ok'},
+ {version: '2.0.0', publishedAt: '2026-09-20T00:00:00.000Z', prerelease: false, status: 'ok'},
+ {version: '1.0.0', publishedAt: null, prerelease: false, status: 'manifest_load_error'},
+ ],
+ contributions: [
+ {kind: 'component', name: 'Chart'},
+ {kind: 'template', name: 'pages/Report'},
+ ],
+ };
+ /** @param {string} name @param {string} [version] */
+ const add = (name, version) => `pnpm add ${version ? `${name}@${version}` : name}`;
+
+ it('describes a package the project does not have, with the command that adds it', () => {
+ expect(detail(PACKAGES, '@acme/charts', {catalog, add}).data).toEqual({
+ name: '@acme/charts',
+ category: '@acme/charts',
+ components: ['Chart'],
+ version: '2.0.0',
+ templates: ['pages/Report'],
+ installed: false,
+ latest: '2.0.0',
+ aliases: ['@acme/charts-legacy'],
+ source: 'Acme',
+ install: 'pnpm add @acme/charts',
+ versions: catalog.versions,
+ });
+ });
+
+ it('describes any version, prereleases included', () => {
+ const {data} = detail(PACKAGES, '@acme/charts', {catalog, add, version: '2.1.0-beta.1'});
+ expect(data.version).toBe('2.1.0-beta.1');
+ expect(data.install).toBe('pnpm add @acme/[email protected]');
+ });
+
+ it('refuses a version that was never published, and suggests releases', () => {
+ let err;
+ try {
+ detail(PACKAGES, '@acme/charts', {catalog, add, version: '3.0.0'});
+ } catch (e) {
+ err = e;
+ }
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_NOT_FOUND');
+ expect(err.suggestions.map(s => s.name)).toEqual([
+ ]);
+ });
+
+ it('names the package the project has instead of offering an alias', () => {
+ const {data} = detail(PACKAGES, '@acme/charts', {
+ catalog,
+ add,
+ installedAs: '@acme/charts-legacy',
+ });
+ expect(data.installedAs).toBe('@acme/charts-legacy');
+ expect(data).not.toHaveProperty('install');
+ });
+
+ it("keeps describing the installed copy from the project, with the source's versions", () => {
+ const {data} = detail(PACKAGES, '@acme/widgets', {
+ catalog: {...catalog, package: '@acme/widgets', latest: '1.3.0'},
+ add,
+ });
+ expect(data).toMatchObject({
+ name: '@acme/widgets',
+ components: ['Alpha', 'Beta'],
+ version: '1.2.3',
+ installed: true,
+ latest: '1.3.0',
+ });
+ expect(data).not.toHaveProperty('install');
+ });
+});
diff --git a/packages/cli/api/discover/detail/item/item.mjs b/packages/cli/api/discover/detail/item/item.mjs
new file mode 100644
index 0000000000..74038ce68f
--- /dev/null
+++ b/packages/cli/api/discover/detail/item/item.mjs
@@ -0,0 +1,78 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file discover.item leaf — one item a package adds, when it is not an
+ * installed component (those keep resolving to their full doc through
+ * ../doc).
+ *
+ * @position api/discover/detail/item — pure projection over the packages and
+ * catalog entry resolved by ../../_adapter.
+ */
+
+import {KIND_FIELDS} from '../../_adapter.mjs';
+import {defaultVersion} from '../../_catalog-view.mjs';
+
+/**
+ * Find one item of a package: an installed package's own templates, docs,
+ * themes, and codemods first, then what a discover source lists for the
+ * package. Returns null when neither has it, so the caller can report the
+ * component lookup's own error.
+ *
+ * @param {import('../../_adapter.mjs').InstalledPackage[]} packages
+ * @param {string} packageName
+ * @param {string} itemName
+ * @param {{
+ * catalog?: import('../../_catalog-view.mjs').CatalogPackage,
+ * version?: string,
+ * add?: (name: string, version?: string) => string,
+ * installedAs?: string,
+ * }} [options]
+ * @returns {import('../../discover.type.mjs').DiscoverItemResponse | null}
+ */
+export function item(packages, packageName, itemName, options = {}) {
+ const {catalog, version, add, installedAs} = options;
+ const pkg = packages.find(p => p.name === packageName);
+ if (pkg && (!version || version === pkg.version)) {
+ for (const [kind, field] of KIND_FIELDS) {
+ if (kind === 'component') continue;
+ const names = /** @type {Record<string, unknown>} */ (pkg)[field];
+ if (Array.isArray(names) && names.includes(itemName)) {
+ return {
+ type: 'discover.item',
+ data: {
+ package: packageName,
+ ...(pkg.version ? {version: pkg.version} : {}),
+ kind,
+ name: itemName,
+ installed: true,
+ },
+ };
+ }
+ }
+ }
+
+ const lower = itemName.toLowerCase();
+ const found =
+ catalog?.contributions.find(c => c.name === itemName) ??
+ catalog?.contributions.find(c => c.name.toLowerCase() === lower);
+ if (!catalog || !found) return null;
+ const shown = version ?? defaultVersion(catalog);
+ return {
+ type: 'discover.item',
+ data: {
+ package: packageName,
+ ...(shown ? {version: shown} : {}),
+ kind: found.kind,
+ name: found.name,
+ ...(found.title ? {title: found.title} : {}),
+ ...(found.summary ? {summary: found.summary} : {}),
+ ...(found.keywords ? {keywords: found.keywords} : {}),
+ installed: pkg != null,
+ ...(pkg == null && installedAs ? {installedAs} : {}),
+ ...(pkg == null && !installedAs && add
+ ? {install: add(packageName, version)}
+ : {}),
+ source: catalog.source,
+ },
+ };
+}
diff --git a/packages/cli/api/discover/detail/item/item.test.mjs b/packages/cli/api/discover/detail/item/item.test.mjs
new file mode 100644
index 0000000000..f9cb576321
--- /dev/null
+++ b/packages/cli/api/discover/detail/item/item.test.mjs
@@ -0,0 +1,73 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the discover.item leaf, a pure projection over installed
+ * packages and a source's catalog entry.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {item} from './item.mjs';
+
+/** @type {any[]} */
+const PACKAGES = [
+ {
+ name: '@acme/widgets',
+ category: '@acme/widgets',
+ version: '1.2.3',
+ components: ['Alpha'],
+ templates: ['pages/Home'],
+ docs: ['guide'],
+ },
+];
+
+/** @type {any} */
+const CATALOG = {
+ package: '@acme/charts',
+ integration: 'acme-charts',
+ aliases: [],
+ latest: '2.0.0',
+ source: 'Acme',
+ versions: [],
+ contributions: [{kind: 'template', name: 'pages/Report', title: 'Report page'}],
+};
+
+/** @param {string} name @param {string} [version] */
+const add = (name, version) => `pnpm add ${version ? `${name}@${version}` : name}`;
+
+describe('discover.item leaf', () => {
+ it("finds an installed package's own template, doc, theme, or codemod", () => {
+ expect(item(PACKAGES, '@acme/widgets', 'pages/Home')).toEqual({
+ type: 'discover.item',
+ data: {
+ package: '@acme/widgets',
+ version: '1.2.3',
+ kind: 'template',
+ name: 'pages/Home',
+ installed: true,
+ },
+ });
+ });
+
+ it('finds an item a source lists, with the command that adds its package', () => {
+ expect(
+ item(PACKAGES, '@acme/charts', 'pages/report', {catalog: CATALOG, add}),
+ ).toEqual({
+ type: 'discover.item',
+ data: {
+ package: '@acme/charts',
+ version: '2.0.0',
+ kind: 'template',
+ name: 'pages/Report',
+ title: 'Report page',
+ installed: false,
+ install: 'pnpm add @acme/charts',
+ source: 'Acme',
+ },
+ });
+ });
+
+ it('returns null when neither the project nor a source has it', () => {
+ expect(item(PACKAGES, '@acme/widgets', 'Nope')).toBeNull();
+ expect(item(PACKAGES, '@acme/charts', 'Nope', {catalog: CATALOG})).toBeNull();
+ });
+});
diff --git a/packages/cli/api/discover/discover.doc.mjs b/packages/cli/api/discover/discover.doc.mjs
index 938fd3d49f..9e591c3149 100644
--- a/packages/cli/api/discover/discover.doc.mjs
+++ b/packages/cli/api/discover/discover.doc.mjs
@@ -13,22 +13,25 @@ export const doc = {
name: 'discover',
namespace: 'cli/api',
displayName: 'discover()',
- summary: 'Browse and search components from configured external packages.',
+ summary:
+ 'Browse and search integrations: the ones a project has and, through discover sources, the ones it could add.',
description:
- 'Explores components contributed by configured external packages and integrations ' +
- 'the ones that declare a components root. With no query it lists those packages; ' +
- 'an @scope/name query browses one package; @scope/name/Component (or a free-text ' +
- "term that resolves to a single component) returns that component's validated doc; " +
- 'a free-text term with several matches returns the candidate list.',
+ 'Lists the integrations a project loads and, when the project or an integration provides a discover source, ' +
+ 'the packages it could add, with what each one adds per kind. An @scope/name query shows one package with every ' +
+ 'version its source knows; @scope/name@version shows one version; @scope/name/Component returns an installed ' +
+ "component's validated doc, and any other item path returns that item. A free-text term searches every item and " +
+ 'package. Discover only reads: it prints the command that adds a package and never runs it.',
importPath: '@astryxdesign/cli/api',
signature:
- 'discover(query?: string, options?: DiscoverOptions): Promise<DiscoverListResponse | DiscoverDetailResponse | DiscoverDetailDocResponse | DiscoverSearchResponse>',
+ 'discover(query?: string, options?: DiscoverOptions): Promise<DiscoverListResponse | DiscoverDetailResponse | DiscoverDetailDocResponse | DiscoverItemResponse | DiscoverSearchResponse>',
keywords: [
'discover',
'packages',
'integrations',
'external',
'components',
+ 'catalog',
+ 'versions',
'search',
],
params: [
@@ -36,13 +39,39 @@ export const doc = {
name: 'query',
type: 'string',
description:
- 'An @scope/name package, an @scope/name/Component path, or a free-text term. Omit to list all configured packages.',
+ 'A package (@scope/name, optionally @version), an item path (@scope/name/<item>), or a free-text term. Omit to list packages.',
},
{
name: 'options.components',
type: 'boolean',
description:
- 'In the CLI package list, print every component of each package instead of the first 10. A display flag for the CLI renderer; the programmatic response is unchanged.',
+ 'In the CLI package list, print every component, and every other item, of each package instead of the first 10. A display flag for the CLI renderer; the programmatic response is unchanged.',
+ },
+ {
+ name: 'options.type',
+ type: "'component' | 'template' | 'doc' | 'theme' | 'codemod' | 'agent-doc'",
+ description:
+ 'Only one kind: in the list, packages that add it; in a search, items of that kind.',
+ },
+ {
+ name: 'options.installed',
+ type: 'boolean',
+ description:
+ 'Only what the project has. Cannot be set with options.available.',
+ default: 'false',
+ },
+ {
+ name: 'options.available',
+ type: 'boolean',
+ description:
+ 'Only what the project could add. Cannot be set with options.installed.',
+ default: 'false',
+ },
+ {
+ name: 'options.limit',
+ type: 'number',
+ description: 'Max number of search results, a positive integer.',
+ default: '20',
},
{
name: 'options.lang',
@@ -60,21 +89,27 @@ export const doc = {
{
type: 'discover.list',
description:
- 'The configured external packages (name, category, components, version, description). When empty it carries meta.configured to distinguish "nothing configured" from "configured but nothing discovered".',
+ 'The installed integrations (name, category, components, version, and a list per other kind they add). With a discover source, meta.available lists what the project could add and meta.sources reports each source. When the list is empty it carries meta.configured.',
},
{
type: 'discover.detail',
- description: 'A single package entry, for an @scope/name query.',
+ description:
+ 'One package: what the shown version adds, whether the project has it, its versions and latest release when a source knows them, and the command that adds it when the project does not have it.',
},
{
type: 'discover.detail.doc',
description:
- 'The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term that resolves to exactly one component.',
+ 'The validated ComponentDoc for one installed component, for an @scope/name/Component query.',
+ },
+ {
+ type: 'discover.item',
+ description:
+ 'One item that is not an installed component: its kind, name, the package and version that add it, and whether the project has the package.',
},
{
type: 'discover.search',
description:
- 'The query echoed back plus the matching {package, component} pairs, when a free-text term matches several components.',
+ 'The query echoed back plus every matching item and package, each with its kind and whether the project has it, even when one name matches exactly or only one item matches; total is set when the limit cut the list.',
},
],
throws: [
@@ -82,17 +117,21 @@ export const doc = {
code: 'ERR_INVALID_ARGUMENT',
when: 'the query is a non-string value, or a free-text search is run with an empty query',
},
+ {
+ code: 'ERR_INVALID_OPTION',
+ when: 'options.type is not a known kind, options.limit is not a positive integer, or options.installed and options.available are both set',
+ },
{
code: 'ERR_UNKNOWN_PACKAGE',
- when: 'the @scope/name package is not among the configured packages',
+ when: 'neither the project nor any discover source has the package',
},
{
code: 'ERR_UNKNOWN_COMPONENT',
- when: 'the component is not found in the named @scope/name package',
+ when: 'the item is not in the named package',
},
{
code: 'ERR_NOT_FOUND',
- when: 'a free-text term matches no component in any package',
+ when: 'a free-text term matches nothing, or the requested version is not published',
},
{
code: 'ERR_INVALID_DOC',
@@ -100,10 +139,14 @@ export const doc = {
},
],
examples: [
- {label: 'List packages', code: 'const {data} = await discover();'},
+ {label: 'List packages', code: 'const {data, meta} = await discover();'},
{label: 'Browse a package', code: "await discover('@acme/ui');"},
+ {label: 'One version', code: "await discover('@acme/[email protected]');"},
{label: 'Show a component doc', code: "await discover('@acme/ui/Button');"},
- {label: 'Free-text search', code: "await discover('button');"},
+ {
+ label: 'Search templates to add',
+ code: "await discover('dashboard', {type: 'template', available: true});",
+ },
],
command: 'discover',
related: ['component', 'search', 'template'],
diff --git a/packages/cli/api/discover/discover.mjs b/packages/cli/api/discover/discover.mjs
index ed4e7b5013..4652a5c562 100644
--- a/packages/cli/api/discover/discover.mjs
+++ b/packages/cli/api/discover/discover.mjs
@@ -3,55 +3,193 @@
/**
* @file Programmatic API for the discover command — dispatcher + barrel.
*
- * `discover()` keeps the exact same signature and response union it always had,
- * so `api/index.mjs` and the CLI consumer are untouched. Its only job now is to
- * discover the external packages (via ./_adapter) and route to the leaf that
- * owns each response shape:
+ * `discover()` browses the integrations a project has and, through discover
+ * sources, the ones it could add. It only reads: the package manager installs.
+ * Its job is to resolve the project and its sources (via ./_adapter) and route
+ * to the leaf that owns each response shape:
*
- * discover.list -> ./list/list.mjs
- * discover.detail -> ./detail/detail.mjs
- * discover.detail.doc -> ./detail/doc/doc.mjs
- * discover.search -> ./search/search.mjs
+ * discover -> ./list/list.mjs discover.list
+ * discover <package>[@<version>] -> ./detail/detail.mjs discover.detail
+ * discover <package>/<Component> -> ./detail/doc/doc.mjs discover.detail.doc
+ * discover <package>/<item> -> ./detail/item/item.mjs discover.item
+ * discover <words> -> ./search/search.mjs discover.search (always a list)
*
- * @position api/discover — thin router over ./_adapter + the discover leaves.
+ * Source results are additive: they ride in `meta.available`/`meta.sources`,
+ * in extra fields, or as extra search matches, so every existing field keeps
+ * its meaning.
+ *
+ * @position api/discover — thin router over ./_adapter, ./_catalog-view, and
+ * the discover leaves.
*/
-import {discoverPackages} from './_adapter.mjs';
+import {
+ addCommand,
+ callSources,
+ declaredDependencies,
+ describeInstalled,
+ discoverPackages,
+ findComponent,
+ hasSources,
+} from './_adapter.mjs';
+import {
+ availableEntries,
+ catalogState,
+ searchItems,
+ withLatest,
+} from './_catalog-view.mjs';
import {list} from './list/list.mjs';
import {detail} from './detail/detail.mjs';
-import {doc} from './detail/doc/doc.mjs';
+import {doc, docFromResult} from './detail/doc/doc.mjs';
+import {item} from './detail/item/item.mjs';
import {search} from './search/search.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
+import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
+import {DISCOVER_KINDS} from '../../authoring/discover/parse.mjs';
+
+const DEFAULT_LIMIT = 20;
+
+/** @type {import('./_adapter.mjs').CatalogResult} */
+const NO_CATALOG = {sources: [], packages: []};
+
+/**
+ * Split a package-shaped query: `name`, `name@version`, or `name/item`, with an
+ * optional `@scope/` prefix on the name.
+ * @param {string} query
+ * @returns {{scoped: boolean, name: string, version?: string, item?: string}}
+ */
+function splitTarget(query) {
+ const scoped = query.startsWith('@');
+ const firstSlash = query.indexOf('/');
+ let head = query;
+ /** @type {string | undefined} */
+ let rest;
+ const split = scoped
+ ? firstSlash < 0
+ ? -1
+ : query.indexOf('/', firstSlash + 1)
+ : firstSlash;
+ if (split > 0) {
+ head = query.slice(0, split);
+ rest = query.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} : {}),
+ };
+}
+
+/**
+ * @param {{type?: unknown, installed?: boolean, available?: boolean, limit?: unknown}} options
+ */
+function checkOptions({type, installed, available, limit}) {
+ if (
+ type != null &&
+ !(/** @type {readonly unknown[]} */ (DISCOVER_KINDS).includes(type))
+ ) {
+ throw new AstryxError(
+ `Unknown --type "${String(type)}"`,
+ DISCOVER_KINDS.map(kind => ({name: kind, reason: 'item kind'})),
+ ERROR_CODES.ERR_INVALID_OPTION,
+ );
+ }
+ if (installed && available) {
+ throw new AstryxError(
+ '--installed and --available cannot be used together',
+ undefined,
+ ERROR_CODES.ERR_INVALID_OPTION,
+ );
+ }
+ if (
+ limit != null &&
+ !(typeof limit === 'number' && Number.isInteger(limit) && limit > 0)
+ ) {
+ throw new AstryxError(
+ `--limit must be a positive integer, not "${String(limit)}"`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_OPTION,
+ );
+ }
+}
+
+/**
+ * Items a source lists for a package that look like the one asked for: names
+ * that contain it, else the closest few by spelling.
+ * @param {import('../../authoring/discover/type.js').DiscoverPackage} entry
+ * @param {string} wanted
+ * @returns {Array<{name: string, reason: string}>}
+ */
+function similarItems(entry, wanted) {
+ const lower = wanted.toLowerCase();
+ const names = [...new Set(entry.contributions.map(c => c.name))];
+ const hits = names.filter(name => name.toLowerCase().includes(lower));
+ const picked =
+ hits.length > 0
+ ? hits.slice(0, 5)
+ : names
+ .map(name => ({
+ name,
+ distance: levenshteinDistance(lower, name.toLowerCase()),
+ }))
+ .filter(m => m.distance <= 3)
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, 5)
+ .map(m => m.name);
+ return picked.map(name => ({
+ name: `${entry.package}/${name}`,
+ reason: 'similar name',
+ }));
+}
/**
* @param {string} [query]
- * @param {object} [options]
- * @param {boolean} [options.components]
- * @param {string} [options.lang]
- * @param {boolean} [options.zh]
+ * @param {import('./discover.type.mjs').DiscoverOptions} [options]
* @returns {Promise<
* import('./discover.type.mjs').DiscoverListResponse |
* import('./discover.type.mjs').DiscoverDetailResponse |
* import('./discover.type.mjs').DiscoverDetailDocResponse |
+ * import('./discover.type.mjs').DiscoverItemResponse |
* import('./discover.type.mjs').DiscoverSearchResponse
* >}
*/
export async function discover(query, options = {}) {
- const {lang = null, zh = false} = options;
- const {packages, configured} = await discoverPackages();
+ const {lang = null, zh = false, type, limit} = options;
+ checkOptions(options);
+ const only = options.installed
+ ? /** @type {const} */ ('installed')
+ : options.available
+ ? /** @type {const} */ ('available')
+ : undefined;
+
+ const {packages: scanned, configured, project} = await discoverPackages();
+ const withSources = hasSources(project);
+ const packages = await describeInstalled(project, scanned);
+ const declared = declaredDependencies(project);
+ const add = addCommand(project);
- // No discoverable packages — either nothing configured, or configured but
- // empty. The list leaf owns the empty envelope + `configured` flag. This
- // short-circuits before query parsing, exactly as the flat command did.
- if (packages.length === 0) return list(packages, {configured});
+ /** @param {{package?: string, version?: string}} [request] */
+ const catalogFor = async request =>
+ withSources ? await callSources(project, request) : NO_CATALOG;
- // No query: the full package list.
- if (!query) return list(packages, {configured});
+ // No query, or nothing to look through: the list.
+ if (!query || (packages.length === 0 && !withSources)) {
+ if (!withSources) return list(packages, {configured, type, only});
+ const catalog = await catalogFor();
+ return list(withLatest(packages, catalog), {
+ configured,
+ type,
+ only,
+ available: availableEntries(catalog, packages, declared),
+ sources: catalog.sources,
+ });
+ }
- // A non-string (truthy) query would crash `.startsWith`/`.indexOf` below
- // with a raw TypeError (no ERR_* code → downgrades to ERR_UNKNOWN). The CLI
- // only ever passes a string, but the public API must fail with a code.
+ // A non-string (truthy) query would crash the parsing below with a raw
+ // TypeError (no ERR_* code → downgrades to ERR_UNKNOWN). The CLI only ever
+ // passes a string, but the public API must fail with a code.
if (typeof query !== 'string') {
throw new AstryxError(
`Invalid query "${String(query)}"`,
@@ -60,17 +198,63 @@ export async function discover(query, options = {}) {
);
}
- // Scoped package query: @scope/name or @scope/name/Component
- if (query.startsWith('@')) {
- const slashIdx = query.indexOf('/', query.indexOf('/') + 1);
- if (slashIdx > 0) {
- const pkgName = query.slice(0, slashIdx);
- const compName = query.slice(slashIdx + 1);
- return await doc(packages, pkgName, compName, {lang, zh});
+ const target = splitTarget(query);
+ const installedNames = new Set(packages.map(p => p.name));
+
+ /**
+ * One package, one version, or one item, once `target.name` is known to be
+ * a package the project or a source has.
+ * @param {import('./_adapter.mjs').CatalogResult} catalog
+ */
+ const packageView = async catalog => {
+ const entry = catalog.packages.find(p => p.package === target.name);
+ const installedAs = entry
+ ? catalogState(entry, installedNames, declared).installedAs
+ : undefined;
+ const context = {catalog: entry, version: target.version, add, installedAs};
+ if (!target.item) return detail(packages, target.name, context);
+ const found = item(packages, target.name, target.item, context);
+ if (found) return found;
+ // Only an installed package has docs to fall back to. For one that is
+ // only in a source, the item is what is unknown, not the package.
+ if (entry && !packages.some(p => p.name === target.name)) {
+ throw new AstryxError(
+ `"${target.item}" not found in ${target.name}`,
+ similarItems(entry, target.item),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
}
- return detail(packages, query);
+ return await doc(packages, target.name, target.item, {lang, zh});
+ };
+
+ // An installed component keeps resolving to its full doc, before any source
+ // is asked anything.
+ const installedPkg = packages.find(p => p.name === target.name);
+ if (installedPkg && target.item && !target.version) {
+ const resolved = findComponent([installedPkg], target.item);
+ if (resolved) return await docFromResult(resolved, {lang, zh});
+ }
+
+ if (target.scoped) {
+ return await packageView(
+ await catalogFor({package: target.name, version: target.version}),
+ );
+ }
+
+ const listing = await catalogFor();
+ const isPackage =
+ installedPkg != null ||
+ listing.packages.some(p => p.package === target.name);
+ if (isPackage && (target.version || target.item || target.name === query)) {
+ return await packageView(
+ await catalogFor({package: target.name, version: target.version}),
+ );
}
- // Free-text search across all packages.
- return await search(packages, query, {lang, zh});
+ return await search(packages, query, {
+ items: searchItems(packages, listing, declared),
+ type,
+ only,
+ limit: limit ?? DEFAULT_LIMIT,
+ });
}
diff --git a/packages/cli/api/discover/discover.test.mjs b/packages/cli/api/discover/discover.test.mjs
index 65c1007057..771c55bc73 100644
--- a/packages/cli/api/discover/discover.test.mjs
+++ b/packages/cli/api/discover/discover.test.mjs
@@ -68,10 +68,19 @@ describe('discover() dispatcher routing', () => {
it('free-text query with multiple matches -> discover.search envelope', async () => {
// 'a' is a substring of both Alpha and Beta (no exact match), so the search
// leaf returns the multi-match discover.search envelope. Proves free-text
- // routing reaches the search leaf and projects its envelope.
+ // routing reaches the search leaf and projects its envelope. Search also
+ // matches package names, so the package itself is listed after them.
const r = await discover('a');
expect(r.type).toBe('discover.search');
- expect(r.data.matches.map(m => m.component).sort()).toEqual(['Alpha', 'Beta']);
+ expect(
+ r.data.matches.filter(m => m.kind === 'component').map(m => m.component),
+ ).toEqual(['Alpha', 'Beta']);
+ expect(r.data.matches).toContainEqual({
+ package: '@acme/widgets',
+ component: '@acme/widgets',
+ kind: 'package',
+ installed: true,
+ });
});
it('free-text query with no match still routes to the search leaf (coded not-found)', async () => {
diff --git a/packages/cli/api/discover/discover.type.mjs b/packages/cli/api/discover/discover.type.mjs
index df190488d9..cb3d7a9a94 100644
--- a/packages/cli/api/discover/discover.type.mjs
+++ b/packages/cli/api/discover/discover.type.mjs
@@ -7,24 +7,37 @@
* Invocation -> type discriminator
* ------------------------------------------------------------------
* astryx --json discover -> discover.list
- * astryx --json discover @scope/name -> discover.detail
+ * astryx --json discover @scope/name[@version] -> discover.detail
* astryx --json discover @scope/name/Component -> discover.detail.doc
- * astryx --json discover <searchterm> (1 match) -> discover.detail.doc
- * astryx --json discover <searchterm> (N matches) -> discover.search
+ * astryx --json discover @scope/name/<item> -> discover.item
+ * astryx --json discover <searchterm> -> discover.search
* (not found) -> CLIError
+ *
+ * Fields added for discover sources are additive: every earlier field keeps
+ * its meaning.
*/
/**
* astryx --json discover
* @typedef {object} DiscoverListResponse
* @property {'discover.list'} type
- * @property {DiscoverListEntry[]} data
- * @property {{configured: boolean}} [meta] Present when the list is empty so
- * callers can distinguish "no packages configured" from "configured but
- * nothing discovered".
+ * @property {DiscoverListEntry[]} data The integrations the project loads.
+ * @property {DiscoverListMeta} [meta] Present when the list is empty, and
+ * whenever the project has a discover source.
*/
/**
+ * @typedef {object} DiscoverListMeta
+ * @property {boolean} [configured] Present when `data` is empty, so callers can
+ * distinguish "no packages configured" from "configured but nothing
+ * discovered".
+ * @property {DiscoverAvailableEntry[]} [available] What the project could add,
+ * one entry per integration, never an alias of a package it has.
+ * @property {DiscoverSourceState[]} [sources] What each discover source did.
+ */
+
+/**
+ * An installed integration.
* @typedef {object} DiscoverListEntry
* @property {string} name
* @property {string} category
@@ -32,13 +45,60 @@
* @property {string} [version]
* @property {string} [description]
* @property {string} [displayName]
+ * @property {string[]} [templates] Template ids, when it adds any.
+ * @property {string[]} [docs] Doc topic names, when it adds any.
+ * @property {string[]} [themes] Theme slugs, when it adds any.
+ * @property {string[]} [codemods] `<version>/<id>`, when it adds any.
+ * @property {string[]} [agentDocs] Agent guidance, when a source lists any.
+ * @property {string} [latest] The latest release a discover source knows.
*/
/**
- * astryx --json discover @scope/name
+ * A package the project could add.
+ * @typedef {object} DiscoverAvailableEntry
+ * @property {string} name
+ * @property {string} [version] Its latest release.
+ * @property {string[]} components
+ * @property {string[]} [templates]
+ * @property {string[]} [docs]
+ * @property {string[]} [themes]
+ * @property {string[]} [codemods]
+ * @property {string[]} [agentDocs]
+ * @property {string} [description]
+ * @property {string[]} [aliases] The integration's other package names.
+ * @property {string} source The discover source that lists it.
+ */
+
+/**
+ * @typedef {object} DiscoverSourceState
+ * @property {string} name
+ * @property {string} from `astryx.config`, or the integration that exports it.
+ * @property {'fresh' | 'saved' | 'failed'} status `saved`: the live call
+ * failed and discover used the copy saved at `savedAt`.
+ * @property {string} [generatedAt]
+ * @property {boolean} [complete]
+ * @property {string} [savedAt]
+ * @property {string} [error]
+ */
+
+/**
+ * astryx --json discover @scope/name[@version]
* @typedef {object} DiscoverDetailResponse
* @property {'discover.detail'} type
- * @property {DiscoverListEntry} data
+ * @property {DiscoverListEntry & {
+ * installed: boolean,
+ * installedVersion?: string,
+ * aliases?: string[],
+ * source?: string,
+ * installedAs?: string,
+ * install?: string,
+ * versions?: import('../../authoring/discover/type').DiscoverVersion[],
+ * }} data `installed` says whether the project has the package;
+ * `installedVersion` is set when it has another version than the one shown.
+ * `install` is the package-manager command that adds a package the project
+ * does not have; discover prints it and never runs it. `installedAs` names
+ * the package the project has instead, when this one is an alias of it.
+ * `versions` (newest first) comes from a discover source.
*/
/**
@@ -49,16 +109,42 @@
*/
/**
- * astryx --json discover <searchterm> (multiple matches)
+ * astryx --json discover @scope/name/<item>, for an item that is not an
+ * installed component.
+ * @typedef {object} DiscoverItemResponse
+ * @property {'discover.item'} type
+ * @property {{
+ * package: string,
+ * version?: string,
+ * kind: import('../../authoring/discover/type').DiscoverKind,
+ * name: string,
+ * title?: string,
+ * summary?: string,
+ * keywords?: string[],
+ * installed: boolean,
+ * installedAs?: string,
+ * install?: string,
+ * source?: string,
+ * }} data
+ */
+
+/**
+ * astryx --json discover <searchterm>
* @typedef {object} DiscoverSearchResponse
* @property {'discover.search'} type
- * @property {{query: string, matches: DiscoverSearchEntry[]}} data
+ * @property {{query: string, matches: DiscoverSearchEntry[], total?: number}} data
+ * `total` is set when `--limit` cut the list.
*/
/**
* @typedef {object} DiscoverSearchEntry
* @property {string} package
- * @property {string} component
+ * @property {string} component The item's name, for every kind; for a package
+ * match, the package name.
+ * @property {import('../../authoring/discover/type').DiscoverKind | 'package'} kind
+ * @property {boolean} installed Whether the project has the package.
+ * @property {string} [title]
+ * @property {string} [summary]
*/
/**
@@ -67,6 +153,10 @@
* @property {boolean} [components]
* @property {string} [lang]
* @property {boolean} [zh]
+ * @property {import('../../authoring/discover/type').DiscoverKind} [type]
+ * @property {boolean} [installed]
+ * @property {boolean} [available]
+ * @property {number} [limit]
*/
export {};
diff --git a/packages/cli/api/discover/list/list.mjs b/packages/cli/api/discover/list/list.mjs
index 3953077a4c..97f1a61ea1 100644
--- a/packages/cli/api/discover/list/list.mjs
+++ b/packages/cli/api/discover/list/list.mjs
@@ -1,26 +1,59 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file discover.list leaf — list the discovered external packages.
+ * @file discover.list leaf — the integrations the project has, and, when it has
+ * discover sources, the ones it could add.
*
- * @position api/discover/list — pure projection of the packages resolved by
- * ../_adapter into the discover.list envelope.
+ * @position api/discover/list — pure projection of the packages and catalog
+ * resolved by ../_adapter into the discover.list envelope.
*/
import {toEntry} from '../_adapter.mjs';
+import {hasKind} from '../_catalog-view.mjs';
/**
- * Build the discover.list response. An empty `packages` set produces the empty
- * envelope carrying `meta.configured`, so callers can distinguish "nothing
- * configured" from "configured but nothing discovered".
+ * Build the discover.list response. `data` lists installed integrations. An
+ * empty `data` carries `meta.configured`, so callers can distinguish "nothing
+ * configured" from "configured but nothing discovered". With discover sources,
+ * `meta.available` lists what the project could add and `meta.sources` reports
+ * what each source did.
*
- * @param {import('../_package-scanner.mjs').ScannedPackage[]} packages
- * @param {{configured: boolean}} meta
+ * @param {Array<import('../_adapter.mjs').InstalledPackage & {latest?: string}>} packages
+ * @param {{
+ * configured: boolean,
+ * available?: Array<Record<string, unknown>>,
+ * sources?: import('../_adapter.mjs').SourceState[],
+ * type?: import('../../../authoring/discover/type').DiscoverKind,
+ * only?: 'installed' | 'available',
+ * }} options
* @returns {import('../discover.type.mjs').DiscoverListResponse}
*/
-export function list(packages, {configured}) {
- if (packages.length === 0) {
- return {type: 'discover.list', data: [], meta: {configured}};
+export function list(packages, {configured, available, sources, type, only}) {
+ const keep = (/** @type {Record<string, unknown>} */ entry) =>
+ type == null || hasKind(entry, type);
+ const data =
+ only === 'available'
+ ? []
+ : packages
+ .map(toEntry)
+ .filter(entry =>
+ keep(/** @type {Record<string, unknown>} */ (entry)),
+ );
+
+ /** @type {Record<string, unknown>} */
+ const meta = {};
+ if (data.length === 0) meta.configured = configured;
+ if (sources !== undefined) {
+ meta.available = only === 'installed' ? [] : (available ?? []).filter(keep);
+ meta.sources = sources;
}
- return {type: 'discover.list', data: packages.map(toEntry)};
+ return Object.keys(meta).length > 0
+ ? {
+ type: 'discover.list',
+ data,
+ meta: /** @type {import('../discover.type.mjs').DiscoverListMeta} */ (
+ meta
+ ),
+ }
+ : {type: 'discover.list', data};
}
diff --git a/packages/cli/api/discover/list/list.test.mjs b/packages/cli/api/discover/list/list.test.mjs
index 2ac88565d4..103f267c21 100644
--- a/packages/cli/api/discover/list/list.test.mjs
+++ b/packages/cli/api/discover/list/list.test.mjs
@@ -57,3 +57,49 @@ describe('discover.list leaf', () => {
});
});
});
+
+describe('discover.list leaf with discover sources', () => {
+ const installed = [
+ pkg('@acme/widgets', ['Alpha'], {
+ version: '1.2.3',
+ latest: '1.3.0',
+ templates: ['pages/Home'],
+ }),
+ ];
+ const available = [
+ {name: '@acme/charts', version: '2.0.0', components: ['Chart'], source: 'Acme'},
+ {name: '@acme/themes', version: '1.0.0', components: [], themes: ['ocean'], source: 'Acme'},
+ ];
+ const sources = [{name: 'Acme', from: 'astryx.config', status: 'fresh'}];
+
+ it('lists what is installed in data and what could be added in meta', () => {
+ const res = list(installed, {configured: true, available, sources});
+ expect(res.data).toEqual([
+ {
+ name: '@acme/widgets',
+ category: '@acme/widgets',
+ components: ['Alpha'],
+ version: '1.2.3',
+ templates: ['pages/Home'],
+ latest: '1.3.0',
+ },
+ ]);
+ expect(res.meta).toEqual({available, sources});
+ });
+
+ it('keeps one side with only', () => {
+ expect(
+ list(installed, {configured: true, available, sources, only: 'installed'})
+ .meta?.available,
+ ).toEqual([]);
+ const res = list(installed, {configured: true, available, sources, only: 'available'});
+ expect(res.data).toEqual([]);
+ expect(res.meta).toEqual({configured: true, available, sources});
+ });
+
+ it('keeps only packages that add a kind with type', () => {
+ const res = list(installed, {configured: true, available, sources, type: 'theme'});
+ expect(res.data).toEqual([]);
+ expect(res.meta?.available?.map(e => e.name)).toEqual(['@acme/themes']);
+ });
+});
diff --git a/packages/cli/api/discover/search/search.mjs b/packages/cli/api/discover/search/search.mjs
index a65b0ba2f0..a9915df055 100644
--- a/packages/cli/api/discover/search/search.mjs
+++ b/packages/cli/api/discover/search/search.mjs
@@ -1,44 +1,76 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file discover.search leaf — free-text search across external packages.
+ * @file discover.search leaf — free-text search across installed packages and,
+ * when the project has discover sources, everything it could add.
*
- * Resolution order (matching the flat command exactly):
- * 1. exact component name -> discover.detail.doc
- * 2. single substring hit -> discover.detail.doc
- * 3. multiple substring hits -> discover.search
- * 4. fuzzy hits (distance <= 3) -> throw ERR_NOT_FOUND with suggestions
- * 5. otherwise -> throw ERR_NOT_FOUND
+ * A free-text query always answers with a list, so its response type depends
+ * on the form of the query and never on what the project has:
+ * 1. any matches -> discover.search
+ * 2. fuzzy hits (distance <= 3) -> throw ERR_NOT_FOUND with suggestions
+ * 3. otherwise -> throw ERR_NOT_FOUND
+ * Matches are installed components, the project's other installed items,
+ * packages, and every item a source lists for a package the project could add.
+ * A caller opens one item by its package path, which ../detail answers.
*
- * @position api/discover/search — projection over ../_adapter's resolver;
- * delegates the single-component cases to ../detail/doc.
+ * @position api/discover/search — pure ranking over the installed component
+ * names and ../_catalog-view's search items.
*/
-import {findComponent} from '../_adapter.mjs';
-import {docFromResult} from '../detail/doc/doc.mjs';
import {levenshteinDistance} from '../../../foundation/text/string-utils.mjs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
+import {DISCOVER_KINDS} from '../../../authoring/discover/parse.mjs';
/**
* @typedef {import('../_package-scanner.mjs').ScannedPackage} ScannedPackage
+ * @typedef {import('../_catalog-view.mjs').SearchItem} SearchItem
*/
+const KIND_ORDER = ['package', ...DISCOVER_KINDS];
+
+/**
+ * How well an item matches: 0 exact name, 1 name prefix, 2 name substring,
+ * 3 title, summary, keyword, or description; null for no match.
+ * @param {SearchItem} item
+ * @param {string} lower
+ * @returns {number | null}
+ */
+function rank(item, lower) {
+ const name = item.name.toLowerCase();
+ if (name === lower) return 0;
+ if (name.startsWith(lower)) return 1;
+ if (name.includes(lower)) return 2;
+ const text = [
+ item.title,
+ item.summary,
+ item.description,
+ ...(item.keywords ?? []),
+ ]
+ .filter(Boolean)
+ .join('\n')
+ .toLowerCase();
+ return text.includes(lower) ? 3 : null;
+}
+
/**
* Search all packages for `query` (a free-text term that never starts with
- * `@`). Resolves to a single component's docs when unambiguous, a search
- * response when several match, or throws AstryxError (ERR_NOT_FOUND) — with
- * fuzzy suggestions when any exist.
+ * `@`). Resolves to a search response when anything matches, even a single
+ * item or an exact component name, or throws AstryxError (ERR_NOT_FOUND) —
+ * with fuzzy suggestions when any exist.
*
- * @param {ScannedPackage[]} packages
+ * @param {ScannedPackage[]} packages installed packages
* @param {string} query
- * @param {{lang?: string | null, zh?: boolean}} opts
- * @returns {Promise<
- * import('../discover.type.mjs').DiscoverDetailDocResponse |
- * import('../discover.type.mjs').DiscoverSearchResponse
- * >}
+ * @param {{
+ * items?: SearchItem[],
+ * type?: import('../../../authoring/discover/type').DiscoverKind,
+ * only?: 'installed' | 'available',
+ * limit?: number,
+ * }} opts
+ * @returns {Promise<import('../discover.type.mjs').DiscoverSearchResponse>}
*/
-export async function search(packages, query, {lang, zh}) {
+export async function search(packages, query, opts) {
+ const {items = [], type, only, limit} = opts;
// An empty query must error, not match every component via `.includes('')`
// (parity with the api/search leaf). The discover() dispatcher already routes
// an empty query to list, but the leaf must be safe on its own.
@@ -51,50 +83,64 @@ export async function search(packages, query, {lang, zh}) {
}
const lower = query.toLowerCase();
- const exact = findComponent(packages, query);
- if (exact) return await docFromResult(exact, {lang, zh});
-
- const substringMatches =
- /** @type {Array<{pkg: ScannedPackage, comp: string}>} */ ([]);
- for (const pkg of packages) {
- for (const comp of pkg.components) {
- if (comp.toLowerCase().includes(lower)) {
- substringMatches.push({pkg, comp});
- }
- }
- }
+ /** @type {SearchItem[]} */
+ const installedComponents = packages.flatMap(pkg =>
+ pkg.components.map(name => ({
+ package: pkg.name,
+ kind: /** @type {const} */ ('component'),
+ name,
+ installed: true,
+ })),
+ );
- if (substringMatches.length === 1) {
- const match = substringMatches[0];
- const result = findComponent([match.pkg], match.comp);
- if (result) return await docFromResult(result, {lang, zh});
- }
+ const ranked = [...installedComponents, ...items]
+ .filter(item => (type == null ? true : item.kind === type))
+ .filter(item =>
+ only === 'installed'
+ ? item.installed
+ : only === 'available'
+ ? !item.installed
+ : true,
+ )
+ .map(item => ({item, score: rank(item, lower)}))
+ .filter(
+ /** @returns {m is {item: SearchItem, score: number}} */
+ m => m.score != null,
+ )
+ .sort(
+ (a, b) =>
+ a.score - b.score ||
+ Number(b.item.installed) - Number(a.item.installed) ||
+ KIND_ORDER.indexOf(a.item.kind) - KIND_ORDER.indexOf(b.item.kind) ||
+ a.item.package.localeCompare(b.item.package) ||
+ a.item.name.localeCompare(b.item.name),
+ );
- if (substringMatches.length > 1) {
+ if (ranked.length > 0) {
+ const matches = ranked.map(({item}) => ({
+ package: item.package,
+ component: item.name,
+ kind: item.kind,
+ installed: item.installed,
+ ...(item.title ? {title: item.title} : {}),
+ ...(item.summary ? {summary: item.summary} : {}),
+ }));
+ const shown = limit == null ? matches : matches.slice(0, limit);
return {
type: 'discover.search',
data: {
query,
- matches: substringMatches.map(m => ({
- package: m.pkg.name,
- component: m.comp,
- })),
+ matches: shown,
+ ...(shown.length < matches.length ? {total: matches.length} : {}),
},
};
}
- // Fuzzy fallback
- const allComponents =
- /** @type {Array<{pkg: ScannedPackage, comp: string}>} */ ([]);
- for (const pkg of packages) {
- for (const comp of pkg.components) {
- allComponents.push({pkg, comp});
- }
- }
- const fuzzyMatches = allComponents
- .map(item => ({
- ...item,
- distance: levenshteinDistance(lower, item.comp.toLowerCase()),
+ // Fuzzy fallback over installed components.
+ const fuzzyMatches = installedComponents
+ .map(entry => ({
+ ...entry,
+ distance: levenshteinDistance(lower, entry.name.toLowerCase()),
}))
.filter(m => m.distance <= 3)
.sort((a, b) => a.distance - b.distance)
@@ -104,7 +150,7 @@ export async function search(packages, query, {lang, zh}) {
throw new AstryxError(
`"${query}" not found`,
fuzzyMatches.map(m => ({
- name: m.pkg.name + '/' + m.comp,
+ name: m.package + '/' + m.name,
reason: 'similar name',
})),
ERROR_CODES.ERR_NOT_FOUND,
diff --git a/packages/cli/api/discover/search/search.test.mjs b/packages/cli/api/discover/search/search.test.mjs
index 57e68df6c7..70249cdd60 100644
--- a/packages/cli/api/discover/search/search.test.mjs
+++ b/packages/cli/api/discover/search/search.test.mjs
@@ -1,8 +1,8 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Colocated tests for the discover.search leaf. Exact/single matches load
- * a real `.doc.mjs`, so these drive a small temp docs directory.
+ * @file Colocated tests for the discover.search leaf, over a small temp docs
+ * directory shaped like a scanned package.
*/
import {describe, it, expect, beforeAll, afterAll} from 'vitest';
@@ -47,16 +47,31 @@ afterAll(() => {
});
describe('discover.search leaf', () => {
- it('an exact component name resolves to its docs', async () => {
+ it('lists an exact component name first, with every other match', async () => {
const res = await search(packages, 'Alpha', {});
- expect(res.type).toBe('discover.detail.doc');
- expect(res.data.name).toBe('Alpha');
+ expect(res.type).toBe('discover.search');
+ expect(res.data.matches.map(m => m.component)).toEqual([
+ 'Alpha',
+ 'AlphaCard',
+ ]);
});
- it('a single substring match resolves to its docs', async () => {
+ it('lists a single match too, so the response type never depends on the data', async () => {
const res = await search(packages, 'card', {});
- expect(res.type).toBe('discover.detail.doc');
- expect(res.data.name).toBe('AlphaCard');
+ expect(res).toEqual({
+ type: 'discover.search',
+ data: {
+ query: 'card',
+ matches: [
+ {
+ package: '@acme/widgets',
+ component: 'AlphaCard',
+ kind: 'component',
+ installed: true,
+ },
+ ],
+ },
+ });
});
it('multiple substring matches return a search response', async () => {
@@ -66,8 +81,18 @@ describe('discover.search leaf', () => {
data: {
query: 'alph',
matches: [
- {package: '@acme/widgets', component: 'Alpha'},
- {package: '@acme/widgets', component: 'AlphaCard'},
+ {
+ package: '@acme/widgets',
+ component: 'Alpha',
+ kind: 'component',
+ installed: true,
+ },
+ {
+ package: '@acme/widgets',
+ component: 'AlphaCard',
+ kind: 'component',
+ installed: true,
+ },
],
},
});
@@ -116,3 +141,112 @@ describe('discover.search leaf — empty query (parity with api/search)', () =>
});
});
});
+
+describe('discover.search leaf across every kind and source', () => {
+ /** @type {any[]} */
+ const items = [
+ {
+ package: '@acme/widgets',
+ kind: 'template',
+ name: 'pages/AlphaHome',
+ installed: true,
+ },
+ {
+ package: '@acme/charts',
+ kind: 'package',
+ name: '@acme/charts',
+ installed: false,
+ description: 'Charts for alpha dashboards',
+ },
+ {
+ package: '@acme/charts',
+ kind: 'component',
+ name: 'AlphaChart',
+ installed: false,
+ },
+ {
+ package: '@acme/charts',
+ kind: 'doc',
+ name: 'guide',
+ installed: false,
+ summary: 'How to chart',
+ },
+ ];
+
+ it('ranks every match by how closely its name matches, installed first among equals', async () => {
+ const res = await search(packages, 'alph', {items});
+ expect(res.type).toBe('discover.search');
+ expect(
+ res.data.matches.map(m => [m.kind, m.component, m.installed]),
+ ).toEqual([
+ ['component', 'Alpha', true],
+ ['component', 'AlphaCard', true],
+ ['component', 'AlphaChart', false],
+ ['template', 'pages/AlphaHome', true],
+ ['package', '@acme/charts', false],
+ ]);
+ });
+
+ it('lists an exact installed component name with the matches from every source', async () => {
+ const res = await search(packages, 'Alpha', {items});
+ expect(res.type).toBe('discover.search');
+ expect(res.data.matches[0]).toEqual({
+ package: '@acme/widgets',
+ component: 'Alpha',
+ kind: 'component',
+ installed: true,
+ });
+ expect(res.data.matches.map(m => m.component)).toContain('AlphaChart');
+ });
+
+ it('lists a single partial component match when other items match too', async () => {
+ const res = await search(packages, 'card', {
+ items: [
+ ...items,
+ {
+ package: '@acme/charts',
+ kind: 'template',
+ name: 'pages/CardGrid',
+ installed: false,
+ },
+ ],
+ });
+ expect(res.type).toBe('discover.search');
+ expect(res.data.matches.map(m => m.component)).toEqual([
+ 'AlphaCard',
+ 'pages/CardGrid',
+ ]);
+ });
+
+ it('lists one installed component when nothing else matches', async () => {
+ const res = await search(packages, 'card', {items});
+ expect(res.type).toBe('discover.search');
+ expect(res.data.matches.map(m => m.component)).toEqual(['AlphaCard']);
+ });
+
+ it('keeps one kind with type, and one side with only', async () => {
+ const templates = await search(packages, 'alph', {items, type: 'template'});
+ expect(templates.data.matches.map(m => m.component)).toEqual([
+ 'pages/AlphaHome',
+ ]);
+ const available = await search(packages, 'alph', {
+ items,
+ only: 'available',
+ });
+ expect(available.data.matches.map(m => m.component)).toEqual([
+ 'AlphaChart',
+ '@acme/charts',
+ ]);
+ });
+
+ it('caps the list at limit and reports the total', async () => {
+ const res = await search(packages, 'alph', {items, limit: 2});
+ expect(res.data.matches).toHaveLength(2);
+ expect(res.data.total).toBe(5);
+ });
+
+ it('matches titles, summaries, keywords, and descriptions too', async () => {
+ const res = await search(packages, 'how to chart', {items});
+ expect(res.data.matches.map(m => m.component)).toEqual(['guide']);
+ });
+});
diff --git a/packages/cli/assets/docs/tree/integrations.doc.mjs b/packages/cli/assets/docs/tree/integrations.doc.mjs
index cda2fc1b84..92a2920eab 100644
--- a/packages/cli/assets/docs/tree/integrations.doc.mjs
+++ b/packages/cli/assets/docs/tree/integrations.doc.mjs
@@ -440,6 +440,25 @@ export const docs = {
},
],
},
+ {
+ title: 'Discover source',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: '`astryx discover` lists the integrations an app has and, through discover sources, the ones it could add, with every version and what each one adds. An integration can supply a source by exporting an async function named `discover` from its integration module. Like `debug`, it is a named export, not a manifest field, so a CLI that predates it simply does not read it.',
+ },
+ {
+ type: 'code',
+ lang: 'typescript',
+ code: "// astryx.integration.ts\nimport type {DiscoverSource} from '@astryxdesign/cli/authoring';\n\nexport const discover: DiscoverSource = async ({signal, package: name, version}) => {\n // Every package you know about, each with every version and what the\n // requested (else latest) version adds.\n return readCatalog({signal, name, version});\n};\n\nexport default {\n components: './components',\n};",
+ },
+ {
+ type: 'prose',
+ text: 'A project can set the same function as `discover` in `astryx.config`. Discover calls every source, the project one first and then each integration in load order, and one that throws, runs past 30 seconds, or returns an invalid catalog never hides the others. It keeps the last good answer from each source in the per-user cache and uses it, with its date, when the source cannot be reached. Discover only reads: it prints the command that adds a package and never runs it. `astryx docs authoring discover-source` has the catalog shape.',
+ },
+ ],
+ },
{
title: 'How It Works',
category: 'guide',
@@ -450,7 +469,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'Runtime integration features — `debug` and `gapReport` — use named exports from the integration module rather than fields in the default manifest. The CLI discovers them alongside the manifest but loads them through the composition rules in `spec:AST-031`: every configured handler runs additively, each in isolation with its own copy of the event.',
+ text: 'Runtime integration features — `debug`, `gapReport`, and `discover` — use named exports from the integration module rather than fields in the default manifest. The CLI discovers them alongside the manifest but loads them through the composition rules in `spec:AST-031`: every configured handler runs additively, each in isolation with its own copy of the event.',
},
{
type: 'prose',
diff --git a/packages/cli/authoring/config/config.doc.mjs b/packages/cli/authoring/config/config.doc.mjs
index 5cca18c4e0..cc53bc9116 100644
--- a/packages/cli/authoring/config/config.doc.mjs
+++ b/packages/cli/authoring/config/config.doc.mjs
@@ -60,6 +60,14 @@ export const doc = {
example:
"{ audience: 'internal', async handle(report, {signal}) { return sendGap(report, {signal}); } }",
},
+ {
+ name: 'discover',
+ type: 'DiscoverSource',
+ description:
+ 'Tell `astryx discover` which integrations this project could add: an async function that returns a catalog. An integration can provide one too, as a `discover` named export from its manifest. Discover calls every source, yours first, and one that fails never hides the others. Discover only reads; your package manager installs.',
+ example:
+ "async ({signal, package: name, version}) => fetchCatalog({signal, name, version})",
+ },
{
name: 'experimental',
type: '{ xle?: { components?: Record<string, XleComponent> } }',
diff --git a/packages/cli/authoring/config/parse.mjs b/packages/cli/authoring/config/parse.mjs
index e904ac407e..f247f74aad 100644
--- a/packages/cli/authoring/config/parse.mjs
+++ b/packages/cli/authoring/config/parse.mjs
@@ -12,6 +12,7 @@
import {z} from 'zod';
import {formatZodError} from '../_shared/errors.mjs';
import {parseGapReportHandler} from '../gap-report/parse.mjs';
+import {parseDiscoverSource} from '../discover/parse.mjs';
/** @typedef {import('./type.js').AstryxConfig} AstryxConfig */
/** @typedef {import('./type.js').PostCodemodHook} PostCodemodHook */
@@ -19,6 +20,7 @@ import {parseGapReportHandler} from '../gap-report/parse.mjs';
/** @typedef {import('./type.js').DebugConfig} DebugConfig */
/** @typedef {import('../debug/type.js').DebugEventHandler} DebugEventHandler */
/** @typedef {import('../gap-report/type.js').GapReportHandler} GapReportHandler */
+/** @typedef {import('../discover/type.js').DiscoverSource} DiscoverSource */
// Typed `z.custom` so `z.infer` reproduces the real function type (not `unknown`).
const buildCommand = /** @type {z.ZodType<PostCodemodHook['buildCommand']>} */ (
@@ -66,6 +68,22 @@ const gapReportHandlerSchema = /** @type {z.ZodType<GapReportHandler>} */ (
)
);
+// The same check an integration's `discover` named export passes. Typed
+// z.custom preserves the public function type.
+const discoverSourceSchema = /** @type {z.ZodType<DiscoverSource>} */ (
+ z.custom(
+ value => {
+ try {
+ parseDiscoverSource(value, 'discover');
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ {message: 'Expected a discover source function'},
+ )
+);
+
const configSchema = z
.object({
integrations: z.array(z.string()).optional(),
@@ -76,6 +94,7 @@ const configSchema = z
.optional(),
debug: debugSchema.optional(),
gapReport: gapReportHandlerSchema.optional(),
+ discover: discoverSourceSchema.optional(),
experimental: z
.object({
xle: z
diff --git a/packages/cli/authoring/config/parse.test.mjs b/packages/cli/authoring/config/parse.test.mjs
index 54f6969d91..5b147ed9aa 100644
--- a/packages/cli/authoring/config/parse.test.mjs
+++ b/packages/cli/authoring/config/parse.test.mjs
@@ -63,6 +63,14 @@ describe('parseConfig (load boundary)', () => {
).toEqual({audience: 'internal', handle});
});
+ it('accepts a discover source function and refuses anything else', () => {
+ const discover = async () => ({});
+ expect(parseConfig({discover}).discover).toBe(discover);
+ expect(reason({discover: 'https://example.com/catalog.json'})).toContain(
+ 'discover',
+ );
+ });
+
it('rejects obsolete or extended gap-report handler shapes', () => {
expect(reason({gapReport: {command: './report.mjs'}})).toContain(
'gapReport',
diff --git a/packages/cli/authoring/config/type.ts b/packages/cli/authoring/config/type.ts
index 7238e71bd3..0926d65ec8 100644
--- a/packages/cli/authoring/config/type.ts
+++ b/packages/cli/authoring/config/type.ts
@@ -11,6 +11,7 @@
import type {DebugEventHandler} from '../debug/type.js';
import type {GapReportHandler} from '../gap-report/type.js';
+import type {DiscoverSource} from '../discover/type.js';
/**
* A command to run as part of a post-codemod hook. Returned by a hook's
@@ -96,6 +97,16 @@ export interface AstryxConfig {
debug?: DebugConfig;
/** Route gap reports through a project-owned handler. See {@link GapReportHandler}. */
gapReport?: GapReportHandler;
+ /**
+ * Tell `astryx discover` about integrations this project could add. See
+ * {@link DiscoverSource}.
+ *
+ * An integration can provide a source too, as a `discover` named export from
+ * its `astryx.integration.*` module. Discover calls every source: this one
+ * first, then each integration's in load order, and one that fails never
+ * hides the others.
+ */
+ discover?: DiscoverSource;
/**
* EXPERIMENTAL — shape may change and is not part of the stable config
* contract. Provisional home for features still being proven out.
diff --git a/packages/cli/authoring/discover/discover.doc.mjs b/packages/cli/authoring/discover/discover.doc.mjs
new file mode 100644
index 0000000000..1b338575ff
--- /dev/null
+++ b/packages/cli/authoring/discover/discover.doc.mjs
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for DiscoverSource, the function `astryx discover` calls to
+ * learn which integrations a project could add.
+ * @input The DiscoverSource type and the catalog types beside it (`type.ts`),
+ * which `parse.mjs` validates.
+ * @output The `discover-source` section of `astryx docs authoring`.
+ * @position packages/cli/authoring/discover — schema documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'discover-source',
+ displayName: 'DiscoverSource',
+ namespace: 'authoring',
+ description:
+ 'A source for `astryx discover`: an async function that returns a catalog of packages a project could add, their versions, and what each version adds. Set it as `discover` in astryx.config, or export it as `discover` from an integration manifest. Discover calls every source, the project one first, and one that throws, runs past 30 seconds, or returns an invalid catalog never hides the others; discover then uses the last good answer it saved for that source. Discover only reads: it prints the command that adds a package and never runs it.',
+ appliesTo:
+ '`discover` in astryx.config.*, or the `discover` named export of astryx.integration.*',
+ fields: [
+ {
+ name: 'context',
+ type: 'DiscoverSourceContext',
+ description: 'The one argument the source is called with.',
+ required: true,
+ fields: [
+ {
+ name: 'context.signal',
+ type: 'AbortSignal',
+ description: 'Aborted when the source runs past 30 seconds.',
+ required: true,
+ },
+ {
+ name: 'context.package',
+ type: 'string',
+ description:
+ 'Set when discover shows one package: return that package with every version.',
+ },
+ {
+ name: 'context.version',
+ type: 'string',
+ description:
+ "With `package`: return that version's contributions. Without it, the latest release's.",
+ },
+ ],
+ },
+ {
+ name: 'returns',
+ type: 'Promise<DiscoverCatalog>',
+ description:
+ 'The catalog. Discover checks it, ignores fields and item kinds it does not know, and refuses any schemaVersion but 1.',
+ required: true,
+ fields: [
+ {
+ name: 'schemaVersion',
+ type: '1',
+ description: 'Version of the catalog shape.',
+ required: true,
+ },
+ {
+ name: 'source',
+ type: '{name: string, generatedAt: string, complete: boolean}',
+ description:
+ 'Who answered, when the data was produced (ISO 8601), and false when the source knows its list is partial.',
+ required: true,
+ },
+ {
+ name: 'packages',
+ type: 'DiscoverPackage[]',
+ description:
+ 'One entry per npm package. When two sources list the same package, the earlier source wins.',
+ required: true,
+ fields: [
+ {
+ name: 'packages[].package',
+ type: 'string',
+ description: 'The npm name.',
+ required: true,
+ },
+ {
+ name: 'packages[].integration',
+ type: 'string',
+ description:
+ 'Shared by every npm name that publishes the same integration. Discover lists an integration once.',
+ required: true,
+ },
+ {
+ name: 'packages[].aliases',
+ type: 'string[]',
+ description:
+ "The integration's other npm names. Discover never offers a package the project has under another name.",
+ required: true,
+ },
+ {
+ name: 'packages[].description',
+ type: 'string',
+ description: 'One line, for the list and search.',
+ },
+ {
+ name: 'packages[].latest',
+ type: 'string | null',
+ description: 'The latest release. Null when there are only prereleases.',
+ required: true,
+ },
+ {
+ name: 'packages[].versions',
+ type: 'DiscoverVersion[]',
+ description:
+ 'Every version, newest first: `{version, publishedAt, prerelease, status}`, where status is `ok` or why the version could not be read.',
+ required: true,
+ },
+ {
+ name: 'packages[].contributions',
+ type: 'DiscoverContribution[]',
+ description:
+ "What the requested (else latest) version adds: `{kind, name, title?, summary?, keywords?}`, where kind is `component`, `template`, `doc`, `theme`, `codemod`, or `agent-doc` (a DiscoverKind) and name is the name the CLI uses for it.",
+ required: true,
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ examples: [
+ {
+ label: 'A project source in astryx.config',
+ code:
+ 'export default {\n' +
+ ' async discover({signal, package: name, version}) {\n' +
+ ' const res = await fetch(catalogUrl(name, version), {signal});\n' +
+ ' return res.json();\n' +
+ ' },\n' +
+ '};',
+ },
+ ],
+};
diff --git a/packages/cli/authoring/discover/parse.mjs b/packages/cli/authoring/discover/parse.mjs
new file mode 100644
index 0000000000..c51af0bbf9
--- /dev/null
+++ b/packages/cli/authoring/discover/parse.mjs
@@ -0,0 +1,128 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Runtime checks for discover sources and the catalogs they return.
+ *
+ * The catalog schema is deliberately not strict: a source may add fields this
+ * CLI does not know, and they are dropped. An unknown `schemaVersion` is
+ * refused, and an item of a kind this CLI does not know is skipped, so a newer
+ * source never breaks an older CLI.
+ *
+ * @position packages/cli/authoring/discover — parse + validate, no I/O.
+ */
+
+import {z} from 'zod';
+
+/** Item kinds a catalog may list, in display order. */
+export const DISCOVER_KINDS = /** @type {const} */ ([
+ 'component',
+ 'template',
+ 'doc',
+ 'theme',
+ 'codemod',
+ 'agent-doc',
+]);
+
+const text = (/** @type {number} */ max) => z.string().min(1).max(max);
+
+const contributionSchema = z.object({
+ kind: text(32),
+ name: text(512),
+ title: z.string().max(512).optional(),
+ summary: z.string().max(4096).optional(),
+ keywords: z.array(z.string().max(128)).max(64).optional(),
+});
+
+const versionSchema = z.object({
+ version: text(256),
+ publishedAt: z.string().max(64).nullable(),
+ prerelease: z.boolean(),
+ status: text(64),
+});
+
+const packageSchema = z.object({
+ package: text(214),
+ integration: text(214),
+ aliases: z.array(text(214)).max(64),
+ description: z.string().max(1024).optional(),
+ latest: text(256).nullable(),
+ versions: z.array(versionSchema).max(50_000),
+ contributions: z.array(contributionSchema).max(50_000),
+});
+
+const catalogSchema = z.object({
+ schemaVersion: z.literal(1),
+ source: z.object({
+ name: text(256),
+ generatedAt: text(64),
+ complete: z.boolean(),
+ }),
+ packages: z.array(packageSchema).max(20_000),
+});
+
+/**
+ * Newest first by publish time. A version with no known publish time goes
+ * last, and ties fall back to the version number.
+ * @param {{version: string, publishedAt: string | null}} a
+ * @param {{version: string, publishedAt: string | null}} b
+ */
+function newestFirst(a, b) {
+ const at = Date.parse(a.publishedAt ?? '');
+ const bt = Date.parse(b.publishedAt ?? '');
+ if (Number.isNaN(at) !== Number.isNaN(bt)) return Number.isNaN(at) ? 1 : -1;
+ if (!Number.isNaN(at) && at !== bt) return bt - at;
+ return b.version.localeCompare(a.version, 'en', {numeric: true});
+}
+
+/**
+ * Check a catalog a discover source returned. Throws an Error naming the first
+ * problem. Items of a kind this CLI does not know are dropped, and versions are
+ * put newest first whatever order the source used.
+ *
+ * @param {unknown} value
+ * @param {string} [label]
+ * @returns {import('./type.js').DiscoverCatalog}
+ */
+export function parseDiscoverCatalog(value, label = 'discover source') {
+ const version =
+ value != null && typeof value === 'object'
+ ? /** @type {{schemaVersion?: unknown}} */ (value).schemaVersion
+ : undefined;
+ if (version !== undefined && version !== 1) {
+ throw new Error(
+ `${label} returned schemaVersion ${String(version)}; this CLI reads schemaVersion 1`,
+ );
+ }
+ const parsed = catalogSchema.safeParse(value);
+ if (!parsed.success) {
+ const issue = parsed.error.issues[0];
+ const where = issue?.path.length ? ` at ${issue.path.join('.')}` : '';
+ throw new Error(
+ `${label} returned an invalid catalog${where}: ${issue?.message}`,
+ );
+ }
+ const known = /** @type {readonly string[]} */ (DISCOVER_KINDS);
+ return /** @type {import('./type.js').DiscoverCatalog} */ ({
+ ...parsed.data,
+ packages: parsed.data.packages.map(pkg => ({
+ ...pkg,
+ versions: [...pkg.versions].sort(newestFirst),
+ contributions: pkg.contributions.filter(c => known.includes(c.kind)),
+ })),
+ });
+}
+
+/**
+ * Check a discover source itself: an async function, like `debug`, that takes
+ * `{signal, package?, version?}` and resolves to a catalog.
+ *
+ * @param {unknown} value
+ * @param {string} label
+ * @returns {import('./type.js').DiscoverSource}
+ */
+export function parseDiscoverSource(value, label) {
+ if (typeof value !== 'function') {
+ throw new Error(`${label} must be a function`);
+ }
+ return /** @type {import('./type.js').DiscoverSource} */ (value);
+}
diff --git a/packages/cli/authoring/discover/parse.test.mjs b/packages/cli/authoring/discover/parse.test.mjs
new file mode 100644
index 0000000000..f30578a3eb
--- /dev/null
+++ b/packages/cli/authoring/discover/parse.test.mjs
@@ -0,0 +1,124 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the discover source and catalog checks.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ DISCOVER_KINDS,
+ parseDiscoverCatalog,
+ parseDiscoverSource,
+} from './parse.mjs';
+
+function catalog(overrides = {}) {
+ return {
+ schemaVersion: 1,
+ source: {
+ name: 'Acme catalog',
+ generatedAt: '2026-09-30T14:00:00.000Z',
+ complete: true,
+ },
+ packages: [
+ {
+ package: '@acme/ui',
+ integration: 'acme-ui',
+ aliases: [],
+ latest: '2.0.0',
+ versions: [
+ {
+ version: '2.0.0',
+ publishedAt: '2026-09-29T00:00:00.000Z',
+ prerelease: false,
+ status: 'ok',
+ },
+ ],
+ contributions: [{kind: 'component', name: 'Button'}],
+ },
+ ],
+ ...overrides,
+ };
+}
+
+describe('parseDiscoverCatalog', () => {
+ it('accepts a catalog', () => {
+ expect(parseDiscoverCatalog(catalog())).toEqual(catalog());
+ });
+
+ it('drops fields it does not know, so a newer source still works', () => {
+ const parsed = parseDiscoverCatalog({...catalog(), cursor: 'next'});
+ expect(parsed).not.toHaveProperty('cursor');
+ });
+
+ it('drops items of a kind it does not know', () => {
+ const value = catalog();
+ value.packages[0].contributions.push({kind: 'widget', name: 'Spinner'});
+ expect(parseDiscoverCatalog(value).packages[0].contributions).toEqual([
+ {kind: 'component', name: 'Button'},
+ ]);
+ });
+
+ it('puts versions newest first whatever order the source used', () => {
+ const value = catalog();
+ value.packages[0].versions = [
+ {
+ version: '1.0.0',
+ publishedAt: '2026-01-05T00:00:00.000Z',
+ prerelease: false,
+ status: 'ok',
+ },
+ {version: '1.5.0', publishedAt: null, prerelease: false, status: 'ok'},
+ {
+ version: '2.0.0',
+ publishedAt: '2026-09-29T00:00:00.000Z',
+ prerelease: false,
+ status: 'ok',
+ },
+ {
+ version: '2.0.0-rc.1',
+ publishedAt: '2026-09-01T00:00:00.000Z',
+ prerelease: true,
+ status: 'ok',
+ },
+ ];
+ expect(
+ parseDiscoverCatalog(value).packages[0].versions.map(v => v.version),
+ ).toEqual(['2.0.0', '2.0.0-rc.1', '1.0.0', '1.5.0']);
+ });
+
+ it('refuses a schemaVersion it does not read', () => {
+ expect(() => parseDiscoverCatalog(catalog({schemaVersion: 2}))).toThrow(
+ 'this CLI reads schemaVersion 1',
+ );
+ });
+
+ it('names the first problem and where it is', () => {
+ expect(() =>
+ parseDiscoverCatalog(catalog({packages: [{package: ''}]}), 'the source'),
+ ).toThrow(/^the source returned an invalid catalog at packages\.0\./);
+ });
+
+ it('lists the kinds in display order', () => {
+ expect(DISCOVER_KINDS).toEqual([
+ 'component',
+ 'template',
+ 'doc',
+ 'theme',
+ 'codemod',
+ 'agent-doc',
+ ]);
+ });
+});
+
+describe('parseDiscoverSource', () => {
+ it('accepts a function', () => {
+ const source = async () => catalog();
+ expect(parseDiscoverSource(source, 'discover')).toBe(source);
+ });
+
+ it('refuses anything else, such as a URL', () => {
+ expect(() =>
+ parseDiscoverSource('https://example.com/catalog.json', 'discover'),
+ ).toThrow('discover must be a function');
+ });
+});
diff --git a/packages/cli/authoring/discover/type.ts b/packages/cli/authoring/discover/type.ts
new file mode 100644
index 0000000000..352ffe30b6
--- /dev/null
+++ b/packages/cli/authoring/discover/type.ts
@@ -0,0 +1,87 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Public type surface for discover sources.
+ *
+ * A discover source tells `astryx discover` which integrations exist beyond the
+ * ones a project already has. A project sets one as `discover` in
+ * `astryx.config`; an integration exports one as a `discover` NAMED export from
+ * its manifest. Discover calls every source, checks each answer, keeps a saved
+ * copy of the last good one, and never installs, enables, or runs anything a
+ * catalog names.
+ */
+
+/** Kinds of item a package can add. */
+export type DiscoverKind =
+ 'component' | 'template' | 'doc' | 'theme' | 'codemod' | 'agent-doc';
+
+/** One item a package version adds. */
+export interface DiscoverContribution {
+ kind: DiscoverKind;
+ /**
+ * The name the CLI uses for it: a component name, template id, doc topic,
+ * theme slug, or codemod id.
+ */
+ name: string;
+ title?: string;
+ summary?: string;
+ keywords?: string[];
+}
+
+/** One published version of a package. */
+export interface DiscoverVersion {
+ version: string;
+ /** ISO 8601 publish time, or null when the source does not know it. */
+ publishedAt: string | null;
+ prerelease: boolean;
+ /** `ok`, or why the source could not read this version. */
+ status: string;
+}
+
+/** One npm package a source knows about. */
+export interface DiscoverPackage {
+ package: string;
+ /** Shared by every npm name that publishes the same integration. */
+ integration: string;
+ /** The integration's other npm names. Discover never offers one the project has. */
+ aliases: string[];
+ description?: string;
+ /** The latest release, or null when the package has only prereleases. */
+ latest: string | null;
+ /** Every version, newest first. */
+ versions: DiscoverVersion[];
+ /** What the requested version adds, or the latest when none was requested. */
+ contributions: DiscoverContribution[];
+}
+
+/** What a discover source returns. */
+export interface DiscoverCatalog {
+ schemaVersion: 1;
+ source: {
+ /** Shown to people, for example "Acme catalog". */
+ name: string;
+ /** ISO 8601 time the source's data was produced. */
+ generatedAt: string;
+ /** False when the source knows its list is partial. */
+ complete: boolean;
+ };
+ packages: DiscoverPackage[];
+}
+
+/** One call to a discover source. */
+export interface DiscoverSourceContext {
+ /** Aborted when the source exceeds its 30-second budget. */
+ readonly signal: AbortSignal;
+ /** Asks for one package: every version, and `version`'s contributions. */
+ readonly package?: string;
+ /** With `package`: the version whose contributions to return. Defaults to the latest. */
+ readonly version?: string;
+}
+
+/**
+ * A discover source: an async function, like `debug`. Set it as `discover` in
+ * astryx.config, or export it as `discover` from an integration manifest.
+ */
+export type DiscoverSource = (
+ context: DiscoverSourceContext,
+) => Promise<DiscoverCatalog>;
diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.ts
index fd7b038591..89843a7c83 100644
--- a/packages/cli/authoring/index.d.ts
+++ b/packages/cli/authoring/index.d.ts
@@ -44,6 +44,15 @@ export type {
GapReportTarget,
GapReportHandlerReceipt,
} from './gap-report/type.js'; // gap-report handler contract
+export type {
+ DiscoverSource,
+ DiscoverSourceContext,
+ DiscoverCatalog,
+ DiscoverPackage,
+ DiscoverVersion,
+ DiscoverContribution,
+ DiscoverKind,
+} from './discover/type.js'; // discover source contract
export type {AstryxCodemod, AstryxConfigCodemod} from './codemod/type.js'; // codemods/*
// ═══════════════════════════════════════════════════════════════════════
@@ -67,6 +76,7 @@ export {
parseGapReportHandler,
parseGapReportReceipt,
} from './gap-report/parse.mjs';
+export {parseDiscoverCatalog} from './discover/parse.mjs';
export {parseCodemod} from './codemod/parse.mjs';
export {parseDebugEvent} from './debug/parse.mjs';
diff --git a/packages/cli/authoring/index.mjs b/packages/cli/authoring/index.mjs
index 8c4ae8ffcf..5698c0ca7e 100644
--- a/packages/cli/authoring/index.mjs
+++ b/packages/cli/authoring/index.mjs
@@ -20,6 +20,7 @@ export {
parseGapReportHandler,
parseGapReportReceipt,
} from './gap-report/parse.mjs';
+export {parseDiscoverCatalog} from './discover/parse.mjs';
export {parseCodemod} from './codemod/parse.mjs';
export {parseDebugEvent} from './debug/parse.mjs';
export {parseDoc} from './doctypes/parse.mjs';
diff --git a/packages/cli/clients/cli/commands/discover.doc.mjs b/packages/cli/clients/cli/commands/discover.doc.mjs
index 8f5869bd70..da7442d053 100644
--- a/packages/cli/clients/cli/commands/discover.doc.mjs
+++ b/packages/cli/clients/cli/commands/discover.doc.mjs
@@ -14,11 +14,13 @@ export const doc = {
name: 'discover',
displayName: 'astryx discover',
namespace: 'cli/commands',
- summary: 'Discover external packages and components',
+ summary:
+ 'Browse and search integrations: the ones you have and the ones you could add',
description:
- 'Explores components contributed by configured external packages and integrations. ' +
- 'With no query it lists those packages; an @scope/name query browses one package; ' +
- 'an @scope/name/Component path or a free-text term resolves to a component doc.',
+ 'Lists the integrations this project loads and, when it has a discover source, the ones it could add, with what each one adds. ' +
+ 'A package query shows one package: what it adds, every version a source knows, and the command that adds it. ' +
+ "An @scope/name/Component path prints an installed component's doc; any other item path shows that item. " +
+ 'Anything else, even an exact component name, searches every item and package and lists the matches. Discover only reads: your package manager installs, updates, and removes packages.',
fn: 'discover',
args: [{name: 'query', param: 'query', required: false}],
options: [
@@ -26,19 +28,61 @@ export const doc = {
flag: '--components',
param: 'options.components',
description:
- 'In the package list, print every component of each package instead of the first 10 and a "+N more" count. No effect on --json output or on a package, component, or search query.',
+ 'In the package list, print every component, and every other item, of each package instead of the first 10 and a "+N more" count. No effect on --json output or on a package, component, or search query.',
+ },
+ {
+ flag: '--type <kind>',
+ param: 'options.type',
+ description:
+ 'Only one kind: component, template, doc, theme, codemod, or agent-doc. In the list, only packages that add it; in a search, only items of that kind.',
+ },
+ {
+ flag: '--installed',
+ param: 'options.installed',
+ description:
+ 'Only what this project has. Cannot be set with --available.',
+ },
+ {
+ flag: '--available',
+ param: 'options.available',
+ description:
+ 'Only what this project could add. Cannot be set with --installed.',
+ },
+ {
+ flag: '--limit <n>',
+ param: 'options.limit',
+ description:
+ 'Max number of search results, a positive integer (default 20).',
},
],
examples: [
- {label: 'List packages', cli: 'astryx discover --json'},
- {label: 'List every component of each package', cli: 'astryx discover --components'},
- {label: 'Browse a package', cli: 'astryx discover @acme/ui'},
+ {
+ label: 'List what you have and what you could add',
+ cli: 'astryx discover',
+ },
+ {
+ label: 'List every component of each package',
+ cli: 'astryx discover --components',
+ },
+ {
+ label: 'Only packages that add themes',
+ cli: 'astryx discover --type theme',
+ },
+ {
+ label: 'Browse a package and its versions',
+ cli: 'astryx discover @acme/ui',
+ },
+ {label: 'See one version', cli: 'astryx discover @acme/[email protected]'},
+ {
+ label: 'Search templates you could add',
+ cli: 'astryx discover dashboard --type template --available',
+ },
],
exitCodes: [
{code: 0, when: 'success'},
{
code: 1,
- when: 'unknown package or component, a malformed doc, or a blank query when packages are discovered',
+ when: 'unknown package, version, component, or item; a malformed doc; an invalid --type or --limit; --installed with --available; or a blank query when packages are discovered',
},
],
related: ['component', 'search', 'template'],
diff --git a/packages/cli/clients/cli/commands/discover.mjs b/packages/cli/clients/cli/commands/discover.mjs
index 17e41cd9e8..cfb142bf3a 100644
--- a/packages/cli/clients/cli/commands/discover.mjs
+++ b/packages/cli/clients/cli/commands/discover.mjs
@@ -1,18 +1,31 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file discover command — find external Astryx packages and components
+ * @file discover command — browse the integrations you have and could add
*
* Usage:
- * astryx discover List all packages
- * astryx discover @scope/name List components in a package
- * astryx discover @scope/name/Component Show docs for a component
- * astryx discover searchterm Search across all packages
+ * astryx discover List installed and available packages
+ * astryx discover @scope/name[@version] One package, with its versions
+ * astryx discover @scope/name/Component Show docs for an installed component
+ * astryx discover @scope/name/<item> One item a package adds
+ * astryx discover searchterm Search every item and package
*/
-import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';
+import {
+ formatFull,
+ formatBrief,
+ formatCompact,
+} from '../lib/component-format.mjs';
import {jsonOut} from '../../../foundation/response/json.mjs';
-import {emit, section, text, record, records, list, code} from '../formatters/index.mjs';
+import {
+ emit,
+ section,
+ text,
+ record,
+ records,
+ list,
+ code,
+} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {discover as discoverApi} from '../../../api/discover/discover.mjs';
import {Project} from '../../../foundation/config/project.mjs';
@@ -23,25 +36,70 @@ import {resultSet} from '../../../foundation/debug/index.mjs';
import {doc as discoverCommand} from './discover.doc.mjs';
import {doc as discoverFn} from '../../../api/discover/discover.doc.mjs';
-// Max components to list inline per package before summarizing with "+N more".
-const MAX_COMPONENTS_SHOWN = 10;
+// Max items to list inline per package before summarizing with "+N more".
+const MAX_ITEMS_SHOWN = 10;
+
+/** @type {Record<string, string>} */
+const KIND_PLURALS = {
+ component: 'components',
+ template: 'templates',
+ doc: 'docs',
+ theme: 'themes',
+ codemod: 'codemods',
+ 'agent-doc': 'agent docs',
+};
+
+// The list fields that hold item names, summarized in the package list.
+const ITEM_FIELDS = [
+ 'components',
+ 'templates',
+ 'docs',
+ 'themes',
+ 'codemods',
+ 'agentDocs',
+];
/**
- * What the run answered with. `discover` browses the integration packages a
- * project has configured, so the top two views count PACKAGES; naming a
- * component inside one answers with that component instead.
- *
- * @param {import('../../../api/discover/discover.type.mjs').DiscoverListResponse
+ * @typedef {import('../../../api/discover/discover.type.mjs').DiscoverListResponse
* | import('../../../api/discover/discover.type.mjs').DiscoverDetailResponse
* | import('../../../api/discover/discover.type.mjs').DiscoverDetailDocResponse
- * | import('../../../api/discover/discover.type.mjs').DiscoverSearchResponse} result
+ * | import('../../../api/discover/discover.type.mjs').DiscoverItemResponse
+ * | import('../../../api/discover/discover.type.mjs').DiscoverSearchResponse} DiscoverResult
+ */
+
+/** @type {Record<string, import('../../../foundation/debug/command-result.mjs').ResultSetKind>} */
+const RESULT_KINDS = {
+ package: 'integration',
+ component: 'component',
+ template: 'template',
+ doc: 'doc',
+ theme: 'theme',
+ codemod: 'migration',
+ 'agent-doc': 'doc',
+};
+
+/**
+ * The run-log kind for a set of item kinds: the one kind, or `mixed`.
+ * @param {string[]} kinds
+ * @returns {import('../../../foundation/debug/command-result.mjs').ResultSetKind}
+ */
+function resultKindOf(kinds) {
+ const mapped = new Set(kinds.map(kind => RESULT_KINDS[kind] ?? 'mixed'));
+ return mapped.size === 1 ? [...mapped][0] : 'mixed';
+}
+
+/**
+ * What the run answered with. The list and package views count PACKAGES;
+ * naming a component or item answers with that item instead.
+ *
+ * @param {DiscoverResult} result
* @returns {import('../../../foundation/debug/command-result.mjs').CommandResult}
*/
function summarize(result) {
switch (result.type) {
case 'discover.list':
return resultSet({
- count: result.data.length,
+ count: result.data.length + (result.meta?.available?.length ?? 0),
resultKind: 'integration',
});
case 'discover.detail':
@@ -52,14 +110,96 @@ function summarize(result) {
});
case 'discover.detail.doc':
return resultSet({count: 1, resultKind: 'component', directMatch: true});
+ case 'discover.item':
+ return resultSet({
+ count: 1,
+ resultKind: resultKindOf([result.data.kind]),
+ directMatch: true,
+ });
case 'discover.search':
return resultSet({
- count: result.data.matches.length,
- resultKind: 'component',
+ count: result.data.total ?? result.data.matches.length,
+ resultKind: resultKindOf(result.data.matches.map(m => m.kind)),
});
}
}
+/**
+ * Record options that summarize each item list to its first names.
+ * @param {boolean} full print every name instead
+ * @returns {import('../formatters/index.mjs').RecordOptions}
+ */
+function itemListOptions(full) {
+ if (full) return {};
+ /** @param {string[]} names */
+ const summary = names => {
+ const shown = names.slice(0, MAX_ITEMS_SHOWN);
+ const remaining = names.length - MAX_ITEMS_SHOWN;
+ return remaining > 0
+ ? `${shown.join(', ')}, +${remaining} more`
+ : shown.join(', ');
+ };
+ return {
+ format: Object.fromEntries(ITEM_FIELDS.map(field => [field, summary])),
+ };
+}
+
+/**
+ * One line per source that did not answer live.
+ * @param {import('../../../api/discover/discover.type.mjs').DiscoverSourceState[]} sources
+ */
+function sourceNotes(sources) {
+ return sources
+ .filter(s => s.status !== 'fresh')
+ .map(s =>
+ s.status === 'saved'
+ ? text(
+ `The discover source from ${s.from} did not answer (${s.error}), so this uses the copy saved ${s.savedAt}.`,
+ )
+ : text(`The discover source from ${s.from} is unavailable: ${s.error}`),
+ );
+}
+
+/**
+ * @param {import('../../../api/discover/discover.type.mjs').DiscoverSourceState[]} sources
+ */
+function sourceSubtitle(sources) {
+ const answered = sources.filter(s => s.status !== 'failed');
+ if (answered.length === 0) return undefined;
+ return (
+ 'from ' +
+ answered
+ .map(
+ s =>
+ `${s.name}${s.generatedAt ? ` (${s.generatedAt.slice(0, 10)})` : ''}`,
+ )
+ .join(', ')
+ );
+}
+
+/**
+ * @param {import('../../../authoring/discover/type').DiscoverVersion[]} versions
+ * @param {{shown?: string, installed?: string, latest?: string}} marks
+ */
+function versionLines(versions, marks) {
+ return versions
+ .filter(v => !v.prerelease || v.version === marks.shown)
+ .map(v => {
+ const tags = [
+ v.version === marks.latest ? 'latest' : '',
+ v.version === marks.installed ? 'installed' : '',
+ v.version === marks.shown &&
+ v.version !== marks.installed &&
+ v.version !== marks.latest
+ ? 'shown'
+ : '',
+ v.status !== 'ok' ? v.status : '',
+ ].filter(Boolean);
+ const date = v.publishedAt ? v.publishedAt.slice(0, 10) : 'date unknown';
+ return `${v.version} ${date}${tags.length ? ` ${tags.join(', ')}` : ''}`;
+ });
+}
+
/**
* @param {import('commander').Command} program
*/
@@ -69,120 +209,255 @@ export function registerDiscover(program) {
action:
/**
* @param {string | undefined} query
- * @param {{components?: boolean}} options
+ * @param {{components?: boolean, type?: string, installed?: boolean, available?: boolean, limit?: string}} options
*/
async (query, options) => {
- const detail = program.opts().detail || 'full';
- const json = program.opts().json || false;
- const lang = program.opts().lang || null;
- const zh = program.opts().zh || false;
- const run = getCliInvocation();
-
- // Non-blocking nudge: if any configured integration has validation
- // issues, print one compact line to stderr pointing at
- // doctor integration validate. Best-effort; suppressed in --json mode.
- try {
- const project = await Project.load(process.cwd());
- await warnOnIntegrationIssues(project, {json});
- } catch {
- // Never let the nudge break the command.
- }
-
- let result;
- try {
- result = await discoverApi(query, {components: options.components, lang, zh});
- } catch (e) {
- const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
- return cliError(err.message, {suggestions: err.suggestions, code: err.code});
- }
-
- const answered = summarize(result);
- if (json) {
- // Forward optional meta (e.g. configured flag for discover.list) as a
- // sibling of data via jsonOut, so the envelope still carries
- // apiVersion and goes through the single sanctioned emit path.
- jsonOut(result);
- return answered;
- }
+ const detail = program.opts().detail || 'full';
+ const json = program.opts().json || false;
+ const lang = program.opts().lang || null;
+ const zh = program.opts().zh || false;
+ const run = getCliInvocation();
+
+ // Non-blocking nudge: if any configured integration has validation
+ // issues, print one compact line to stderr pointing at
+ // doctor integration validate. Best-effort; suppressed in --json mode.
+ try {
+ const project = await Project.load(process.cwd());
+ await warnOnIntegrationIssues(project, {json});
+ } catch {
+ // Never let the nudge break the command.
+ }
+
+ /** @type {DiscoverResult} */
+ let result;
+ try {
+ result = await discoverApi(query, {
+ components: options.components,
+ lang,
+ zh,
+ type: /** @type {any} */ (options.type),
+ installed: options.installed,
+ available: options.available,
+ // Number(), not parseInt(): the API refuses `1.5` and `5abc` itself.
+ limit: options.limit != null ? Number(options.limit) : undefined,
+ });
+ } catch (e) {
+ const err =
+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
+ return cliError(err.message, {
+ suggestions: err.suggestions,
+ code: err.code,
+ });
+ }
+
+ const answered = summarize(result);
+ if (json) {
+ // Forward optional meta (e.g. configured flag for discover.list) as a
+ // sibling of data via jsonOut, so the envelope still carries
+ // apiVersion and goes through the single sanctioned emit path.
+ jsonOut(result);
+ return answered;
+ }
+
+ switch (result.type) {
+ case 'discover.list': {
+ const listOpts = itemListOptions(Boolean(options.components));
+ const available = result.meta?.available;
+ const sources = result.meta?.sources ?? [];
- switch (result.type) {
- case 'discover.list': {
- if (result.data.length === 0) {
- if (result.meta && result.meta.configured === false) {
+ // No discover source: the list of what this project has, as always.
+ if (available === undefined) {
+ if (result.data.length === 0) {
+ if (result.meta && result.meta.configured === false) {
+ emit(
+ text('No integrations configured.'),
+ text('Add integration package names to astryx.config.mjs:'),
+ code(
+ "export default {\n integrations: ['@scope/your-integration'],\n};",
+ ),
+ );
+ } else {
+ emit(
+ text(
+ 'No external components found in configured integrations.',
+ ),
+ );
+ }
+ break;
+ }
emit(
- text('No integrations configured.'),
- text('Add integration package names to astryx.config.mjs:'),
- code(
- "export default {\n integrations: ['@scope/your-integration'],\n};",
+ records(result.data, listOpts),
+ text(
+ [
+ 'Usage:',
+ ` ${run} discover <package> Browse a package`,
+ ` ${run} discover <package>/Component View component docs`,
+ ` ${run} discover <search> Search all packages`,
+ ].join('\n'),
),
);
- } else {
- emit(text('No external components found in configured integrations.'));
+ break;
}
+
+ const kind = options.type
+ ? (KIND_PLURALS[options.type] ?? options.type)
+ : null;
+ /** @type {import('../formatters/index.mjs').Block[]} */
+ const blocks = [];
+ if (!options.available) {
+ blocks.push(section('Installed'));
+ blocks.push(
+ result.data.length > 0
+ ? records(result.data, listOpts)
+ : text(
+ kind
+ ? `None of this project's integrations add ${kind}.`
+ : 'None yet.',
+ ),
+ );
+ }
+ if (!options.installed) {
+ blocks.push(section('Available', sourceSubtitle(sources)));
+ blocks.push(
+ available.length > 0
+ ? records(available, listOpts)
+ : text(
+ !sources.some(s => s.status !== 'failed')
+ ? 'No source answered, so there is nothing to list.'
+ : kind
+ ? `No package you could add adds ${kind}.`
+ : 'Nothing new to add: this project has every integration its sources list.',
+ ),
+ );
+ }
+ blocks.push(...sourceNotes(sources));
+ blocks.push(
+ text(
+ [
+ 'Usage:',
+ ` ${run} discover <package> Browse a package and its versions`,
+ ` ${run} discover <package>/<item> View one item`,
+ ` ${run} discover <search> Search every item and package`,
+ ].join('\n'),
+ ),
+ );
+ emit(...blocks);
break;
}
- // One record per package, every field of the JSON entry. The default
- // view summarizes each package's components (first N + "+N more");
- // --components lists them all (record comma-joins the full array).
- /** @type {import('../formatters/index.mjs').RecordOptions} */
- const listOpts = {};
- if (!options.components) {
- listOpts.format = {
- components: (/** @type {string[]} */ comps) => {
- const shown = comps.slice(0, MAX_COMPONENTS_SHOWN);
- const remaining = comps.length - MAX_COMPONENTS_SHOWN;
- return remaining > 0
- ? `${shown.join(', ')}, +${remaining} more`
- : shown.join(', ');
- },
- };
+ case 'discover.detail': {
+ const d = result.data;
+ /** @type {import('../formatters/index.mjs').Block[]} */
+ const blocks = [record(d, {omit: ['versions', 'install']})];
+ if (d.versions) {
+ const shown = d.version;
+ const lines = versionLines(d.versions, {
+ shown,
+ installed: d.installed
+ ? (d.installedVersion ?? d.version)
+ : undefined,
+ latest: d.latest,
+ });
+ const prereleases = d.versions.filter(v => v.prerelease).length;
+ blocks.push(
+ section(
+ 'Versions',
+ `${d.versions.length} published, newest first`,
+ ),
+ );
+ if (lines.length > 0) blocks.push(list(lines));
+ if (prereleases > 0) {
+ blocks.push(
+ text(
+ `${prereleases === 1 ? '1 prerelease is' : `${prereleases} prereleases are`} not listed. See any version: ${run} discover ${d.name}@<version>`,
+ ),
+ );
+ }
+ }
+ if (d.install) {
+ blocks.push(
+ section('Add it'),
+ code(d.install),
+ text(
+ 'Astryx loads an integration on the next command once it is a dependency.',
+ ),
+ );
+ } else if (d.installedAs) {
+ blocks.push(
+ text(
+ `This project already has this integration as ${d.installedAs}.`,
+ ),
+ );
+ }
+ blocks.push(
+ text(
+ d.installed
+ ? `Usage: ${run} discover ${d.name}/<ComponentName>`
+ : `See one item: ${run} discover ${d.name}/<item>`,
+ ),
+ );
+ emit(...blocks);
+ break;
}
- emit(
- records(result.data, listOpts),
- text(
- [
- 'Usage:',
- ` ${run} discover <package> Browse a package`,
- ` ${run} discover <package>/Component View component docs`,
- ` ${run} discover <search> Search all packages`,
- ].join('\n'),
- ),
- );
- break;
- }
- case 'discover.detail': {
- const d = result.data;
- emit(
- record(d),
- text(`Usage: ${run} discover ${d.name}/<ComponentName>`),
- );
- break;
- }
+ case 'discover.detail.doc': {
+ const docs = result.data;
+ const md =
+ detail === 'brief'
+ ? formatBrief(docs, docs.name, '')
+ : detail === 'compact'
+ ? formatCompact(docs, docs.name, '')
+ : formatFull(docs);
+ emit(code(md));
+ break;
+ }
- case 'discover.detail.doc': {
- const docs = result.data;
- const md =
- detail === 'brief'
- ? formatBrief(docs, docs.name, '')
- : detail === 'compact'
- ? formatCompact(docs, docs.name, '')
- : formatFull(docs);
- emit(code(md));
- break;
- }
+ case 'discover.item': {
+ const d = result.data;
+ emit(
+ record(d, {omit: ['install']}),
+ ...(d.install
+ ? [
+ section('Add it'),
+ code(d.install),
+ text(
+ 'Astryx loads an integration on the next command once it is a dependency.',
+ ),
+ ]
+ : []),
+ text(`Its package: ${run} discover ${d.package}`),
+ );
+ break;
+ }
- case 'discover.search': {
- const {query: q, matches} = result.data;
- emit(
- section(`Found ${matches.length} matches for "${q}"`),
- list(matches.map(m => `${run} discover ${m.package}/${m.component}`)),
- );
- break;
+ case 'discover.search': {
+ const {query: q, matches, total} = result.data;
+ const count = total ?? matches.length;
+ emit(
+ section(
+ `Found ${count} ${count === 1 ? 'match' : 'matches'} for "${q}"`,
+ total != null
+ ? `showing the first ${matches.length}`
+ : undefined,
+ ),
+ list(
+ matches.map(m => {
+ const target =
+ m.kind === 'package'
+ ? m.package
+ : `${m.package}/${m.component}`;
+ const tags = [
+ m.kind && m.kind !== 'component' ? m.kind : '',
+ m.installed === false ? 'not installed' : '',
+ ].filter(Boolean);
+ return `${run} discover ${target}${tags.length ? ` (${tags.join(', ')})` : ''}`;
+ }),
+ ),
+ );
+ break;
+ }
}
- }
- return answered;
- },
+ return answered;
+ },
});
}
diff --git a/packages/cli/clients/cli/commands/discover.sources.test.mjs b/packages/cli/clients/cli/commands/discover.sources.test.mjs
new file mode 100644
index 0000000000..83c29315b5
--- /dev/null
+++ b/packages/cli/clients/cli/commands/discover.sources.test.mjs
@@ -0,0 +1,267 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx discover` with a discover source: the list, a package page, a
+ * search, and the refused option pair, driven through the real CLI against a
+ * hermetic project whose astryx.config sets `discover`. Saved copies go to a
+ * temp cache directory, never the project.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+const CONFIG = `
+const packages = [
+ {
+ package: '@test/kit',
+ integration: 'test-kit',
+ aliases: [],
+ latest: '3.2.0',
+ versions: [
+ {version: '3.2.0', publishedAt: '2026-09-29T00:00:00.000Z', prerelease: false, status: 'ok'},
+ {version: '3.1.4', publishedAt: '2026-09-01T00:00:00.000Z', prerelease: false, status: 'ok'},
+ ],
+ contributions: [{kind: 'component', name: 'Dial'}],
+ },
+ {
+ package: '@test/charts',
+ integration: 'test-charts',
+ aliases: [],
+ latest: '2.0.0',
+ versions: [
+ {version: '2.1.0-beta.1', publishedAt: '2026-09-25T00:00:00.000Z', prerelease: true, status: 'ok'},
+ {version: '2.0.0', publishedAt: '2026-09-20T00:00:00.000Z', prerelease: false, status: 'ok'},
+ ],
+ contributions: [
+ {kind: 'component', name: 'Chart'},
+ {kind: 'template', name: 'pages/Report'},
+ ],
+ },
+ {
+ package: '@test/boards',
+ integration: 'test-boards',
+ aliases: [],
+ latest: '1.0.0',
+ versions: [
+ {version: '1.0.0', publishedAt: '2026-09-10T00:00:00.000Z', prerelease: false, status: 'ok'},
+ ],
+ contributions: [{kind: 'template', name: 'pages/DialBoard'}],
+ },
+];
+
+export default {
+ integrations: ['@test/kit'],
+ async discover({package: name}) {
+ return {
+ schemaVersion: 1,
+ source: {name: 'Test catalog', generatedAt: '2026-09-30T00:00:00.000Z', complete: true},
+ packages: packages.filter(p => name == null || p.package === name),
+ };
+ },
+};
+`;
+
+let tmpDir;
+let project;
+/** @type {Record<string, string | undefined>} */
+let savedEnv;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-discover-sources-'));
+ project = path.join(tmpDir, 'project');
+ const pkgDir = path.join(project, 'node_modules', '@test', 'kit');
+ fs.mkdirSync(path.join(pkgDir, 'components'), {recursive: true});
+ fs.writeFileSync(
+ path.join(project, 'package.json'),
+ JSON.stringify({
+ name: 'proj',
+ version: '1.0.0',
+ dependencies: {'@test/kit': '3.1.4'},
+ }),
+ );
+ fs.writeFileSync(path.join(project, 'astryx.config.mjs'), CONFIG);
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@test/kit', version: '3.1.4'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default {components: './components'};\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'components', 'Dial.doc.mjs'),
+ `export const docs = {name: 'Dial', usage: {description: 'A dial.'}};\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'components', 'Dial.tsx'),
+ `export function Dial() { return null; }\n`,
+ );
+ // The saved copy lives in the per-user cache; point it at the temp dir.
+ savedEnv = {
+ HOME: process.env.HOME,
+ XDG_CACHE_HOME: process.env.XDG_CACHE_HOME,
+ LOCALAPPDATA: process.env.LOCALAPPDATA,
+ };
+ process.env.HOME = path.join(tmpDir, 'home');
+ process.env.XDG_CACHE_HOME = path.join(tmpDir, 'cache');
+ process.env.LOCALAPPDATA = path.join(tmpDir, 'localappdata');
+});
+
+afterEach(() => {
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/** The per-user cache directory this platform uses under the redirected env. */
+function userCacheDir() {
+ if (process.platform === 'win32') {
+ return path.join(tmpDir, 'localappdata', 'astryx', 'Cache');
+ }
+ if (process.platform === 'darwin') {
+ return path.join(tmpDir, 'home', 'Library', 'Caches', 'astryx');
+ }
+ return path.join(tmpDir, 'cache', 'astryx');
+}
+
+describe('astryx discover with a discover source', () => {
+ it('lists what the project has and what it could add, in --json', async () => {
+ const {status, stdout} = await runCli(['discover', '--json'], {
+ cwd: project,
+ });
+
+ expect(status).toBe(0);
+ const {data, meta} = JSON.parse(stdout);
+ expect(data).toEqual([
+ expect.objectContaining({
+ name: '@test/kit',
+ components: ['Dial'],
+ version: '3.1.4',
+ latest: '3.2.0',
+ }),
+ ]);
+ expect(meta.available).toEqual([
+ {
+ name: '@test/charts',
+ components: ['Chart'],
+ version: '2.0.0',
+ templates: ['pages/Report'],
+ source: 'Test catalog',
+ },
+ {
+ name: '@test/boards',
+ components: [],
+ version: '1.0.0',
+ templates: ['pages/DialBoard'],
+ source: 'Test catalog',
+ },
+ ]);
+ expect(meta.sources).toEqual([
+ expect.objectContaining({
+ name: 'Test catalog',
+ from: 'astryx.config',
+ status: 'fresh',
+ }),
+ ]);
+ });
+
+ it('prints both sides as records', async () => {
+ const {status, stdout} = await runCli(['discover'], {cwd: project});
+
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^Installed$/m);
+ expect(stdout).toMatch(/^Available$/m);
+ expect(stdout).toMatch(/^name:\s+@test\/charts$/m);
+ expect(stdout).toMatch(/^latest:\s+3\.2\.0$/m);
+ });
+
+ it('shows a package it does not have with its releases and the command that adds it, and never runs it', async () => {
+ const {status, stdout} = await runCli(['discover', '@test/charts'], {
+ cwd: project,
+ });
+
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^installed:\s+false$/m);
+ expect(stdout).toContain('- 2.0.0 2026-09-20 latest');
+ expect(stdout).not.toContain('2.1.0-beta.1 ');
+ expect(stdout).toContain('1 prerelease is not listed.');
+ // The verb follows the detected package manager.
+ expect(stdout).toMatch(
+ /^(npm install|pnpm add|yarn add|bun add) @test\/charts$/m,
+ );
+ expect(
+ fs.existsSync(path.join(project, 'node_modules', '@test', 'charts')),
+ ).toBe(false);
+ });
+
+ it('says which item is missing from a package only a source lists', async () => {
+ const {status, stdout} = await runCli(
+ ['discover', '@test/charts/Nope', '--json'],
+ {cwd: project},
+ );
+
+ expect(status).toBe(1);
+ const {code, error} = JSON.parse(stdout);
+ expect(code).toBe('ERR_UNKNOWN_COMPONENT');
+ expect(error).toBe('"Nope" not found in @test/charts');
+ });
+
+ it('searches every kind in every source', async () => {
+ const {status, stdout} = await runCli(['discover', 'report', '--json'], {
+ cwd: project,
+ });
+
+ expect(status).toBe(0);
+ expect(JSON.parse(stdout).data.matches).toEqual([
+ {
+ package: '@test/charts',
+ component: 'pages/Report',
+ kind: 'template',
+ installed: false,
+ },
+ ]);
+ });
+
+ it('refuses --installed with --available', async () => {
+ const {status, stdout} = await runCli(
+ ['discover', '--installed', '--available', '--json'],
+ {cwd: project},
+ );
+
+ expect(status).toBe(1);
+ expect(JSON.parse(stdout).code).toBe('ERR_INVALID_OPTION');
+ });
+
+ it('lists every match for a free-text query, even an exact component name, and opens one by its package path', async () => {
+ const exact = await runCli(['discover', 'Dial', '--json'], {cwd: project});
+ const {type, data} = JSON.parse(exact.stdout);
+ expect(type).toBe('discover.search');
+ expect(data.matches.map(m => [m.component, m.installed])).toEqual([
+ ['Dial', true],
+ ['pages/DialBoard', false],
+ ]);
+
+ const opened = await runCli(['discover', '@test/kit/Dial', '--json'], {
+ cwd: project,
+ });
+ expect(JSON.parse(opened.stdout).type).toBe('discover.detail.doc');
+ });
+
+ it('saves the answer in the user cache and writes nothing into the project', async () => {
+ const before = fs.readdirSync(project).sort();
+ await runCli(['discover', '--json'], {cwd: project});
+
+ expect(fs.readdirSync(project).sort()).toEqual(before);
+ expect(fs.existsSync(path.join(project, 'node_modules', '.cache'))).toBe(
+ false,
+ );
+ expect(fs.readdirSync(path.join(userCacheDir(), 'discover'))).toHaveLength(
+ 1,
+ );
+ });
+});
diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjs
index 13dd81b78d..3ee37c17c5 100644
--- a/packages/cli/clients/cli/lib/manifest.mjs
+++ b/packages/cli/clients/cli/lib/manifest.mjs
@@ -69,6 +69,7 @@ export const RESPONSE_TYPES = {
'discover.list',
'discover.detail',
'discover.detail.doc',
+ 'discover.item',
'discover.search',
],
search: ['search'],
diff --git a/packages/cli/foundation/discovery/authoring-self-docs.mjs b/packages/cli/foundation/discovery/authoring-self-docs.mjs
index d49be59625..7e69af012c 100644
--- a/packages/cli/foundation/discovery/authoring-self-docs.mjs
+++ b/packages/cli/foundation/discovery/authoring-self-docs.mjs
@@ -33,6 +33,7 @@ export const AUTHORING_SELF_DOCS = [
'config/config.doc.mjs',
'debug/debug.doc.mjs',
'gap-report/gap-report.doc.mjs',
+ 'discover/discover.doc.mjs',
'codemod/codemod.doc.mjs',
'identity/identity.doc.mjs',
'doctypes/base/graph-fields.doc.mjs',
diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjs
index 7e9df230e7..83ccb30769 100644
--- a/packages/cli/foundation/integrations/integrations.mjs
+++ b/packages/cli/foundation/integrations/integrations.mjs
@@ -29,6 +29,7 @@ import {
} from '../../authoring/integration/schema.mjs';
import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';
import {parseGapReportHandler} from '../../authoring/gap-report/parse.mjs';
+import {parseDiscoverSource} from '../../authoring/discover/parse.mjs';
import {resolveProviders} from './provider-resolution.mjs';
/**
@@ -80,6 +81,9 @@ import {resolveProviders} from './provider-resolution.mjs';
* validated package-owned handler from the `gapReport` NAMED export.
* @property {string} [__gapReportError] isolated named-handler validation error.
* Named exports are not manifest keys — see {@link loadManifest}.
+ * @property {import('../../authoring/discover/type').DiscoverSource} [__discover]
+ * validated catalog source from the `discover` NAMED export.
+ * @property {string} [__discoverError] isolated discover-source validation error.
*/
/** Conventional manifest basenames, in load-precedence order. */
@@ -167,6 +171,23 @@ function parseGapReportHandlerExport(value, label) {
}
}
+/**
+ * Parse the optional named discover source the same way: a malformed one is
+ * isolated from every other contribution and reported by `astryx discover`.
+ *
+ * @param {unknown} value
+ * @param {string} label
+ * @returns {{source?: import('../../authoring/discover/type').DiscoverSource, error?: string}}
+ */
+function parseDiscoverSourceExport(value, label) {
+ if (value === undefined) return {};
+ try {
+ return {source: parseDiscoverSource(value, `${label} named export "discover"`)};
+ } catch (error) {
+ return {error: error instanceof Error ? error.message : String(error)};
+ }
+}
+
/**
* Load and validate a manifest module's default export, while isolating the
* optional `agentDocs` contribution from the manifest's other fields.
@@ -183,7 +204,7 @@ function parseGapReportHandlerExport(value, label) {
* @param {string} file absolute manifest path
* @param {string} [label] used in error messages
* @param {{fresh?: boolean}} [options]
- * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, gapReport?: import('../../authoring/gap-report/type').GapReportHandler, gapReportError?: string, agentDocsError?: string}>}
+ * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, gapReport?: import('../../authoring/gap-report/type').GapReportHandler, gapReportError?: string, discover?: import('../../authoring/discover/type').DiscoverSource, discoverError?: string, agentDocsError?: string}>}
*/
export async function loadManifest(
file,
@@ -194,6 +215,7 @@ export async function loadManifest(
const raw = mod?.default;
const baseManifest = parseIntegrationBase(raw, label);
const gapReport = parseGapReportHandlerExport(mod?.gapReport, label);
+ const discover = parseDiscoverSourceExport(mod?.discover, label);
const hasAgentDocs =
raw != null &&
typeof raw === 'object' &&
@@ -228,6 +250,8 @@ export async function loadManifest(
: undefined,
gapReport: gapReport.handler,
gapReportError: gapReport.error,
+ discover: discover.source,
+ discoverError: discover.error,
agentDocsError,
};
}
@@ -345,6 +369,10 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {
let gapReportHandler;
/** @type {string | undefined} */
let gapReportError;
+ /** @type {import('../../authoring/discover/type').DiscoverSource | undefined} */
+ let discoverSource;
+ /** @type {string | undefined} */
+ let discoverError;
/** @type {string | undefined} */
let agentDocsError;
try {
@@ -354,6 +382,8 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {
debug: debugHandler,
gapReport: gapReportHandler,
gapReportError,
+ discover: discoverSource,
+ discoverError,
agentDocsError,
} = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));
} catch (err) {
@@ -397,6 +427,8 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {
__debug: debugHandler,
__gapReport: gapReportHandler,
__gapReportError: gapReportError,
+ __discover: discoverSource,
+ __discoverError: discoverError,
__spec: spec,
__packageDir: packageDir,
__packageExports: pkg.exports ?? null,
@@ -448,6 +480,10 @@ export async function loadIntegrations(
let gapReportHandler;
/** @type {string | undefined} */
let gapReportError;
+ /** @type {import('../../authoring/discover/type').DiscoverSource | undefined} */
+ let discoverSource;
+ /** @type {string | undefined} */
+ let discoverError;
/** @type {string | undefined} */
let agentDocsError;
try {
@@ -457,6 +493,8 @@ export async function loadIntegrations(
debug: debugHandler,
gapReport: gapReportHandler,
gapReportError,
+ discover: discoverSource,
+ discoverError,
agentDocsError,
} = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));
} catch (err) {
@@ -507,6 +545,8 @@ export async function loadIntegrations(
__debug: debugHandler,
__gapReport: gapReportHandler,
__gapReportError: gapReportError,
+ __discover: discoverSource,
+ __discoverError: discoverError,
__spec: spec,
__packageDir: packageDir,
__packageExports: pkg.exports ?? null,
diff --git a/packages/cli/foundation/integrations/integrations.test.mjs b/packages/cli/foundation/integrations/integrations.test.mjs
index d955564be1..446a7b0537 100644
--- a/packages/cli/foundation/integrations/integrations.test.mjs
+++ b/packages/cli/foundation/integrations/integrations.test.mjs
@@ -785,3 +785,34 @@ describe('the `gapReport` named export', () => {
expect(loaded.__unknownKeys).toEqual(['gapReport']);
});
});
+
+describe('the `discover` named export', () => {
+ it('is carried out of the manifest module as __discover', async () => {
+ writeManifestPackage(tmpDir, {
+ body:
+ `export async function discover() { return {schemaVersion: 1}; }\n` +
+ `export default {issuesUrl: 'https://example.com/i'};\n`,
+ });
+
+ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});
+
+ expect(typeof loaded.__discover).toBe('function');
+ expect(loaded.__discoverError).toBeUndefined();
+ expect(loaded.__unknownKeys).toEqual([]);
+ expect(loaded.issuesUrl).toBe('https://example.com/i');
+ });
+
+ it('keeps the manifest and records why when the export is not a function', async () => {
+ writeManifestPackage(tmpDir, {
+ body:
+ `export const discover = {url: 'https://example.com/catalog.json'};\n` +
+ `export default {issuesUrl: 'https://example.com/i'};\n`,
+ });
+
+ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});
+
+ expect(loaded.__discover).toBeUndefined();
+ expect(loaded.__discoverError).toContain('must be a function');
+ expect(loaded.issuesUrl).toBe('https://example.com/i');
+ });
+});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 419a2c1b60..16b94d7bc7 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -104,21 +104,27 @@ export const doc = {
{
value: 'discover.list',
description:
- 'The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered".',
+ '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".',
},
{
value: 'discover.detail',
- description: 'A single external package entry, for an @scope/name query.',
+ description:
+ '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.',
},
{
value: 'discover.detail.doc',
description:
- 'The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component.',
+ 'The validated ComponentDoc for one installed component, for an @scope/name/Component query.',
+ },
+ {
+ value: 'discover.item',
+ description:
+ '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.',
},
{
value: 'discover.search',
description:
- 'The echoed query plus the matching {package, component} pairs, when a free-text term matches several components.',
+ '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
diff --git a/packages/cli/test/doc-routes.ids.json b/packages/cli/test/doc-routes.ids.json
index ad95b5a205..94b517e568 100644
--- a/packages/cli/test/doc-routes.ids.json
+++ b/packages/cli/test/doc-routes.ids.json
@@ -1059,6 +1059,7 @@
"component-doc",
"config",
"debug-event",
+ "discover-source",
"enum-doc",
"function-doc",
"gap-report-handler",
diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.json
index c6d238b6dc..f455e2ea76 100644
--- a/packages/cli/test/doc-routes.json
+++ b/packages/cli/test/doc-routes.json
@@ -97,6 +97,16 @@
"rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `gap-report-handler` (schema row), which the topic renders as one section.",
"status": "proposed"
},
+ {
+ "kind": "section",
+ "id": "authoring#discover-source",
+ "oldCliRoute": "astryx docs authoring discover-source",
+ "oldDocsiteUrl": "/docs/authoring#discoversource",
+ "placement": "keep-flat",
+ "aliasNeeded": false,
+ "rationale": "Stays a section of authoring under the same key. Its content is the schema self-doc `discover-source` (schema row), which the topic renders as one section.",
+ "status": "proposed"
+ },
{
"kind": "section",
"id": "authoring#codemod",
@@ -538,6 +548,17 @@
"rationale": "Stays a section of cli/integrations under the same key.",
"status": "proposed"
},
+ {
+ "kind": "section",
+ "id": "cli/integrations#discover-source",
+ "oldCliRoute": "astryx docs cli/integrations discover-source",
+ "oldDocsiteUrl": "/docs/cli-integrations#discover-source",
+ "placement": "namespace:cli/integrations",
+ "aliasNeeded": false,
+ "evidence": "Moves with cli/integrations.",
+ "rationale": "Stays a section of cli/integrations under the same key.",
+ "status": "proposed"
+ },
{
"kind": "section",
"id": "cli/integrations#how-it-works",
@@ -2394,13 +2415,13 @@
"kind": "schema",
"id": "@astryxdesign/cli/schema",
"provider": "@astryxdesign/cli",
- "count": 18,
+ "count": 19,
"oldCliRoute": null,
"oldDocsiteUrl": null,
"placement": "generated:@astryxdesign/cli/schema",
"aliasNeeded": false,
- "evidence": "No schema doc authors a placement; output declares cli/api and the other 17 declare authoring.",
- "rationale": "17 declare namespace 'authoring' and are read as sections of `astryx docs authoring`; `output` declares cli/api and is read as the leaf cli/api/schemas/output. Their home in the tree for authoring is a later phase.",
+ "evidence": "No schema doc authors a placement; output declares cli/api and the other 18 declare authoring.",
+ "rationale": "18 declare namespace 'authoring' and are read as sections of `astryx docs authoring`; `output` declares cli/api and is read as the leaf cli/api/schemas/output. Their home in the tree for authoring is a later phase.",
"status": "proposed"
},
{