An open source design system that's fully customizable and agent ready
TypeScript
fix: load integration component docs and imports correctly (#6291)
Joey47cfd5289399
diff --git a/.changeset/fix-default-export-component-loader.md b/.changeset/fix-default-export-component-loader.mdnew file mode 100644index 0000000000..4b8d2b7cf1--- /dev/null+++ b/.changeset/fix-default-export-component-loader.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[fix] Component loader now reads default-export `.doc.mjs` files (the shape `integration add component` writes), fixing a crash where `component` and `search` could not load generated docs. Human `component` detail and list views now use the API-resolved import specifier instead of recomputing from core, so integration components report their package-authored import. `pack --check` now reports an error when a component doc cannot be loaded instead of silently approving.+@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 6f8dac5252..652dcb5221 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -395,7 +395,7 @@ Every response has a `type` discriminant. The full set is below (generated from| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. || `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |-| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |+| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries, or a full ComponentDoc per entry. || `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). || `component.detail.props` | Just one component's props table (ComponentPropDoc[]). || `component.detail.source` | One component's source file, as {component, source}. |diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjsindex b3075d9ca6..9df8446976 100644--- a/packages/cli/api/component/_adapter.mjs+++ b/packages/cli/api/component/_adapter.mjs@@ -19,7 +19,10 @@*/import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';-import {findCoreDir, discoverExternalPackages} from '../../foundation/fs/paths.mjs';+import {+ findCoreDir,+ discoverExternalPackages,+} from '../../foundation/fs/paths.mjs';import {CORE_PACKAGE,discoverComponents,@@ -109,7 +112,11 @@ export {CORE_PACKAGE};export function requireCoreDir(cwd) {const coreDir = findCoreDir(cwd);if (!coreDir) {- throw new AstryxError('Could not find @astryxdesign/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);+ throw new AstryxError(+ 'Could not find @astryxdesign/core package',+ undefined,+ ERROR_CODES.ERR_CORE_NOT_FOUND,+ );}return coreDir;}@@ -197,12 +204,19 @@ export function resolveOwners(coreDir, dirName, loadedIntegrations) {* @param {{owners: ComponentOwner[], loadedIntegrations: import('../../foundation/integrations/integrations.mjs').LoadedIntegration[], cwd: string, name: string}} ctx* @returns {ScopeResolution}*/-export function classifyScope(packageScope, {owners, loadedIntegrations, cwd, name}) {+export function classifyScope(+ packageScope,+ {owners, loadedIntegrations, cwd, name},+) {// Core scope: resolve from core directly.if (packageScope === CORE_PACKAGE) {const owner = owners.find(o => o.package === CORE_PACKAGE);if (!owner) {- throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);+ throw new AstryxError(+ `No component "${name}" in package "${packageScope}"`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,+ );}return {kind: 'core', owner};}@@ -212,7 +226,11 @@ export function classifyScope(packageScope, {owners, loadedIntegrations, cwd, naif (integration) {const owner = owners.find(o => o.package === packageScope);if (!owner) {- throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);+ throw new AstryxError(+ `No component "${name}" in package "${packageScope}"`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,+ );}return {kind: 'integration', owner};}@@ -220,7 +238,11 @@ export function classifyScope(packageScope, {owners, loadedIntegrations, cwd, na// Legacy fallback: node_modules `pkg.astryx.docs` external package.const ext = resolveExternalPackage(packageScope, cwd);if (!ext) {- throw new AstryxError(`External package "${packageScope}" not found`, undefined, ERROR_CODES.ERR_UNKNOWN_PACKAGE);+ throw new AstryxError(+ `External package "${packageScope}" not found`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,+ );}return {kind: 'legacy', ext};}@@ -283,7 +305,9 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {// type, which (unlike a fresh literal) does not widen on assignment./** @type {string} */let resolvedOwnerPackage = CORE_PACKAGE;- let resolvedSourcePath = readmePath ? findComponentSource(coreDir, dirName) : null;+ let resolvedSourcePath = readmePath+ ? findComponentSource(coreDir, dirName)+ : null;if (!readmePath) {const externals = discoverExternalPackages(cwd);@@ -305,7 +329,8 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {if (results.length > 0) {const topScore = results[0].score;const topTied = results.filter(r => r.score === topScore);- const secondScore = results.length > topTied.length ? results[topTied.length].score : 0;+ const secondScore =+ results.length > topTied.length ? results[topTied.length].score : 0;const gap = topScore - secondScore;if (topScore >= 90 && topTied.length === 1 && gap >= 20) {@@ -315,8 +340,11 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {resolvedSourcePath = findComponentSource(coreDir, resolvedName);} else {const threshold = Math.max(topScore - 20, 1);- const candidates = results.filter(r => r.score >= threshold).slice(0, 5);- if (candidates.length < 2) candidates.push(...results.slice(candidates.length, 2));+ const candidates = results+ .filter(r => r.score >= threshold)+ .slice(0, 5);+ if (candidates.length < 2)+ candidates.push(...results.slice(candidates.length, 2));throw new AstryxError(`No component named "${name}"`,candidates.map(c => ({name: c.name, reason: c.reason})),@@ -324,12 +352,20 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {);}} else {- throw new AstryxError(`No component named "${name}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);+ throw new AstryxError(+ `No component named "${name}"`,+ undefined,+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,+ );}}if (!readmePath || !readmePath.endsWith('.doc.mjs')) {- throw new AstryxError(`No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`, undefined, ERROR_CODES.ERR_NO_DOC);+ throw new AstryxError(+ `No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`,+ undefined,+ ERROR_CODES.ERR_NO_DOC,+ );}return {readmePath, resolvedName, resolvedOwnerPackage, resolvedSourcePath};@@ -357,7 +393,10 @@ export async function loadComponentDoc(docPath, opts = {}) {* @returns {any[]}*/export function extractProps(docs) {- return docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);+ return (+ docs.props ||+ (docs.components ? docs.components.flatMap(c => c.props || []) : [])+ );}/**@@ -374,14 +413,12 @@ export function extractProps(docs) {export function withOwnership(docs, owner, componentName, coreDir) {const importSpec =owner.package === CORE_PACKAGE- ? resolveImportPath(coreDir, componentName)- : resolveIntegrationImportPath(owner, componentName);+ ? (docs.import ?? resolveImportPath(coreDir, componentName))+ : resolveIntegrationImportPath(owner, componentName, docs.import);return /** @type {any} */ ({...docs,package: owner.package,- // A doc file may state its own specifier, e.g. when one entry point exports- // several components. Only fall back to a resolved one when it does not.- import: docs.import ?? importSpec,+ import: importSpec,sourceAvailable: owner.sourcePath != null,});}@@ -395,9 +432,10 @@ export function withOwnership(docs, owner, componentName, coreDir) {** @param {OwnershipSubject} owner* @param {string} componentName+ * @param {string|null} [authoredImport]* @returns {string}*/-function resolveIntegrationImportPath(owner, componentName) {+function resolveIntegrationImportPath(owner, componentName, authoredImport) {return resolveIntegrationImport({exportsMap: owner.integration?.__packageExports,@@ -406,6 +444,7 @@ function resolveIntegrationImportPath(owner, componentName) {packageName: owner.package,},componentName,+ authoredImport,);}@@ -421,10 +460,12 @@ function resolveIntegrationImportPath(owner, componentName) {*/export function scopeSubComponent(docs, dirName, coreDir) {const requestedXDS = `XDS${dirName}`;- const isParentDoc = docs.name && docs.name.toLowerCase() !== dirName.toLowerCase();- const matchingComponent = isParentDoc && docs.components- ? docs.components.find(c => c.name === requestedXDS || c.name === dirName)- : null;+ const isParentDoc =+ docs.name && docs.name.toLowerCase() !== dirName.toLowerCase();+ const matchingComponent =+ isParentDoc && docs.components+ ? docs.components.find(c => c.name === requestedXDS || c.name === dirName)+ : null;if (!matchingComponent) return null;diff --git a/packages/cli/api/component/component.doc.mjs b/packages/cli/api/component/component.doc.mjsindex ba62b63b61..0e1ecf3d24 100644--- a/packages/cli/api/component/component.doc.mjs+++ b/packages/cli/api/component/component.doc.mjs@@ -108,7 +108,7 @@ export const doc = {{type: 'component.list',description:- "The catalog grouped by category. data.detail is the level ('names' | 'compact' | 'full') and data.components is the grouped map: names+package, brief entries, or full ComponentDoc per entry.",+ "The catalog grouped by category. data.detail is the level ('names' | 'compact' | 'full') and data.components is the grouped map: names entries with name, package, and an optional canonical import for integrations; brief entries; or full ComponentDoc entries.",},{type: 'component.detail',diff --git a/packages/cli/api/component/component.type.mjs b/packages/cli/api/component/component.type.mjsindex 5c4110f737..64f2c50fa0 100644--- a/packages/cli/api/component/component.type.mjs+++ b/packages/cli/api/component/component.type.mjs@@ -32,7 +32,7 @@* The list view emits ONE `component.list` type across all three detail levels;* the depth is carried in `data.detail` and `data.components` holds the grouped* map whose entry shape depends on that level:- * - 'names' -> ComponentListEntry[] (name + owner package)+ * - 'names' -> ComponentListEntry[] (name + owner package + optional import)* - 'compact' -> ComponentBriefEntry[] (name + 1-line description + import)* - 'full' -> ComponentDoc[] (full authored doc per entry)* @typedef {object} ComponentListResponse@@ -52,10 +52,13 @@/*** A single entry in a `component.list` group at `detail: 'names'`. Pre-1.0 the* list moved from bare strings to package-qualified objects so consumers can- * disambiguate ownership (core vs. an integration package).+ * disambiguate ownership (core vs. an integration package). Integration entries+ * carry `import` — the package-authored specifier; core entries omit it (the+ * specifier is derived from the component name by the renderer).* @typedef {object} ComponentListEntry* @property {string} name* @property {string} package - Owner package, e.g. '@astryxdesign/core' or '@acme/astryx-meta'.+ * @property {string} [import] - Import specifier; present for integration components, absent for core.*//**diff --git a/packages/cli/api/component/integration-import-agreement.test.mjs b/packages/cli/api/component/integration-import-agreement.test.mjsindex 94f6603af7..bef57e33e5 100644--- a/packages/cli/api/component/integration-import-agreement.test.mjs+++ b/packages/cli/api/component/integration-import-agreement.test.mjs@@ -106,7 +106,10 @@ function searchImportFor(result, name) {async function bothSurfaces() {const detail = await component('AcmeCarousel', {cwd: tmpDir});const found = await search('carousel', {cwd: tmpDir});- return {detail: detail.data.import, found: searchImportFor(found, 'AcmeCarousel')};+ return {+ detail: detail.data.import,+ found: searchImportFor(found, 'AcmeCarousel'),+ };}const SUBPATH_EXPORTS = {@@ -115,7 +118,9 @@ const SUBPATH_EXPORTS = {};beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-import-agreement-test-'));+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-import-agreement-test-'),+ );});afterEach(() => {@@ -224,7 +229,9 @@ describe('integration component import specifiers', () => {'a prefixed wildcard only matches the subpaths it covers',async () => {// `./components/*` does not cover `./Carousel`, so this falls back.- scaffold({exports: {'.': './src/index.js', './components/*': './src/*/index.js'}});+ scaffold({+ exports: {'.': './src/index.js', './components/*': './src/*/index.js'},+ });const {detail, found} = await bothSurfaces();expect(detail).toBe('@acme/widgets');@@ -278,7 +285,10 @@ describe('integration component import specifiers', () => {scaffold({exports: {'.': './src/index.js',- './Carousel': {import: './src/Carousel/index.js', require: './cjs/Carousel.js'},+ './Carousel': {+ import: './src/Carousel/index.js',+ require: './cjs/Carousel.js',+ },},});const {detail, found} = await bothSurfaces();@@ -298,7 +308,12 @@ describe('integration component import specifiers', () => {// loader looked and there was none.scaffold({exports: SUBPATH_EXPORTS});const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');- const docPath = path.join(pkgDir, 'src', 'Carousel', 'AcmeCarousel.doc.mjs');+ const docPath = path.join(+ pkgDir,+ 'src',+ 'Carousel',+ 'AcmeCarousel.doc.mjs',+ );expect(resolveIntegrationImportPath(@@ -310,9 +325,150 @@ describe('integration component import specifiers', () => {// A parsed `null` is an answer, not a gap: it must not fall back to a read.expect(resolveIntegrationImportPath(- {exportsMap: null, packageDir: pkgDir, docPath, packageName: '@acme/widgets'},+ {+ exportsMap: null,+ packageDir: pkgDir,+ docPath,+ packageName: '@acme/widgets',+ },'AcmeCarousel',),).toBe('@acme/widgets');});});++/**+ * Scaffold a default-export component doc (the shape `integration add component`+ * generates). This is a separate function because the existing scaffold writes+ * a named `export const docs`, and we need to test both.+ */+function scaffoldDefaultExport({exports: exportsMap, docImport} = {}) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.config.mjs'),+ "export default {integrations: ['@acme/widgets']};\n",+ );++ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');+ const componentDir = path.join(pkgDir, 'src', 'Carousel');+ fs.mkdirSync(componentDir, {recursive: true});++ fs.writeFileSync(+ path.join(pkgDir, 'package.json'),+ JSON.stringify({+ name: '@acme/widgets',+ version: '1.0.0',+ ...(exportsMap ? {exports: exportsMap} : {}),+ }),+ );+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ "export default {components: './src'};\n",+ );+ fs.writeFileSync(+ path.join(componentDir, 'AcmeCarousel.tsx'),+ 'export const AcmeCarousel = () => null;\n',+ );+ // Default export — the shape integration add component writes+ fs.writeFileSync(+ path.join(componentDir, 'AcmeCarousel.doc.mjs'),+ `export default ${JSON.stringify(+ {+ type: 'component',+ name: 'AcmeCarousel',+ displayName: 'Acme Carousel',+ keywords: ['carousel', 'slides'],+ usage: {description: 'A carousel that cycles through slides.'},+ props: [],+ ...(docImport ? {import: docImport} : {}),+ },+ null,+ 2,+ )};\n`,+ );+}++describe('default-export component doc agreement', () => {+ it(+ 'component detail loads a default-export doc without crashing',+ async () => {+ scaffoldDefaultExport({exports: SUBPATH_EXPORTS});+ const result = await component('AcmeCarousel', {cwd: tmpDir});+ expect(result.type).toBe('component.detail');+ expect(result.data.name).toBe('AcmeCarousel');+ expect(result.data.import).toBe('@acme/widgets/Carousel');+ expect(result.data.package).toBe('@acme/widgets');+ },+ SLOW,+ );++ it(+ 'a doc-authored import in a default export wins over the resolved subpath',+ async () => {+ scaffoldDefaultExport({+ exports: SUBPATH_EXPORTS,+ docImport: '@acme/widgets/Alias',+ });+ const result = await component('AcmeCarousel', {cwd: tmpDir});+ expect(result.data.import).toBe('@acme/widgets/Alias');+ },+ SLOW,+ );++ it(+ 'search finds a default-export component with the correct import',+ async () => {+ scaffoldDefaultExport({exports: SUBPATH_EXPORTS});+ const found = await search('carousel', {cwd: tmpDir});+ const hit = searchImportFor(found, 'AcmeCarousel');+ expect(hit).toBe('@acme/widgets/Carousel');+ },+ SLOW,+ );++ it(+ 'component and search agree on a default-export component',+ async () => {+ scaffoldDefaultExport({exports: SUBPATH_EXPORTS});+ const {detail, found} = await bothSurfaces();+ expect(detail).toBe('@acme/widgets/Carousel');+ expect(found).toBe(detail);+ },+ SLOW,+ );++ it(+ 'list includes the integration import for a default-export component',+ async () => {+ scaffoldDefaultExport({exports: SUBPATH_EXPORTS});+ const result = await component(undefined, {cwd: tmpDir, list: true});+ expect(result.type).toBe('component.list');+ const allEntries = Object.values(result.data.components).flat();+ const entry = allEntries.find(e => e.name === 'AcmeCarousel');+ expect(entry).toBeDefined();+ expect(entry.package).toBe('@acme/widgets');+ // The import must be the integration subpath, not a core path.+ expect(/** @type {any} */ (entry).import).toBe('@acme/widgets/Carousel');+ },+ SLOW,+ );++ it(+ 'list honors a default-export component doc import alias',+ async () => {+ scaffoldDefaultExport({+ exports: SUBPATH_EXPORTS,+ docImport: '@acme/widgets/Alias',+ });+ const result = await component(undefined, {cwd: tmpDir, list: true});+ expect(result.type).toBe('component.list');+ const allEntries = Object.values(result.data.components).flat();+ const entry = allEntries.find(e => e.name === 'AcmeCarousel');+ expect(/** @type {any} */ (entry).import).toBe('@acme/widgets/Alias');+ },+ SLOW,+ );+});diff --git a/packages/cli/api/component/list/list.mjs b/packages/cli/api/component/list/list.mjsindex 50d8aec8f1..b69e95edab 100644--- a/packages/cli/api/component/list/list.mjs+++ b/packages/cli/api/component/list/list.mjs@@ -18,6 +18,7 @@ import {discoverIntegrationComponents,findComponentReadme,resolveImportPath,+ resolveIntegrationImportPath,} from '../../../foundation/discovery/component-discovery.mjs';import {discoverExternalPackages} from '../../../foundation/fs/paths.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';@@ -44,7 +45,10 @@ import {loadComponentDoc, loadIntegrationsSafely} from '../_adapter.mjs';* @param {string|null} opts.lang* @returns {Promise<ComponentListResponse>}*/-export async function componentList(coreDir, {cwd, category, detail, zh, dense, lang}) {+export async function componentList(+ coreDir,+ {cwd, category, detail, zh, dense, lang},+) {const components = discoverComponents(coreDir);if (category) {@@ -67,15 +71,30 @@ export async function componentList(coreDir, {cwd, category, detail, zh, dense,if (readme && readme.endsWith('.doc.mjs')) {try {const docs = await loadComponentDoc(readme, {zh, lang});- entries.push({name: comp, description: docs.usage?.description || docs.description || '', import: resolveImportPath(coreDir, comp)});+ entries.push({+ name: comp,+ description: docs.usage?.description || docs.description || '',+ import: resolveImportPath(coreDir, comp),+ });} catch {- entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ entries.push({+ name: comp,+ description: '',+ import: resolveImportPath(coreDir, comp),+ });}} else {- entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ entries.push({+ name: comp,+ description: '',+ import: resolveImportPath(coreDir, comp),+ });}}- return {type: 'component.list', data: {detail: 'compact', components: {[match[0]]: entries}}};+ return {+ type: 'component.list',+ data: {detail: 'compact', components: {[match[0]]: entries}},+ };}if (detail === 'full') {@@ -93,7 +112,10 @@ export async function componentList(coreDir, {cwd, category, detail, zh, dense,entries.push({name: `XDS${comp}`, description: ''});}}- return {type: 'component.list', data: {detail: 'full', components: {[match[0]]: entries}}};+ return {+ type: 'component.list',+ data: {detail: 'full', components: {[match[0]]: entries}},+ };}// Default: brief — package-qualified object list for the category.@@ -101,7 +123,12 @@ export async function componentList(coreDir, {cwd, category, detail, zh, dense,// strings, so consumers can disambiguate ownership.return {type: 'component.list',- data: {detail: 'names', components: {[match[0]]: match[1].map(n => ({name: n, package: CORE_PACKAGE}))}},+ data: {+ detail: 'names',+ components: {+ [match[0]]: match[1].map(n => ({name: n, package: CORE_PACKAGE})),+ },+ },};}@@ -116,16 +143,31 @@ export async function componentList(coreDir, {cwd, category, detail, zh, dense,if (readme && readme.endsWith('.doc.mjs')) {try {const docs = await loadComponentDoc(readme, {zh, lang});- result[cat].push({name: comp, description: docs.usage?.description || docs.description || '', import: resolveImportPath(coreDir, comp)});+ result[cat].push({+ name: comp,+ description: docs.usage?.description || docs.description || '',+ import: resolveImportPath(coreDir, comp),+ });} catch {- result[cat].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ result[cat].push({+ name: comp,+ description: '',+ import: resolveImportPath(coreDir, comp),+ });}} else {- result[cat].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});+ result[cat].push({+ name: comp,+ description: '',+ import: resolveImportPath(coreDir, comp),+ });}}}- return {type: 'component.list', data: {detail: 'compact', components: result}};+ return {+ type: 'component.list',+ data: {detail: 'compact', components: result},+ };}if (detail === 'full') {@@ -151,7 +193,7 @@ export async function componentList(coreDir, {cwd, category, detail, zh, dense,// Default: brief — package-qualified object list (core + integrations).// Pre-1.0 JSON contract: each group's members are {name, package} objects.- /** @type {Record<string, Array<{name: string, package: string}>>} */+ /** @type {Record<string, ComponentListEntry[]>} */const listData = {};for (const [cat, comps] of Object.entries(components)) {listData[cat] = comps.map(n => ({name: n, package: CORE_PACKAGE}));@@ -166,13 +208,44 @@ export async function componentList(coreDir, {cwd, category, detail, zh, dense,// Group integration components by their doc `group`, falling back to the// package name. Keys are package-qualified so they never collide with// core groups or each other.- /** @type {Map<string, Array<{name: string, package: string}>>} */+ /** @type {Map<string, Array<{name: string, package: string, import?: string}>>} */const byGroup = new Map();for (const rec of owned) {const groupLabel = rec.group ?? integration.name;const key = `${groupLabel} (${integration.name})`;if (!byGroup.has(key)) byGroup.set(key, []);- byGroup.get(key)?.push({name: rec.name, package: integration.name});+ // Use the doc-authored import when present; otherwise resolve the package+ // export so list, detail, search, JSON, and human output all agree.+ const fallbackImport = resolveIntegrationImportPath(+ {+ exportsMap: integration.__packageExports,+ packageDir: integration.__packageDir,+ docPath: rec.docPath,+ packageName: integration.name,+ },+ rec.name,+ );+ let importPath = fallbackImport;+ try {+ const docs = await loadComponentDoc(rec.docPath, {zh, lang});+ importPath = resolveIntegrationImportPath(+ {+ exportsMap: integration.__packageExports,+ packageDir: integration.__packageDir,+ docPath: rec.docPath,+ packageName: integration.name,+ },+ rec.name,+ docs.import,+ );+ } catch {+ // Keep list resilient; validation owns malformed integration docs.+ }+ byGroup.get(key)?.push({+ name: rec.name,+ package: integration.name,+ import: importPath,+ });}for (const [key, members] of byGroup) {members.sort((a, b) => a.name.localeCompare(b.name));@@ -211,5 +284,8 @@ export async function componentList(coreDir, {cwd, category, detail, zh, dense,}}}- return {type: 'component.list', data: {detail: 'names', components: listData}};+ return {+ type: 'component.list',+ data: {detail: 'names', components: listData},+ };}diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex 096d9f2ed4..68c96c463a 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -353,13 +353,21 @@ function resolveConsumerSpecifiers(specifiers, scratchBase) {*/async function validatePackedComponentExports(integration, scratchBase) {const records = discoverIntegrationComponents(integration);+ /** @type {Issue[]} */+ const issues = [];/** @type {Array<{name: string, specifier: string}>} */const components = [];for (const record of records) {let docs;try {docs = await loadComponentDoc(record.docPath);- } catch {+ } catch (err) {+ issues.push(+ error(+ 'component_doc_unloadable',+ `Component "${record.name}" doc at "${record.docPath}" could not be loaded: ${err instanceof Error ? err.message : String(err)}`,+ ),+ );continue;}const specifier =@@ -380,8 +388,6 @@ async function validatePackedComponentExports(integration, scratchBase) {components.map(component => component.specifier),scratchBase,);- /** @type {Issue[]} */- const issues = [];for (const {name, specifier} of components) {const result = resolved.get(specifier);if (!result?.url || result.error) {diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 63ed69e880..1a52650804 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -59,7 +59,10 @@ import {resolveImportPath,resolveIntegrationImportPath,} from '../../foundation/discovery/component-discovery.mjs';-import {discoverHooks, findHookDoc} from '../../foundation/discovery/hook-discovery.mjs';+import {+ discoverHooks,+ findHookDoc,+} from '../../foundation/discovery/hook-discovery.mjs';import {loadIntegrationsSafely} from '../component/_adapter.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';import {discoverTemplates, extractComponents} from '../template/template.mjs';@@ -92,7 +95,17 @@ import {setResultCoverage} from './coverage.mjs';* and its siblings). Lowercase, single words or short phrases.*/const SYNONYMS = {- dashboard: ['overview', 'analytics', 'kpi', 'kpis', 'metrics', 'stats', 'reporting', 'insights', 'control'],+ dashboard: [+ 'overview',+ 'analytics',+ 'kpi',+ 'kpis',+ 'metrics',+ 'stats',+ 'reporting',+ 'insights',+ 'control',+ ],login: ['signin', 'auth', 'authentication', 'sso', 'credentials', 'account'],signup: ['register', 'registration', 'onboarding'],payment: ['checkout', 'billing', 'card', 'pay', 'purchase', 'order'],@@ -153,7 +166,6 @@ export function stem(w) {return s;}-/** Valid domain filters for `--type`. */export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template'];@@ -162,12 +174,66 @@ export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template'];* ("a page where you can see business stats") ranks on its content words.*/const STOPWORDS = new Set([- 'a', 'an', 'the', 'of', 'for', 'to', 'with', 'and', 'or', 'in', 'on', 'at',- 'by', 'that', 'this', 'my', 'your', 'our', 'their', 'is', 'are', 'be', 'it',- 'its', 'as', 'from', 'page', 'screen', 'app', 'application', 'view', 'where',- 'you', 'can', 'some', 'like', 'just', 'basically', 'kinda', 'want', 'wants',- 'need', 'needs', 'something', 'thing', 'things', 'build', 'make', 'create',- 'i', 'me', 'we', 'us', 'so', 'up', 'out', 'over', 'side', 'one', 'big',+ 'a',+ 'an',+ 'the',+ 'of',+ 'for',+ 'to',+ 'with',+ 'and',+ 'or',+ 'in',+ 'on',+ 'at',+ 'by',+ 'that',+ 'this',+ 'my',+ 'your',+ 'our',+ 'their',+ 'is',+ 'are',+ 'be',+ 'it',+ 'its',+ 'as',+ 'from',+ 'page',+ 'screen',+ 'app',+ 'application',+ 'view',+ 'where',+ 'you',+ 'can',+ 'some',+ 'like',+ 'just',+ 'basically',+ 'kinda',+ 'want',+ 'wants',+ 'need',+ 'needs',+ 'something',+ 'thing',+ 'things',+ 'build',+ 'make',+ 'create',+ 'i',+ 'me',+ 'we',+ 'us',+ 'so',+ 'up',+ 'out',+ 'over',+ 'side',+ 'one',+ 'big',]);/**@@ -178,12 +244,14 @@ const STOPWORDS = new Set([* @returns {string[]}*/export function tokenizeQuery(term) {- return term- .split(/\s+/)- // Strip only leading/trailing punctuation; keep joined identifiers intact- // (e.g. "foo_bar" stays one token) so gibberish stays gibberish.- .map(t => t.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, ''))- .filter(t => t.length >= 2 && !STOPWORDS.has(t));+ return (+ term+ .split(/\s+/)+ // Strip only leading/trailing punctuation; keep joined identifiers intact+ // (e.g. "foo_bar" stays one token) so gibberish stays gibberish.+ .map(t => t.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, ''))+ .filter(t => t.length >= 2 && !STOPWORDS.has(t))+ );}/**@@ -227,7 +295,8 @@ function bestForToken(tok, candidate) {const h = scoreCandidate(s, candidate);if (h) {const score = Math.round(h.score * 0.85);- if (!best || score > best.score) best = {score, reason: `${h.reason} (~${tok})`};+ if (!best || score > best.score)+ best = {score, reason: `${h.reason} (~${tok})`};}}}@@ -259,7 +328,8 @@ export function scoreQuery(term, tokens, candidate) {// single words), but if stopwords left exactly one DIFFERENT token (e.g.// "pricing page" → "pricing"), score that token too and take the stronger.if (tokens.length <= 1) {- const single = tokens.length === 1 ? bestForToken(tokens[0], candidate) : null;+ const single =+ tokens.length === 1 ? bestForToken(tokens[0], candidate) : null;if (full && (!single || full.score >= single.score)) return asFull(full);return single ? asFull(single) : null;}@@ -313,7 +383,9 @@ export function scoreQuery(term, tokens, candidate) {// terms can never score lower, since every term of the expression is// non-decreasing in the set of matched tokens.const coverage = matched / tokens.length;- const tokenScore = Math.round(strongest + Math.min(matched - 1, 3) * 12 + coverage * 15);+ const tokenScore = Math.round(+ strongest + Math.min(matched - 1, 3) * 12 + coverage * 15,+ );if (full && full.score >= tokenScore) return asFull(full);return {@@ -341,7 +413,14 @@ export function scoreQuery(term, tokens, candidate) {*/export function scoreCandidate(term,- {name, keywords = [], weakKeywords = [], description = '', prose = [], guidance = []},+ {+ name,+ keywords = [],+ weakKeywords = [],+ description = '',+ prose = [],+ guidance = [],+ },) {let best = 0;let reason = '';@@ -365,7 +444,11 @@ export function scoreCandidate(// Substring (both directions), min 4 chars, >=50% coverage.const shorter = term.length < nameLower.length ? term : nameLower;const longer = term.length < nameLower.length ? nameLower : term;- if (shorter.length >= 4 && longer.includes(shorter) && shorter.length / longer.length >= 0.5) {+ if (+ shorter.length >= 4 &&+ longer.includes(shorter) &&+ shorter.length / longer.length >= 0.5+ ) {consider(60, `name contains "${shorter}"`);}const dist = levenshteinDistance(term, nameLower);@@ -453,7 +536,8 @@ export function scoreCandidate(async function loadModuleDoc(docPath, exportName = 'docs') {try {const mod = await import(pathToFileURL(docPath).href);- return mod[exportName] ?? null;+ // Support both the stamped default export and the legacy named export.+ return mod?.default ?? mod[exportName] ?? null;} catch {return null;}@@ -480,12 +564,20 @@ async function loadModuleDoc(docPath, exportName = 'docs') {function guidanceFrom(doc) {if (!doc) return [];const features = Array.isArray(doc.features) ? doc.features : [];- const practices = Array.isArray(doc.usage?.bestPractices) ? doc.usage.bestPractices : [];+ const practices = Array.isArray(doc.usage?.bestPractices)+ ? doc.usage.bestPractices+ : [];return [...features, ...practices].map(entry =>typeof entry === 'string'? entry- : [entry?.title, entry?.text, entry?.description, entry?.do, entry?.dont]+ : [+ entry?.title,+ entry?.text,+ entry?.description,+ entry?.do,+ entry?.dont,+ ].filter(Boolean).join(' '),)@@ -560,17 +652,16 @@ async function gatherIntegrationComponents(cwd) {// Reporting the bare package name here handed out a path that does not// resolve, and disagreed with what `component <Name>` said about the// very same component.- _import:- doc?.import ??- resolveIntegrationImportPath(- {- exportsMap: integration.__packageExports,- packageDir: integration.__packageDir,- docPath: rec.docPath,- packageName: rec.package,- },- rec.name,- ),+ _import: resolveIntegrationImportPath(+ {+ exportsMap: integration.__packageExports,+ packageDir: integration.__packageDir,+ docPath: rec.docPath,+ packageName: rec.package,+ },+ rec.name,+ doc?.import,+ ),});}}@@ -701,7 +792,9 @@ async function gatherTemplates(cwd) {// category words are a deliberate statement of what the template is for,// while scraped JSX tags only say what it happens to render. See the// scoring table at the top of this file for why the derived set is capped.- const keywords = Array.isArray(t.componentsUsed) ? [...t.componentsUsed] : [];+ const keywords = Array.isArray(t.componentsUsed)+ ? [...t.componentsUsed]+ : [];/** @type {string[]} */let weakKeywords = [];if (t.type === 'page') {@@ -712,7 +805,8 @@ async function gatherTemplates(cwd) {// Best-effort: skip keyword enrichment if the source can't be read.}}- if (t.category) keywords.push(...t.category.split(/[^A-Za-z0-9]+/).filter(Boolean));+ if (t.category)+ keywords.push(...t.category.split(/[^A-Za-z0-9]+/).filter(Boolean));}return {domain: 'template',@@ -814,10 +908,7 @@ export async function search(query, options = {}) {// Validate limit here (not just in the CLI) so direct API callers get the same// contract: a non-positive or non-integer limit is an error, never a silent// "return everything". (Previously `limit <= 0` fell through to the full set.)- if (- limit != null &&- (!Number.isInteger(limit) || limit <= 0)- ) {+ if (limit != null && (!Number.isInteger(limit) || limit <= 0)) {throw new AstryxError(`Invalid limit "${limit}". Must be a positive integer.`,undefined,@@ -852,7 +943,10 @@ export async function search(query, options = {}) {const scored = [];for (const candidate of all) {const hit = scoreQuery(term, tokens, candidate);- if (hit) scored.push(toResult(candidate, hit.score, hit.reason, hit.matched, hit.total));+ if (hit)+ scored.push(+ toResult(candidate, hit.score, hit.reason, hit.matched, hit.total),+ );}// Sort by score desc, then domain (stable order), then name.diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjsindex e2560d41bf..f39cf19df8 100644--- a/packages/cli/clients/cli/commands/component/index.mjs+++ b/packages/cli/clients/cli/commands/component/index.mjs@@ -205,7 +205,10 @@ export function registerComponent(program) {}/** @param {import('../../../../api/component/component.type.mjs').ComponentListEntry} item */const importCell = item => {- const importPath = resolveImportPath(coreDir, item.name);+ // Use a precomputed import when the API supplies one (integration+ // components carry it); only fall back to the core resolver for+ // core components.+ const importPath = item.import ?? resolveImportPath(coreDir, item.name);const qualify =item.package !== CORE_PKG || (nameCounts.get(item.name)?.size ?? 0) > 1;return qualify ? `${importPath} [${item.package}]` : importPath;diff --git a/packages/cli/foundation/discovery/__fixtures__/component-both-exports.doc.mjs b/packages/cli/foundation/discovery/__fixtures__/component-both-exports.doc.mjsnew file mode 100644index 0000000000..c4b0b784ce--- /dev/null+++ b/packages/cli/foundation/discovery/__fixtures__/component-both-exports.doc.mjs@@ -0,0 +1,19 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Fixture: a component doc that has BOTH a default export and a named `docs`+ * export. The default export must win (same precedence as loadComponentDoc).+ */+export default {+ type: 'component',+ name: 'DefaultWinsCard',+ description: 'From the default export.',+ props: [{name: 'priority', type: 'number', description: 'Priority level.'}],+};++export const docs = {+ type: 'component',+ name: 'NamedLosesCard',+ description: 'From the named export — must NOT be returned.',+ props: [],+};diff --git a/packages/cli/foundation/discovery/__fixtures__/component-default-export.doc.mjs b/packages/cli/foundation/discovery/__fixtures__/component-default-export.doc.mjsnew file mode 100644index 0000000000..4a50a881d3--- /dev/null+++ b/packages/cli/foundation/discovery/__fixtures__/component-default-export.doc.mjs@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Fixture: a component doc using the stamped default export convention+ * (what `integration add component` generates). loadDocs must read this+ * shape identically to the legacy named `export const docs` form.+ */+export default {+ type: 'component',+ name: 'DefaultExportCard',+ description: 'A card written with default export.',+ props: [{name: 'title', type: 'string', description: 'Card title.'}],+};diff --git a/packages/cli/foundation/discovery/__fixtures__/component-named-export.doc.mjs b/packages/cli/foundation/discovery/__fixtures__/component-named-export.doc.mjsnew file mode 100644index 0000000000..d83b14ce50--- /dev/null+++ b/packages/cli/foundation/discovery/__fixtures__/component-named-export.doc.mjs@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Fixture: a component doc using the legacy named export convention.+ */+export const docs = {+ type: 'component',+ name: 'NamedExportCard',+ description: 'A card written with named export.',+ props: [{name: 'title', type: 'string', description: 'Card title.'}],+};diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjsindex f77f985d82..d62e7d050a 100644--- a/packages/cli/foundation/discovery/component-discovery.mjs+++ b/packages/cli/foundation/discovery/component-discovery.mjs@@ -375,7 +375,9 @@ export function resolveImportPath(coreDir, componentName) {// Priority 1: exact subpath export matching the component name (e.g. ./Heading)// This allows convenience re-export directories to win over the source directory.- const exactMatch = exportKeys.find(k => k.toLowerCase() === `./${componentName}`.toLowerCase());+ const exactMatch = exportKeys.find(+ k => k.toLowerCase() === `./${componentName}`.toLowerCase(),+ );if (exactMatch) {return `@astryxdesign/core/${exactMatch.slice(2)}`;}@@ -387,7 +389,9 @@ export function resolveImportPath(coreDir, componentName) {const relToSrc = path.relative(srcDir, sourcePath);const topDir = relToSrc.split(path.sep)[0];- const topMatch = exportKeys.find(k => k.toLowerCase() === `./${topDir}`.toLowerCase());+ const topMatch = exportKeys.find(+ k => k.toLowerCase() === `./${topDir}`.toLowerCase(),+ );if (topMatch) {return `@astryxdesign/core/${topMatch.slice(2)}`;}@@ -434,8 +438,9 @@ function exportsPublish(exportsMap, subpath) {}/**- * Resolve the specifier an integration component is imported from, against the- * owning package's `exports` map.+ * Resolve the specifier an integration component is imported from. An authored+ * doc import is canonical; otherwise resolve against the owning package's+ * `exports` map.** A component lives in a directory that need not share its name — several* components can be exported from one entry point — so the specifier has to@@ -461,13 +466,24 @@ function exportsPublish(exportsMap, subpath) {** @param {{exportsMap?: Record<string, unknown>|null, packageDir?: string, docPath?: string|null, packageName: string}} owner* @param {string} componentName+ * @param {string|null} [authoredImport]* @returns {string}*/-export function resolveIntegrationImportPath(owner, componentName) {+export function resolveIntegrationImportPath(+ owner,+ componentName,+ authoredImport,+) {+ if (authoredImport) return authoredImport;const {exportsMap, packageDir, docPath, packageName} = owner;- const map = exportsMap === undefined ? readPackageExports(packageDir) : exportsMap;- const directory = docPath ? path.basename(path.dirname(docPath)) : componentName;- return exportsPublish(map, `./${directory}`) ? `${packageName}/${directory}` : packageName;+ const map =+ exportsMap === undefined ? readPackageExports(packageDir) : exportsMap;+ const directory = docPath+ ? path.basename(path.dirname(docPath))+ : componentName;+ return exportsPublish(map, `./${directory}`)+ ? `${packageName}/${directory}`+ : packageName;}/**@@ -783,4 +799,4 @@ export function discoverOwnedComponents(coreDir, loadedIntegrations = []) {/*** Minimal cleanup for full docs (default mode).* Strips SYNC comments, rewrites title, collapses blank lines.- */\ No newline at end of file+ */diff --git a/packages/cli/foundation/discovery/component-loader.mjs b/packages/cli/foundation/discovery/component-loader.mjsindex 47db469216..540a1708cd 100644--- a/packages/cli/foundation/discovery/component-loader.mjs+++ b/packages/cli/foundation/discovery/component-loader.mjs@@ -140,7 +140,10 @@ export function mergeTranslation(docs, translation) {*/export async function loadDocs(readmePath, {zh = false, dense = false, lang} = {}) {const mod = await import(pathToFileURL(readmePath).href);- const docs = mod.docs;+ // Support both the new stamped default export (`export default {type: 'component', …}`)+ // and the legacy named export (`export const docs = {…}`). Default wins when both+ // are present, matching loadComponentDoc's precedence.+ const docs = mod?.default ?? mod.docs;// Resolve which translation to use (--lang takes priority over legacy flags)const locale = lang || (dense ? 'dense' : zh ? 'zh' : null);diff --git a/packages/cli/foundation/discovery/component-loader.test.mjs b/packages/cli/foundation/discovery/component-loader.test.mjsindex 5c99760e94..c5ee36982a 100644--- a/packages/cli/foundation/discovery/component-loader.test.mjs+++ b/packages/cli/foundation/discovery/component-loader.test.mjs@@ -107,6 +107,54 @@ describe('mergeTranslation — component prop descriptions (regression)', () =>});});+describe('loadDocs — default vs named export resolution', () => {+ const fixtureDir = path.join(import.meta.dirname, '__fixtures__');++ it('reads a default-export .doc.mjs (the shape integration add component writes)', async () => {+ const docs = await loadDocs(path.join(fixtureDir, 'component-default-export.doc.mjs'));+ expect(docs).toBeDefined();+ expect(docs.name).toBe('DefaultExportCard');+ expect(docs.description).toBe('A card written with default export.');+ expect(docs.props).toHaveLength(1);+ expect(docs.props[0].name).toBe('title');+ });++ it('still reads a named-export .doc.mjs (legacy shape)', async () => {+ const docs = await loadDocs(path.join(fixtureDir, 'component-named-export.doc.mjs'));+ expect(docs).toBeDefined();+ expect(docs.name).toBe('NamedExportCard');+ expect(docs.props).toHaveLength(1);+ });++ it('default export agrees with loadComponentDoc', async () => {+ const docPath = path.join(fixtureDir, 'component-default-export.doc.mjs');+ const fromLoadDocs = await loadDocs(docPath);+ const fromLoadComponentDoc = await loadComponentDoc(docPath);+ expect(fromLoadDocs).toEqual(fromLoadComponentDoc);+ });++ it('named export agrees with loadComponentDoc', async () => {+ const docPath = path.join(fixtureDir, 'component-named-export.doc.mjs');+ const fromLoadDocs = await loadDocs(docPath);+ const fromLoadComponentDoc = await loadComponentDoc(docPath);+ expect(fromLoadDocs).toEqual(fromLoadComponentDoc);+ });++ it('default export wins when both default and named exports are present', async () => {+ const docPath = path.join(fixtureDir, 'component-both-exports.doc.mjs');+ const fromLoadDocs = await loadDocs(docPath);+ const fromLoadComponentDoc = await loadComponentDoc(docPath);++ // Default export must win at both loaders+ expect(fromLoadDocs.name).toBe('DefaultWinsCard');+ expect(fromLoadDocs.description).toBe('From the default export.');+ expect(fromLoadDocs.props).toHaveLength(1);+ expect(fromLoadComponentDoc.name).toBe('DefaultWinsCard');+ // And the two must agree+ expect(fromLoadDocs).toEqual(fromLoadComponentDoc);+ });+});+describe('loadComponentDoc — full localized doc overlays', () => {it('inherits canonical anatomy when docsZh omits it and matches loadDocs', async () => {const docPath = path.join(diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 2c0ca54e45..660cff067d 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -31,7 +31,7 @@ export const doc = {{value: 'component.list',description:- 'The component catalog grouped by category: `detail` (the level: names | compact | full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry.',+ 'The component catalog grouped by category: `detail` (the level: names | compact | full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries, or a full ComponentDoc per entry.',},{value: 'component.detail',