An open source design system that's fully customizable and agent ready
TypeScript
refactor(cli): split discover into api/discover leaf shape (#4484)
Joey076d7ad4b186
diff --git a/.changeset/cli-discover-leaves.md b/.changeset/cli-discover-leaves.mdnew file mode 100644index 0000000000..8aa66ccd12--- /dev/null+++ b/.changeset/cli-discover-leaves.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[refactor] CLI: discover reorganized into api/discover leaf shape (list, detail, detail/doc, search) behind a shared _adapter that owns external-package discovery and doc loading; discover.mjs is now a dispatcher+barrel keeping the same exports. Pure reorg — `--json` and human output are byte-identical and api/index.mjs + the CLI consumer are untouched. Adds colocated leaf tests.+@josephfarinadiff --git a/packages/cli/api/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjsnew file mode 100644index 0000000000..02c13e3c4b--- /dev/null+++ b/packages/cli/api/discover/_adapter.mjs@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Shared external-package adapter for the discover leaves.+ *+ * 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.+ *+ * @position api/discover — orchestration over lib/project, lib/package-scanner,+ * and lib/component-loader; the discover dispatcher + leaves consume it.+ */++import {Project} from '../../lib/project.mjs';+import {+ scanAllPackages,+ findComponentInPackages,+} from '../../lib/package-scanner.mjs';+import {loadDocs} from '../../lib/component-loader.mjs';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../lib/error-codes.mjs';++/**+ * @typedef {import('../../lib/package-scanner.mjs').ScannedPackage} ScannedPackage+ */++/**+ * A located component doc within a scanned package — the shape returned by+ * {@link findComponent}, consumed by {@link loadValidatedDoc}.+ * @typedef {{pkg: ScannedPackage, docPath: string, componentName: string}} ComponentResolution+ */++/**+ * Validate the loose shape of a loaded docs object. Returns an error string+ * describing the first problem, or `null` when the docs are usable.+ * @param {unknown} docs+ * @returns {string | null}+ */+function validateDocs(docs) {+ if (!docs || typeof docs !== 'object')+ return 'docs export is missing or not an object';+ const d = /** @type {Record<string, any>} */ (docs);+ if (typeof d.name !== 'string' || !d.name)+ return 'docs.name is missing or not a string';+ if (!d.usage || typeof d.usage.description !== 'string')+ return 'docs.usage.description is missing or not a string';+ if (d.props && !Array.isArray(d.props))+ return 'docs.props must be an array';+ if (d.components && !Array.isArray(d.components))+ return 'docs.components must be an array';+ if (d.usage?.bestPractices && !Array.isArray(d.usage.bestPractices))+ return 'docs.usage.bestPractices must be an array';+ return null;+}++/**+ * Discover the configured external packages for the current project.+ *+ * External packages come from configured integrations that declare a components+ * root; each becomes a scannable package keyed by its docsDir. `configured`+ * reports whether ANY integration declared a components root — it lets an empty+ * result distinguish "nothing configured" (`false`) from "configured but+ * nothing discovered" (`true`), which the list leaf surfaces as `meta`.+ *+ * @returns {Promise<{packages: ScannedPackage[], configured: boolean}>}+ */+export async function discoverPackages() {+ const project = await Project.load();+ const loadedIntegrations =+ /** @type {import('../../lib/integrations.mjs').LoadedIntegration[]} */ (+ project.loadedIntegrations+ );++ const explicitPackages = loadedIntegrations+ .filter(integration => integration.components)+ .map(integration => ({+ name: integration.name,+ version: integration.version,+ category: integration.name,+ docsDir: integration.components,+ }));+ if (explicitPackages.length === 0) {+ return {packages: [], configured: false};+ }++ const packages = scanAllPackages(+ [],+ /** @type {ScannedPackage[]} */ (/** @type {unknown} */ (explicitPackages)),+ );+ return {packages, configured: true};+}++/**+ * 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+ * @returns {import('../../types/discover').DiscoverListEntry}+ */+export function toEntry(pkg) {+ return {+ name: pkg.name,+ category: pkg.category,+ components: pkg.components,+ version: pkg.version,+ description: pkg.description,+ displayName: pkg.displayName,+ };+}++/**+ * Locate a component's doc file within the given packages (case-insensitive).+ * @param {ScannedPackage[]} packages+ * @param {string} name+ * @returns {ComponentResolution | null}+ */+export function findComponent(packages, name) {+ return findComponentInPackages(packages, name);+}++/**+ * Load and validate a resolved component's docs. Throws AstryxError+ * (ERR_INVALID_DOC) when the file fails to load or the docs are malformed.+ * Returns the (optionally translated) docs object itself; leaves wrap it in the+ * `discover.detail.doc` envelope.+ * @param {ComponentResolution} result+ * @param {{lang?: string | null, zh?: boolean}} opts+ * @returns {Promise<import('../../types/discover').DiscoverDetailDocResponse['data']>}+ */+export async function loadValidatedDoc(result, {lang, zh}) {+ let docs;+ try {+ docs = await loadDocs(+ result.docPath,+ /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}),+ );+ } catch (e) {+ throw new AstryxError(+ `Failed to load docs for ${result.componentName}: ${/** @type {any} */ (e).message}`,+ undefined,+ ERROR_CODES.ERR_INVALID_DOC,+ );+ }+ const err = validateDocs(docs);+ if (err)+ throw new AstryxError(+ `Invalid docs for ${result.componentName}: ${err}`,+ undefined,+ ERROR_CODES.ERR_INVALID_DOC,+ );+ return docs;+}diff --git a/packages/cli/api/discover/detail/detail.mjs b/packages/cli/api/discover/detail/detail.mjsnew file mode 100644index 0000000000..8e65e99a53--- /dev/null+++ b/packages/cli/api/discover/detail/detail.mjs@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file discover.detail leaf — browse one external package (@scope/name).+ *+ * @position api/discover/detail — pure projection over the packages resolved by+ * ../_adapter; throws AstryxError (ERR_UNKNOWN_PACKAGE) for an unknown scope.+ */++import {toEntry} from '../_adapter.mjs';+import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../lib/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.+ *+ * @param {import('../../../lib/package-scanner.mjs').ScannedPackage[]} packages+ * @param {string} query scoped package name, e.g. `@scope/name`+ * @returns {import('../../../types/discover').DiscoverDetailResponse}+ */+export function detail(packages, query) {+ const pkg = packages.find(p => p.name === query);+ if (!pkg) {+ throw new AstryxError(+ `Package "${query}" not found`,+ packages.map(p => ({name: p.name, reason: 'available package'})),+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,+ );+ }+ return {type: 'discover.detail', data: toEntry(pkg)};+}diff --git a/packages/cli/api/discover/detail/detail.test.mjs b/packages/cli/api/discover/detail/detail.test.mjsnew file mode 100644index 0000000000..05c0ce89e7--- /dev/null+++ b/packages/cli/api/discover/detail/detail.test.mjs@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated unit tests for the discover.detail leaf. The leaf is a pure+ * projection over already-resolved packages, so these need no filesystem.+ */++import {describe, it, expect} from 'vitest';+import {detail} from './detail.mjs';+import {AstryxError} from '../../error.mjs';++/** Build a minimal ScannedPackage for projection tests. */+function pkg(name, components, extra = {}) {+ return {+ name,+ category: name,+ components,+ dir: '/virtual/' + name,+ astryx: {},+ docsDir: '/virtual/' + name + '/docs',+ ...extra,+ };+}++const PACKAGES = [+ pkg('@acme/widgets', ['Alpha', 'Beta'], {version: '1.2.3'}),+ pkg('@acme/gadgets', ['Gamma']),+];++describe('discover.detail leaf', () => {+ it('projects the matched package into a detail entry', () => {+ const res = detail(PACKAGES, '@acme/widgets');+ expect(res.type).toBe('discover.detail');+ expect(res.data).toEqual({+ name: '@acme/widgets',+ category: '@acme/widgets',+ components: ['Alpha', 'Beta'],+ version: '1.2.3',+ });+ });++ it('throws ERR_UNKNOWN_PACKAGE with the available packages as suggestions', () => {+ let err;+ try {+ detail(PACKAGES, '@acme/nope');+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(AstryxError);+ expect(err.code).toBe('ERR_UNKNOWN_PACKAGE');+ expect(err.message).toBe('Package "@acme/nope" not found');+ expect(err.suggestions).toEqual([+ {name: '@acme/widgets', reason: 'available package'},+ {name: '@acme/gadgets', reason: 'available package'},+ ]);+ });+});diff --git a/packages/cli/api/discover/detail/doc/doc.mjs b/packages/cli/api/discover/detail/doc/doc.mjsnew file mode 100644index 0000000000..7c23ac4b41--- /dev/null+++ b/packages/cli/api/discover/detail/doc/doc.mjs@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file discover.detail.doc leaf — resolve one external component's docs.+ *+ * Two entry points, both producing the discover.detail.doc envelope:+ * - {@link doc} resolves a `@scope/name/Component` query (package + component+ * lookup, with ERR_UNKNOWN_PACKAGE / ERR_UNKNOWN_COMPONENT suggestions).+ * - {@link docFromResult} wraps an already-resolved component (used by the+ * search leaf when a free-text query narrows to exactly one component).+ *+ * @position api/discover/detail/doc — projection over ../../_adapter's resolver+ * + doc loader; owns the discover.detail.doc envelope.+ */++import {findComponent, loadValidatedDoc} from '../../_adapter.mjs';+import {levenshteinDistance} from '../../../../lib/string-utils.mjs';+import {AstryxError} from '../../../error.mjs';+import {ERROR_CODES} from '../../../../lib/error-codes.mjs';++/**+ * Wrap an already-resolved component in the discover.detail.doc envelope by+ * loading + validating its docs. The single place the envelope is built.+ *+ * @param {import('../../_adapter.mjs').ComponentResolution} result+ * @param {{lang?: string | null, zh?: boolean}} opts+ * @returns {Promise<import('../../../../types/discover').DiscoverDetailDocResponse>}+ */+export async function docFromResult(result, opts) {+ return {type: 'discover.detail.doc', data: await loadValidatedDoc(result, opts)};+}++/**+ * Resolve a `@scope/name/Component` query to its validated docs. Throws+ * AstryxError (ERR_UNKNOWN_PACKAGE) when the scope is unknown, or+ * (ERR_UNKNOWN_COMPONENT) — with substring/fuzzy suggestions — when the+ * component is not in the package.+ *+ * @param {import('../../../../lib/package-scanner.mjs').ScannedPackage[]} packages+ * @param {string} pkgName+ * @param {string} compName+ * @param {{lang?: string | null, zh?: boolean}} opts+ * @returns {Promise<import('../../../../types/discover').DiscoverDetailDocResponse>}+ */+export async function doc(packages, pkgName, compName, {lang, zh}) {+ const pkg = packages.find(p => p.name === pkgName);+ if (!pkg)+ throw new AstryxError(+ `Package "${pkgName}" not found`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,+ );++ const result = findComponent([pkg], compName);+ if (!result) {+ const lower = compName.toLowerCase();+ const hits = pkg.components.filter(c => c.toLowerCase().includes(lower));+ const suggestions =+ hits.length > 0+ ? hits+ : pkg.components+ .map(c => ({+ name: c,+ distance: levenshteinDistance(lower, c.toLowerCase()),+ }))+ .filter(m => m.distance <= 3)+ .sort((a, b) => a.distance - b.distance)+ .slice(0, 5)+ .map(m => m.name);+ throw new AstryxError(+ `Component "${compName}" not found in ${pkgName}`,+ suggestions.map(s => ({name: s, reason: 'similar name'})),+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,+ );+ }++ return docFromResult(result, {lang, zh});+}diff --git a/packages/cli/api/discover/detail/doc/doc.test.mjs b/packages/cli/api/discover/detail/doc/doc.test.mjsnew file mode 100644index 0000000000..c5d583683b--- /dev/null+++ b/packages/cli/api/discover/detail/doc/doc.test.mjs@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated tests for the discover.detail.doc leaf. Doc resolution loads+ * a real `.doc.mjs` from disk, so these drive a small temp docs directory.+ */++import {describe, it, expect, beforeAll, afterAll} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {doc, docFromResult} from './doc.mjs';+import {AstryxError} from '../../../error.mjs';++let docsDir;+let pkg;++beforeAll(() => {+ docsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'discover-doc-'));+ fs.writeFileSync(+ path.join(docsDir, 'Alpha.doc.mjs'),+ `export const docs = {name: 'Alpha', usage: {description: 'Alpha component'}, props: []};\n`,+ );+ fs.writeFileSync(+ path.join(docsDir, 'AlphaCard.doc.mjs'),+ `export const docs = {name: 'AlphaCard', usage: {description: 'Alpha card'}, props: []};\n`,+ );+ fs.writeFileSync(+ path.join(docsDir, 'Beta.doc.mjs'),+ `export const docs = {name: 'Beta', usage: {description: 'Beta component'}, props: []};\n`,+ );+ pkg = {+ name: '@acme/widgets',+ category: '@acme/widgets',+ version: '1.0.0',+ dir: docsDir,+ astryx: {},+ docsDir,+ components: ['Alpha', 'AlphaCard', 'Beta'],+ };+});++afterAll(() => {+ fs.rmSync(docsDir, {recursive: true, force: true});+});++describe('discover.detail.doc leaf', () => {+ it('resolves @scope/name/Component to its validated docs', async () => {+ const res = await doc([pkg], '@acme/widgets', 'Alpha', {});+ expect(res.type).toBe('discover.detail.doc');+ expect(res.data.name).toBe('Alpha');+ expect(res.data.usage.description).toBe('Alpha component');+ });++ it('resolves case-insensitively', async () => {+ const res = await doc([pkg], '@acme/widgets', 'alpha', {});+ expect(res.data.name).toBe('Alpha');+ });++ it('throws ERR_UNKNOWN_PACKAGE for an unknown scope', async () => {+ await expect(doc([pkg], '@acme/nope', 'Alpha', {})).rejects.toMatchObject({+ code: 'ERR_UNKNOWN_PACKAGE',+ });+ });++ it('throws ERR_UNKNOWN_COMPONENT with substring suggestions', async () => {+ let err;+ try {+ await doc([pkg], '@acme/widgets', 'card', {});+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(AstryxError);+ expect(err.code).toBe('ERR_UNKNOWN_COMPONENT');+ expect(err.suggestions).toEqual([{name: 'AlphaCard', reason: 'similar name'}]);+ });++ it('docFromResult wraps an already-resolved component', async () => {+ const res = await docFromResult(+ {+ pkg,+ docPath: path.join(docsDir, 'Beta.doc.mjs'),+ componentName: 'Beta',+ },+ {},+ );+ expect(res).toEqual({+ type: 'discover.detail.doc',+ data: {name: 'Beta', usage: {description: 'Beta component'}, props: []},+ });+ });+});diff --git a/packages/cli/api/discover/discover.mjs b/packages/cli/api/discover/discover.mjsindex adf38736b2..53a881e54f 100644--- a/packages/cli/api/discover/discover.mjs+++ b/packages/cli/api/discover/discover.mjs@@ -1,43 +1,26 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Programmatic API for the discover command.+ * @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.list -> ./list/list.mjs+ * discover.detail -> ./detail/detail.mjs+ * discover.detail.doc -> ./detail/doc/doc.mjs+ * discover.search -> ./search/search.mjs+ *+ * @position api/discover — thin router over ./_adapter + the discover leaves.*/-import {Project} from '../../lib/project.mjs';-import {- scanAllPackages,- findComponentInPackages,-} from '../../lib/package-scanner.mjs';-import {loadDocs} from '../../lib/component-loader.mjs';-import {levenshteinDistance} from '../../lib/string-utils.mjs';-import {AstryxError} from '../error.mjs';-import {ERROR_CODES} from '../../lib/error-codes.mjs';--/**- * @typedef {import('../../lib/package-scanner.mjs').ScannedPackage} ScannedPackage- */--/**- * @param {unknown} docs- * @returns {string | null}- */-function validateDocs(docs) {- if (!docs || typeof docs !== 'object')- return 'docs export is missing or not an object';- const d = /** @type {Record<string, any>} */ (docs);- if (typeof d.name !== 'string' || !d.name)- return 'docs.name is missing or not a string';- if (!d.usage || typeof d.usage.description !== 'string')- return 'docs.usage.description is missing or not a string';- if (d.props && !Array.isArray(d.props))- return 'docs.props must be an array';- if (d.components && !Array.isArray(d.components))- return 'docs.components must be an array';- if (d.usage?.bestPractices && !Array.isArray(d.usage.bestPractices))- return 'docs.usage.bestPractices must be an array';- return null;-}+import {discoverPackages} from './_adapter.mjs';+import {list} from './list/list.mjs';+import {detail} from './detail/detail.mjs';+import {doc} from './detail/doc/doc.mjs';+import {search} from './search/search.mjs';/*** @param {string} [query]@@ -54,47 +37,15 @@ function validateDocs(docs) {*/export async function discover(query, options = {}) {const {lang = null, zh = false} = options;- const project = await Project.load();- const loadedIntegrations =- /** @type {import('../../lib/integrations.mjs').LoadedIntegration[]} */ (- project.loadedIntegrations- );- /** @param {ScannedPackage} pkg */- const toEntry = pkg => ({- name: pkg.name,- category: pkg.category,- components: pkg.components,- version: pkg.version,- description: pkg.description,- displayName: pkg.displayName,- });+ const {packages, configured} = await discoverPackages();- // External packages come from configured integrations that declare a- // components root. Each becomes a scannable package keyed by its docsDir.- const explicitPackages = loadedIntegrations- .filter(integration => integration.components)- .map(integration => ({- name: integration.name,- version: integration.version,- category: integration.name,- docsDir: integration.components,- }));- if (explicitPackages.length === 0) {- return {type: 'discover.list', data: [], meta: {configured: false}};- }+ // 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});- const packages = scanAllPackages(- [],- /** @type {ScannedPackage[]} */ (/** @type {unknown} */ (explicitPackages)),- );-- if (packages.length === 0) {- return {type: 'discover.list', data: [], meta: {configured: true}};- }-- if (!query) {- return {type: 'discover.list', data: packages.map(toEntry)};- }+ // No query: the full package list.+ if (!query) return list(packages, {configured});// Scoped package query: @scope/name or @scope/name/Componentif (query.startsWith('@')) {@@ -102,160 +53,11 @@ export async function discover(query, options = {}) {if (slashIdx > 0) {const pkgName = query.slice(0, slashIdx);const compName = query.slice(slashIdx + 1);- return await resolveComponentDocs(packages, compName, pkgName, {- lang,- zh,- });- }-- const pkg = packages.find(p => p.name === query);- if (!pkg) {- throw new AstryxError(- `Package "${query}" not found`,- packages.map(p => ({name: p.name, reason: 'available package'})),- ERROR_CODES.ERR_UNKNOWN_PACKAGE,- );- }- return {type: 'discover.detail', data: toEntry(pkg)};- }-- // Search mode- const lower = query.toLowerCase();-- const exact = findComponentInPackages(packages, query);- if (exact) {- return await loadAndValidate(exact, {lang, zh});- }-- const substringMatches = /** @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});- }+ return await doc(packages, pkgName, compName, {lang, zh});}+ return detail(packages, query);}- if (substringMatches.length === 1) {- const match = substringMatches[0];- const result = findComponentInPackages([match.pkg], match.comp);- if (result) return await loadAndValidate(result, {lang, zh});- }-- if (substringMatches.length > 1) {- return {- type: 'discover.search',- data: {- query,- matches: substringMatches.map(m => ({- package: m.pkg.name,- component: m.comp,- })),- },- };- }-- // Fuzzy fallback- const allComponents = /** @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()),- }))- .filter(m => m.distance <= 3)- .sort((a, b) => a.distance - b.distance)- .slice(0, 5);-- if (fuzzyMatches.length > 0) {- throw new AstryxError(- `"${query}" not found`,- fuzzyMatches.map(m => ({- name: m.pkg.name + '/' + m.comp,- reason: 'similar name',- })),- ERROR_CODES.ERR_NOT_FOUND,- );- }-- throw new AstryxError(- `"${query}" not found in any package`,- undefined,- ERROR_CODES.ERR_NOT_FOUND,- );-}--/**- * @param {ScannedPackage[]} packages- * @param {string} compName- * @param {string} pkgName- * @param {{lang?: string|null, zh?: boolean}} opts- * @returns {Promise<import('../../types/discover').DiscoverDetailDocResponse>}- */-async function resolveComponentDocs(packages, compName, pkgName, {lang, zh}) {- const pkg = packages.find(p => p.name === pkgName);- if (!pkg)- throw new AstryxError(- `Package "${pkgName}" not found`,- undefined,- ERROR_CODES.ERR_UNKNOWN_PACKAGE,- );-- const result = findComponentInPackages([pkg], compName);- if (!result) {- const lower = compName.toLowerCase();- const hits = pkg.components.filter(c => c.toLowerCase().includes(lower));- const suggestions =- hits.length > 0- ? hits- : pkg.components- .map(c => ({- name: c,- distance: levenshteinDistance(lower, c.toLowerCase()),- }))- .filter(m => m.distance <= 3)- .sort((a, b) => a.distance - b.distance)- .slice(0, 5)- .map(m => m.name);- throw new AstryxError(- `Component "${compName}" not found in ${pkgName}`,- suggestions.map(s => ({name: s, reason: 'similar name'})),- ERROR_CODES.ERR_UNKNOWN_COMPONENT,- );- }-- return await loadAndValidate(result, {lang, zh});-}--/**- * @param {{docPath: string, componentName: string, pkg: ScannedPackage}} result- * @param {{lang?: string|null, zh?: boolean}} opts- * @returns {Promise<import('../../types/discover').DiscoverDetailDocResponse>}- */-async function loadAndValidate(result, {lang, zh}) {- let docs;- try {- docs = await loadDocs(- result.docPath,- /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang}),- );- } catch (e) {- throw new AstryxError(- `Failed to load docs for ${result.componentName}: ${/** @type {any} */ (e).message}`,- undefined,- ERROR_CODES.ERR_INVALID_DOC,- );- }- const err = validateDocs(docs);- if (err)- throw new AstryxError(- `Invalid docs for ${result.componentName}: ${err}`,- undefined,- ERROR_CODES.ERR_INVALID_DOC,- );- return {type: 'discover.detail.doc', data: docs};+ // Free-text search across all packages.+ return await search(packages, query, {lang, zh});}diff --git a/packages/cli/api/discover/list/list.mjs b/packages/cli/api/discover/list/list.mjsnew file mode 100644index 0000000000..e20ebaee19--- /dev/null+++ b/packages/cli/api/discover/list/list.mjs@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file discover.list leaf — list the discovered external packages.+ *+ * @position api/discover/list — pure projection of the packages resolved by+ * ../_adapter into the discover.list envelope.+ */++import {toEntry} from '../_adapter.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".+ *+ * @param {import('../../../lib/package-scanner.mjs').ScannedPackage[]} packages+ * @param {{configured: boolean}} meta+ * @returns {import('../../../types/discover').DiscoverListResponse}+ */+export function list(packages, {configured}) {+ if (packages.length === 0) {+ return {type: 'discover.list', data: [], meta: {configured}};+ }+ return {type: 'discover.list', data: packages.map(toEntry)};+}diff --git a/packages/cli/api/discover/list/list.test.mjs b/packages/cli/api/discover/list/list.test.mjsnew file mode 100644index 0000000000..2ac88565d4--- /dev/null+++ b/packages/cli/api/discover/list/list.test.mjs@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated unit tests for the discover.list leaf. The leaf is a pure+ * projection of already-resolved packages, so these need no filesystem.+ */++import {describe, it, expect} from 'vitest';+import {list} from './list.mjs';++/** Build a minimal ScannedPackage for projection tests. */+function pkg(name, components, extra = {}) {+ return {+ name,+ category: name,+ components,+ dir: '/virtual/' + name,+ astryx: {},+ docsDir: '/virtual/' + name + '/docs',+ ...extra,+ };+}++describe('discover.list leaf', () => {+ it('projects packages into list entries (no meta when non-empty)', () => {+ const res = list(+ [pkg('@acme/widgets', ['Alpha', 'Beta'], {version: '1.2.3'})],+ {configured: true},+ );+ expect(res.type).toBe('discover.list');+ expect(res.meta).toBeUndefined();+ expect(res.data).toEqual([+ {+ name: '@acme/widgets',+ category: '@acme/widgets',+ components: ['Alpha', 'Beta'],+ version: '1.2.3',+ },+ ]);+ });++ it('returns the configured:true empty envelope when nothing was discovered', () => {+ const res = list([], {configured: true});+ expect(res).toEqual({+ type: 'discover.list',+ data: [],+ meta: {configured: true},+ });+ });++ it('returns the configured:false empty envelope when nothing is configured', () => {+ const res = list([], {configured: false});+ expect(res).toEqual({+ type: 'discover.list',+ data: [],+ meta: {configured: false},+ });+ });+});diff --git a/packages/cli/api/discover/search/search.mjs b/packages/cli/api/discover/search/search.mjsnew file mode 100644index 0000000000..27fcfc629a--- /dev/null+++ b/packages/cli/api/discover/search/search.mjs@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file discover.search leaf — free-text search across external packages.+ *+ * 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+ *+ * @position api/discover/search — projection over ../_adapter's resolver;+ * delegates the single-component cases to ../detail/doc.+ */++import {findComponent} from '../_adapter.mjs';+import {docFromResult} from '../detail/doc/doc.mjs';+import {levenshteinDistance} from '../../../lib/string-utils.mjs';+import {AstryxError} from '../../error.mjs';+import {ERROR_CODES} from '../../../lib/error-codes.mjs';++/**+ * @typedef {import('../../../lib/package-scanner.mjs').ScannedPackage} ScannedPackage+ */++/**+ * 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.+ *+ * @param {ScannedPackage[]} packages+ * @param {string} query+ * @param {{lang?: string | null, zh?: boolean}} opts+ * @returns {Promise<+ * import('../../../types/discover').DiscoverDetailDocResponse |+ * import('../../../types/discover').DiscoverSearchResponse+ * >}+ */+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});+ }+ }+ }++ if (substringMatches.length === 1) {+ const match = substringMatches[0];+ const result = findComponent([match.pkg], match.comp);+ if (result) return await docFromResult(result, {lang, zh});+ }++ if (substringMatches.length > 1) {+ return {+ type: 'discover.search',+ data: {+ query,+ matches: substringMatches.map(m => ({+ package: m.pkg.name,+ component: m.comp,+ })),+ },+ };+ }++ // Fuzzy fallback+ const allComponents =+ /** @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()),+ }))+ .filter(m => m.distance <= 3)+ .sort((a, b) => a.distance - b.distance)+ .slice(0, 5);++ if (fuzzyMatches.length > 0) {+ throw new AstryxError(+ `"${query}" not found`,+ fuzzyMatches.map(m => ({+ name: m.pkg.name + '/' + m.comp,+ reason: 'similar name',+ })),+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }++ throw new AstryxError(+ `"${query}" not found in any package`,+ undefined,+ ERROR_CODES.ERR_NOT_FOUND,+ );+}diff --git a/packages/cli/api/discover/search/search.test.mjs b/packages/cli/api/discover/search/search.test.mjsnew file mode 100644index 0000000000..1a0bb1adf2--- /dev/null+++ b/packages/cli/api/discover/search/search.test.mjs@@ -0,0 +1,104 @@+// 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.+ */++import {describe, it, expect, beforeAll, afterAll} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {search} from './search.mjs';+import {AstryxError} from '../../error.mjs';++let docsDir;+let packages;++beforeAll(() => {+ docsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'discover-search-'));+ fs.writeFileSync(+ path.join(docsDir, 'Alpha.doc.mjs'),+ `export const docs = {name: 'Alpha', usage: {description: 'Alpha component'}, props: []};\n`,+ );+ fs.writeFileSync(+ path.join(docsDir, 'AlphaCard.doc.mjs'),+ `export const docs = {name: 'AlphaCard', usage: {description: 'Alpha card'}, props: []};\n`,+ );+ fs.writeFileSync(+ path.join(docsDir, 'Beta.doc.mjs'),+ `export const docs = {name: 'Beta', usage: {description: 'Beta component'}, props: []};\n`,+ );+ packages = [+ {+ name: '@acme/widgets',+ category: '@acme/widgets',+ version: '1.0.0',+ dir: docsDir,+ astryx: {},+ docsDir,+ components: ['Alpha', 'AlphaCard', 'Beta'],+ },+ ];+});++afterAll(() => {+ fs.rmSync(docsDir, {recursive: true, force: true});+});++describe('discover.search leaf', () => {+ it('an exact component name resolves to its docs', async () => {+ const res = await search(packages, 'Alpha', {});+ expect(res.type).toBe('discover.detail.doc');+ expect(res.data.name).toBe('Alpha');+ });++ it('a single substring match resolves to its docs', async () => {+ const res = await search(packages, 'card', {});+ expect(res.type).toBe('discover.detail.doc');+ expect(res.data.name).toBe('AlphaCard');+ });++ it('multiple substring matches return a search response', async () => {+ const res = await search(packages, 'alph', {});+ expect(res).toEqual({+ type: 'discover.search',+ data: {+ query: 'alph',+ matches: [+ {package: '@acme/widgets', component: 'Alpha'},+ {package: '@acme/widgets', component: 'AlphaCard'},+ ],+ },+ });+ });++ it('throws ERR_NOT_FOUND with fuzzy suggestions for a close miss', async () => {+ let err;+ try {+ await search(packages, 'Alfa', {});+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(AstryxError);+ expect(err.code).toBe('ERR_NOT_FOUND');+ expect(err.message).toBe('"Alfa" not found');+ expect(err.suggestions?.[0]).toEqual({+ name: '@acme/widgets/Alpha',+ reason: 'similar name',+ });+ });++ it('throws ERR_NOT_FOUND without suggestions for a far miss', async () => {+ let err;+ try {+ await search(packages, 'zzzzzzz', {});+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(AstryxError);+ expect(err.code).toBe('ERR_NOT_FOUND');+ expect(err.message).toBe('"zzzzzzz" not found in any package');+ expect(err.suggestions).toBeUndefined();+ });+});