An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): list and search VStack, HStack and Heading, whose docs live in their family's folder (#7625)
Joey2ec83d72a1f6
diff --git a/.changeset/component-list-family-docs.md b/.changeset/component-list-family-docs.mdnew file mode 100644index 0000000000..3d0ce31a48--- /dev/null+++ b/.changeset/component-list-family-docs.md@@ -0,0 +1,15 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx component --list` and `astryx search` find VStack, HStack and Heading++Each has its own import path, but its doc lives in its family's folder: Stack's+doc documents HStack and VStack, and Heading's doc sits next to Text's. The list+only counted a doc in the component's own folder, so the three were missing from+the list and from search, and `astryx component VStack` found its doc only+through fuzzy matching. A component whose doc is elsewhere is now listed and+searchable with its own import path, and `astryx component VStack` opens its doc+directly.++@josephfarinadiff --git a/packages/cli/api/component/component.test.mjs b/packages/cli/api/component/component.test.mjsindex 8ec2cb81ab..e48753a212 100644--- a/packages/cli/api/component/component.test.mjs+++ b/packages/cli/api/component/component.test.mjs@@ -13,6 +13,7 @@ import {describe, it, expect} from 'vitest';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {component} from './component.mjs';+import {search} from '../search/search.mjs';import {AstryxError} from '../error.mjs';import {runCli} from '../../test-utils/run-cli.mjs';@@ -92,6 +93,85 @@ describe('component dispatcher — detail levels on list', () => {);});+describe('component list — components whose docs live in a family folder', () => {+ it('lists HStack, VStack and Heading at every detail level, each with its own import', async () => {+ const {docs: stackDoc} = await import(+ path.join(REPO, 'packages', 'core', 'src', 'Stack', 'Stack.doc.mjs')+ );+ const vstackMember = stackDoc.components.find(c => c.name === 'VStack');++ const names = await component(undefined, {cwd, list: true});+ const listed = Object.values(names.data.components).flat();+ for (const name of ['HStack', 'VStack', 'Heading']) {+ expect(listed).toContainEqual({name, package: '@astryxdesign/core'});+ }++ const compact = await component(undefined, {cwd, list: true, detail: 'compact'});+ const brief = Object.values(compact.data.components).flat();+ expect(brief.find(e => e.name === 'VStack')).toEqual({+ name: 'VStack',+ package: '@astryxdesign/core',+ description: vstackMember.description,+ import: '@astryxdesign/core/VStack',+ });++ const full = await component(undefined, {cwd, list: true, detail: 'full'});+ const entry = Object.values(full.data.components)+ .flat()+ .find(e => e.name === 'VStack');+ // Shaped like every other full entry (a component doc plus its package):+ // the member's own name, display name and summary, and no scoping field+ // the full-entry type does not describe.+ expect(entry).toEqual({+ name: 'VStack',+ package: '@astryxdesign/core',+ displayName: vstackMember.displayName,+ group: stackDoc.group,+ category: stackDoc.category,+ usage: {description: vstackMember.description},+ props: vstackMember.props,+ theming: stackDoc.theming,+ import: '@astryxdesign/core/VStack',+ });+ }, SLOW);++ it('prints each one\'s own import path in the list, the detail, and search', async () => {+ // The path `component <Name>` prints is the one docs and examples teach:+ // the component's own entry point, never its family's (/Stack, /Text) or+ // a re-export (/Layout).+ const compact = Object.values(+ (await component(undefined, {cwd, list: true, detail: 'compact'})).data.components,+ ).flat();+ const full = Object.values(+ (await component(undefined, {cwd, list: true, detail: 'full'})).data.components,+ ).flat();+ const textList = (await runCli(['component', '--list'], cwd)).stdout;+ const textCompact = (+ await runCli(['component', '--list', '--detail', 'compact'], cwd)+ ).stdout;+ /** The `import:` line of a text record, found by its `name:` line. */+ const textImport = (text, name) =>+ new RegExp(`^name:\\s+${name}\\n(?:(?!name:).*\\n)*?import:\\s+(\\S+)`, 'm').exec(+ text,+ )?.[1];+ for (const name of ['VStack', 'HStack', 'Heading']) {+ const expected = `@astryxdesign/core/${name}`;+ expect(compact.find(e => e.name === name)?.import).toBe(expected);+ expect((await component(name, {cwd})).data.import).toBe(expected);+ const hits = (await search(name, {cwd, type: 'component'})).data.results;+ expect(hits.find(r => r.name === name)?.import).toBe(expected);+ expect(textImport(textList, name)).toBe(expected);+ expect(textImport(textCompact, name)).toBe(expected);+ }+ // The full level spreads a component's own doc, which states no import+ // (Button's entry has none either); a member's entry is scoped to the+ // member and states its own.+ for (const name of ['VStack', 'HStack']) {+ expect(full.find(e => e.name === name)?.import).toBe(`@astryxdesign/core/${name}`);+ }+ }, SLOW);+});+describe('component dispatcher — projection precedence (locked)', () => {it('--props routes to component.detail.props',diff --git a/packages/cli/api/component/list/list.mjs b/packages/cli/api/component/list/list.mjsindex bfabf5d618..855f1baa57 100644--- a/packages/cli/api/component/list/list.mjs+++ b/packages/cli/api/component/list/list.mjs@@ -16,6 +16,7 @@ import {discoverComponents,discoverExternalComponentsGrouped,discoverValidIntegrationComponents,+ familyMember,findComponentReadme,findExternalComponentDoc,resolveImportPath,@@ -66,6 +67,33 @@ async function legacyImport(ext, name, coreDir, docOpts) {*/const coreEntry = doc => ({name: doc.name, package: CORE_PACKAGE, ...doc});+/**+ * The full-level entry for a component documented as a member of its family's+ * doc (VStack in Stack's doc): a component doc built from the member's own+ * entry, under its own name, display name and import, shaped like every other+ * full entry. Null when the doc is the component's own.+ * @param {any} docs+ * @param {string} name+ * @param {string} coreDir+ * @returns {any}+ */+function memberEntry(docs, name, coreDir) {+ const member = familyMember(docs, name);+ if (!member) return null;+ return {+ name,+ package: CORE_PACKAGE,+ displayName: member.displayName ?? name,+ ...(docs.group ? {group: docs.group} : {}),+ ...(docs.category ? {category: docs.category} : {}),+ usage: member.usage ?? {description: member.description ?? ''},+ props: member.props ?? [],+ ...(member.examples ? {examples: member.examples} : {}),+ ...(docs.theming ? {theming: docs.theming} : {}),+ import: resolveImportPath(coreDir, name),+ };+}+/*** The entry for a Core slot an integration component replaces* (spec:AST-035 FR11), at the list's detail level: the replacement's own name,@@ -177,7 +205,11 @@ export async function componentList(entries.push({name: comp,package: CORE_PACKAGE,- description: docs.usage?.description || docs.description || '',+ description:+ familyMember(docs, comp)?.description ||+ docs.usage?.description ||+ docs.description ||+ '',import: resolveImportPath(coreDir, comp),});} catch {@@ -215,7 +247,8 @@ export async function componentList(const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {- entries.push(coreEntry(await loadComponentDoc(readme, {zh, lang, dense})));+ const docs = await loadComponentDoc(readme, {zh, lang, dense});+ entries.push(memberEntry(docs, comp, coreDir) ?? coreEntry(docs));} catch {entries.push({name: `XDS${comp}`, package: CORE_PACKAGE, description: ''});}@@ -269,7 +302,11 @@ export async function componentList(result[cat].push({name: comp,package: CORE_PACKAGE,- description: docs.usage?.description || docs.description || '',+ description:+ familyMember(docs, comp)?.description ||+ docs.usage?.description ||+ docs.description ||+ '',import: resolveImportPath(coreDir, comp),});} catch {@@ -310,7 +347,8 @@ export async function componentList(const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {- result[cat].push(coreEntry(await loadComponentDoc(readme, {zh, lang, dense})));+ const docs = await loadComponentDoc(readme, {zh, lang, dense});+ result[cat].push(memberEntry(docs, comp, coreDir) ?? coreEntry(docs));} catch {result[cat].push({name: `XDS${comp}`, package: CORE_PACKAGE, description: ''});}diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 2f12d86f33..beefeee190 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -85,6 +85,7 @@ import {findCoreDir} from '../../foundation/fs/paths.mjs';import {discoverComponents,discoverValidIntegrationComponents,+ familyMember,findComponentReadme,resolveImportPath,resolveIntegrationImportPath,@@ -1079,7 +1080,11 @@ async function gatherCoreComponents(coreDir) {/** @type {string[]} */let guidance = [];if (readme && readme.endsWith('.doc.mjs')) {- const doc = await loadModuleDoc(readme);+ const loaded = await loadModuleDoc(readme);+ // A member documented in its family's doc (VStack in Stack's doc) is+ // indexed from its own entry: the family's keywords and guidance+ // describe the family, not the member.+ const doc = familyMember(loaded, comp) ?? loaded;if (doc) {keywords = Array.isArray(doc.keywords) ? doc.keywords : [];description = doc.usage?.description || doc.description || '';@@ -1225,11 +1230,11 @@ export async function componentKeywords(coreDir, cwd) {.flat().map(async name => {const readme = findComponentReadme(coreDir, name);- const doc =+ const loaded =readme && readme.endsWith('.doc.mjs')? await loadModuleDoc(readme): null;- return {name, keywords: keywordsOf(doc)};+ return {name, keywords: keywordsOf(familyMember(loaded, name) ?? loaded)};});const loadedIntegrations = await loadIntegrationsSafely(cwd);const replacements = await loadComponentReplacements(diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjsindex f7b85c503d..de763fb22c 100644--- a/packages/cli/api/search/search.test.mjs+++ b/packages/cli/api/search/search.test.mjs@@ -616,6 +616,42 @@ describe('search leaf — a theme is found by its names; its description is pros);});+describe('search leaf — components whose docs live in a family folder', () => {+ it("indexes a family member from its own entry, not the family's keywords", async () => {+ // HStack and VStack are documented in Stack's doc, whose keywords+ // (horizontal, vertical, row, column, ...) describe Stack.+ const reasons = async (/** @type {string} */ query) =>+ Object.fromEntries(+ (await search(query, {cwd, type: 'component'})).data.results.map(r => [+ r.name,+ r.reason,+ ]),+ );+ const column = await reasons('column');+ expect(column.HStack ?? '').not.toMatch(/keyword/);+ expect(column.VStack ?? '').not.toMatch(/keyword/);+ expect(column.Stack).toMatch(/keyword/);+ const vertical = (await search('vertical', {cwd, type: 'component'})).data.results.map(+ r => r.name,+ );+ expect(vertical.indexOf('VStack')).toBeGreaterThanOrEqual(0);+ if (vertical.includes('HStack')) {+ expect(vertical.indexOf('VStack')).toBeLessThan(vertical.indexOf('HStack'));+ }+ }, SLOW);++ it('ranks VStack, HStack and Heading first for their own names, with their own import', async () => {+ for (const name of ['VStack', 'HStack', 'Heading']) {+ const r = await search(name.toLowerCase(), {cwd, type: 'component'});+ expect(r.data.results[0]).toMatchObject({+ domain: 'component',+ name,+ import: `@astryxdesign/core/${name}`,+ });+ }+ }, SLOW);+});+describe('search leaf — integration components', () => {/*** A minimal consumer project: a stub `@astryxdesign/core` (so `findCoreDir`diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjsindex 53802c50b7..da4977c414 100644--- a/packages/cli/foundation/discovery/component-discovery.mjs+++ b/packages/cli/foundation/discovery/component-discovery.mjs@@ -5,12 +5,15 @@*/import * as fs from 'node:fs';+import {createRequire} from 'node:module';import * as path from 'node:path';import {listDir, listDirEntries, pathExists} from '../fs/listing-cache.mjs';import {existsCaseExact} from '../fs/paths.mjs';import {CORE_PROVIDER_ID} from '../identity/providers.mjs';import {loadComponentDoc} from './component-loader.mjs';+const require = createRequire(import.meta.url);+const SKIP_DIRS = new Set(['hooks', 'utils', '__tests__', 'node_modules']);/** The owner package name for built-in (core) components. */@@ -109,8 +112,193 @@ function readDocMeta(docPath) {}}+/** @type {typeof import('@babel/parser') | undefined} */+let babelParser;++/**+ * A property of an object literal, by its plain key.+ * @param {any} object - an ObjectExpression node+ * @param {string} key+ * @returns {any}+ */+function propertyValue(object, key) {+ for (const property of object.properties) {+ if (property.type !== 'ObjectProperty' || property.computed) continue;+ const name =+ property.key.type === 'Identifier'+ ? property.key.name+ : property.key.type === 'StringLiteral'+ ? property.key.value+ : null;+ if (name === key) return property.value;+ }+ return null;+}++/**+ * The names a component doc lists as `components` members, read from its+ * source without running it. Only a static `{name: '<Name>'}` entry in the doc+ * object the loader reads (the `default` export, else `docs`) counts: a name in+ * prose, an example, or `relatedComponents` is not a member.+ * @param {string} source - the doc file's text+ * @returns {string[]}+ */+function docMemberNames(source) {+ /** @type {any} */+ let ast;+ try {+ babelParser ??= require('@babel/parser');+ ast = /** @type {typeof import('@babel/parser')} */ (babelParser).parse(source, {+ sourceType: 'module',+ });+ } catch {+ return [];+ }+ /** @type {Map<string, any>} */+ const constants = new Map();+ let defaultExport = null;+ let docsExport = null;+ for (const node of ast.program.body) {+ const declaration =+ node.type === 'ExportNamedDeclaration' ? node.declaration : node;+ if (declaration?.type === 'VariableDeclaration') {+ for (const declarator of declaration.declarations) {+ if (declarator.id.type !== 'Identifier' || !declarator.init) continue;+ constants.set(declarator.id.name, declarator.init);+ if (node.type === 'ExportNamedDeclaration' && declarator.id.name === 'docs') {+ docsExport = declarator.init;+ }+ }+ }+ if (node.type === 'ExportDefaultDeclaration') defaultExport = node.declaration;+ }+ let doc = defaultExport ?? docsExport;+ if (doc?.type === 'Identifier') doc = constants.get(doc.name);+ if (doc?.type !== 'ObjectExpression') return [];+ const members = propertyValue(doc, 'components');+ if (members?.type !== 'ArrayExpression') return [];+ return members.elements.flatMap((/** @type {any} */ element) => {+ if (element?.type !== 'ObjectExpression') return [];+ const name = propertyValue(element, 'name');+ return name?.type === 'StringLiteral' ? [name.value] : [];+ });+}++/**+ * Whether `name` has its own component folder in Core: `src/<Name>/<Name>.tsx`+ * (or the `XDS`-prefixed form).+ * @param {string} srcDir+ * @param {string} name+ * @returns {boolean}+ */+function hasOwnFolder(srcDir, name) {+ return [`${name}.tsx`, `XDS${name}.tsx`].some(file =>+ existsCaseExact(path.join(srcDir, name, file), srcDir),+ );+}++/**+ * Member names read in this process, by doc path, reused while the file keeps+ * its size and mtime.+ * @type {Map<string, {size: number, mtimeMs: number, members: string[]}>}+ */+const memberReads = new Map();++/**+ * The names a doc lists as `components` members (see docMemberNames).+ * @param {string} docPath+ * @returns {string[]}+ */+function readDocMembers(docPath) {+ let stat;+ try {+ stat = fs.statSync(docPath);+ } catch {+ return [];+ }+ const cached = memberReads.get(docPath);+ if (cached && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) {+ return cached.members;+ }+ /** @type {string[]} */+ let members;+ try {+ members = docMemberNames(fs.readFileSync(docPath, 'utf-8'));+ } catch {+ members = [];+ }+ memberReads.set(docPath, {size: stat.size, mtimeMs: stat.mtimeMs, members});+ return members;+}++// A sibling component folder named by a relative import or re-export.+const SIBLING_IMPORT_RE =+ /(?:\bfrom|\bimport\s*\()\s*['"]\.\.\/([A-Za-z0-9_-]+)(?:\/[^'"]*)?['"]/g;++/**+ * The Core doc that documents `name` as one of its `components` members: the+ * doc of a component it builds on. HStack and VStack import Stack, and Stack's+ * doc lists them, so each has its own folder and import path but no doc of its+ * own. Only the folders the component's own source imports from are read.+ * @param {string} srcDir+ * @param {string} name+ * @returns {string | null}+ */+function findFamilyDoc(srcDir, name) {+ const sourcePath = [`${name}.tsx`, `XDS${name}.tsx`]+ .map(file => path.join(srcDir, name, file))+ .find(file => existsCaseExact(file, srcDir));+ if (!sourcePath) return null;+ let source;+ try {+ source = fs.readFileSync(sourcePath, 'utf-8');+ } catch {+ return null;+ }+ const families = [+ ...new Set([...source.matchAll(SIBLING_IMPORT_RE)].map(match => match[1])),+ ]+ .filter(dir => dir !== name && !SKIP_DIRS.has(dir))+ .sort();+ for (const dir of families) {+ const dirPath = path.join(srcDir, dir);+ if (!existsCaseExact(dirPath, srcDir)) continue;+ for (const file of [...listDir(dirPath)].sort()) {+ if (!file.endsWith('.doc.mjs')) continue;+ const docPath = path.join(dirPath, file);+ const members = readDocMembers(docPath);+ if (members.includes(name) || members.includes(`XDS${name}`)) {+ return docPath;+ }+ }+ }+ return null;+}++/**+ * The entry a family doc gives `name` in its `components`, when the doc is not+ * the component's own (Stack's doc for VStack); null otherwise.+ * @param {any} docs - a loaded component doc+ * @param {string} name - bare component name+ * @returns {any}+ */+export function familyMember(docs, name) {+ if (!docs || docs.name === name || docs.name === `XDS${name}`) return null;+ const members = Array.isArray(docs.components) ? docs.components : [];+ return (+ members.find(+ (/** @type {any} */ member) =>+ member?.name === name || member?.name === `XDS${name}`,+ ) ?? null+ );+}+/*** Auto-discover components by scanning for Astryx*.tsx files in core/src/.+ * A component is listed when a doc documents it: a doc in its folder, or, for a+ * component folder with no doc of its own, the doc `findComponentReadme` finds+ * elsewhere (Heading's doc in the Text folder; HStack and VStack as members of+ * Stack's doc).** Returns an ordered Record where:* - Grouped components use the group name as key: `'Buttons': ['Button', 'IconButton']`@@ -192,6 +380,25 @@ export function discoverComponents(coreDir) {}}+ // A component folder with no doc in it is still listed when a doc elsewhere+ // documents it, the doc `component <Name>` opens: its own same-stem doc in a+ // family folder (Text/Heading.doc.mjs), or a member entry in the family's doc+ // (HStack and VStack in Stack's doc).+ for (const entry of topEntries) {+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name)) continue;+ const name = entry.name;+ if (componentGroups.has(name) || name.endsWith('Context')) continue;+ if (listDir(path.join(srcDir, name)).some(file => file.endsWith('.doc.mjs'))) {+ continue;+ }+ if (!hasOwnFolder(srcDir, name)) continue;+ const docPath = findComponentReadme(coreDir, name);+ if (!docPath?.endsWith('.doc.mjs')) continue;+ const meta = readDocMeta(docPath);+ if (meta.hidden || meta.hiddenComponents.has(name)) continue;+ componentGroups.set(name, meta.group);+ }+// Build the result: group name → sorted members, or component name → [self]/** @type {Map<string, string[]>} */const groups = new Map();@@ -284,6 +491,10 @@ export function findComponentReadme(coreDir, name) {}}+ // A component with its own folder, documented as a member of its family's+ // doc (HStack and VStack in Stack's doc).+ if (hasOwnFolder(srcDir, name)) return findFamilyDoc(srcDir, name);+return null;}diff --git a/packages/cli/foundation/discovery/component-discovery.test.mjs b/packages/cli/foundation/discovery/component-discovery.test.mjsindex cbe7c9f103..74cab3355c 100644--- a/packages/cli/foundation/discovery/component-discovery.test.mjs+++ b/packages/cli/foundation/discovery/component-discovery.test.mjs@@ -16,6 +16,7 @@ import {fileURLToPath} from 'node:url';import {CORE_PACKAGE,discoverComponents,+ familyMember,findComponentReadme,findComponentSource,resolveImportPath,@@ -121,6 +122,91 @@ describe('discoverComponents (real core)', () => {expect(discoverComponents(core)).toEqual({});});+ it('lists HStack, VStack and Heading, whose docs live in their family folders', () => {+ // Each has its own folder and import path; Stack's doc documents HStack and+ // VStack as members, and Heading's own doc sits in the Text folder.+ const comps = discoverComponents(CORE);+ expect(comps.Layout).toEqual(expect.arrayContaining(['HStack', 'Stack', 'VStack']));+ expect(comps.Heading).toEqual(['Heading']);+ expect(findComponentReadme(CORE, 'VStack')).toMatch(/[\\/]Stack[\\/]Stack\.doc\.mjs$/);+ expect(findComponentReadme(CORE, 'HStack')).toMatch(/[\\/]Stack[\\/]Stack\.doc\.mjs$/);+ expect(findComponentReadme(CORE, 'Heading')).toMatch(/[\\/]Text[\\/]Heading\.doc\.mjs$/);+ expect(resolveImportPath(CORE, 'VStack')).toBe('@astryxdesign/core/VStack');+ expect(resolveImportPath(CORE, 'Heading')).toBe('@astryxdesign/core/Heading');+ }, SLOW);++ it('lists a component folder with no doc when its family doc lists it as a member', () => {+ const core = mkTmp('as-cd-family-');+ const write = (rel, text) => {+ fs.mkdirSync(path.dirname(path.join(core, 'src', rel)), {recursive: true});+ fs.writeFileSync(path.join(core, 'src', rel), text);+ };+ write('Stack/Stack.tsx', 'x');+ write('VStack/VStack.tsx', "import {Stack} from '../Stack/Stack';\n");+ write('Prose/Prose.tsx', "import {Stack} from '../Stack/Stack';\n");+ // Listed by Stack's doc, but builds on nothing in Stack's folder.+ write('Orphan/Orphan.tsx', "import {x} from '../utils';\n");+ write(+ 'Stack/Stack.doc.mjs',+ 'export const docs = {\n' ++ " name: 'Stack',\n" ++ " group: 'Layout',\n" ++ " relatedComponents: ['Prose'],\n" ++ " usage: {description: 'Pair with Prose.', examples: [{code: \"<Prose label='Prose' />\"}]},\n" ++ " components: [{name: 'Stack'}, {name: 'VStack', description: 'Vertical.'}, {name: 'Orphan'}],\n" ++ '};\n',+ );+ expect(discoverComponents(core)).toEqual({Layout: ['Stack', 'VStack']});+ expect(findComponentReadme(core, 'VStack')).toBe(+ path.join(core, 'src', 'Stack', 'Stack.doc.mjs'),+ );+ // Named only in relatedComponents, prose, and an example: not documented.+ expect(findComponentReadme(core, 'Prose')).toBeNull();+ // A family doc is read only from the folders the component imports.+ expect(findComponentReadme(core, 'Orphan')).toBeNull();+ });++ it('lists a component folder with no doc when its own doc sits in a family folder', () => {+ const core = mkTmp('as-cd-sibling-');+ for (const dir of ['Text', 'Heading']) {+ fs.mkdirSync(path.join(core, 'src', dir), {recursive: true});+ }+ fs.writeFileSync(path.join(core, 'src', 'Text', 'Text.tsx'), 'x');+ fs.writeFileSync(path.join(core, 'src', 'Heading', 'Heading.tsx'), 'x');+ fs.writeFileSync(+ path.join(core, 'src', 'Text', 'Text.doc.mjs'),+ "export const docs = {name: 'Text', components: [{name: 'Heading'}]};\n",+ );+ fs.writeFileSync(+ path.join(core, 'src', 'Text', 'Heading.doc.mjs'),+ "export const docs = {name: 'Heading'};\n",+ );+ expect(discoverComponents(core)).toEqual({Heading: ['Heading'], Text: ['Text']});+ expect(findComponentReadme(core, 'Heading')).toBe(+ path.join(core, 'src', 'Text', 'Heading.doc.mjs'),+ );+ });++ it('keeps a member its family hides, and a context folder, unlisted', () => {+ const core = mkTmp('as-cd-family-hidden-');+ for (const dir of ['Stack', 'VStack', 'SizeContext']) {+ fs.mkdirSync(path.join(core, 'src', dir), {recursive: true});+ fs.writeFileSync(+ path.join(core, 'src', dir, `${dir}.tsx`),+ "import {Stack} from '../Stack/Stack';\n",+ );+ }+ fs.writeFileSync(+ path.join(core, 'src', 'Stack', 'Stack.doc.mjs'),+ 'export const docs = {\n' ++ " name: 'Stack',\n" ++ " hiddenComponents: ['VStack'],\n" ++ " components: [{name: 'Stack'}, {name: 'VStack'}, {name: 'SizeContext'}],\n" ++ '};\n',+ );+ expect(discoverComponents(core)).toEqual({Stack: ['Stack']});+ });+it('returns {} for an empty src/ dir', () => {const core = mkTmp('as-cd-emptysrc-');fs.mkdirSync(path.join(core, 'src'));@@ -133,6 +219,16 @@ describe('discoverComponents (real core)', () => {});});+describe('familyMember', () => {+ it("returns a family doc's entry for a member, and null for a component's own doc", () => {+ const stack = {name: 'Stack', components: [{name: 'Stack'}, {name: 'VStack', description: 'v'}]};+ expect(familyMember(stack, 'VStack')).toEqual({name: 'VStack', description: 'v'});+ expect(familyMember(stack, 'Stack')).toBeNull();+ expect(familyMember({name: 'Button'}, 'Button')).toBeNull();+ expect(familyMember(stack, 'HStack')).toBeNull();+ });+});+describe('findComponentReadme / findComponentSource / resolveImportPath', () => {it('finds the doc + source for a top-level component', () => {expect(findComponentReadme(CORE, 'Button')).toMatch(/Button\.doc\.mjs$/);diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex d6fdbdb40d..1033dad299 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -246,6 +246,10 @@ const RUNNERS = {runs: 'astryx.config, through the config parser',sites: ['loadModuleWithParser(..., parseConfig)'],},+ 'foundation/discovery/component-discovery.mjs': {+ runs: '@babel/parser, on first use, to read the members a family doc lists in its components without running the doc',+ sites: ['require(@babel/parser)'],+ },'foundation/discovery/docs-discovery.mjs': {runs: 'a contributed topic, for its catalog fields: name, title, description, category, and relationships',sites: ['importDocModule'],diff --git a/packages/cli/foundation/doc-compiler/inputs.mjs b/packages/cli/foundation/doc-compiler/inputs.mjsindex 48f3ac2125..3330cebb34 100644--- a/packages/cli/foundation/doc-compiler/inputs.mjs+++ b/packages/cli/foundation/doc-compiler/inputs.mjs@@ -81,8 +81,31 @@ const NON_DESCRIPTOR_DIRS = new Set([export async function collectDocInputs(project) {const list = new InputList();+ // A component documented as a member of its family's doc (HStack and VStack+ // in Stack's doc) is read through the family's own entry: one descriptor,+ // one reader. Own docs go first so the family keeps its name.+ /** @type {Array<{name: string, package: string, docPath: string}>} */+ const ownDocs = [];+ /** @type {Array<{name: string, package: string, docPath: string}>} */+ const familyDocs = [];for (const record of await project.components()) {if (record.docPath == null) continue;+ const stem = path+ .basename(record.docPath)+ .replace(/\.doc\.[cm]?[jt]s$/u, '')+ .replace(/^XDS/u, '');+ const entry = {+ name: record.name,+ package: record.package,+ docPath: record.docPath,+ };+ (stem === record.name ? ownDocs : familyDocs).push(entry);+ }+ for (const record of ownDocs) {+ list.add('components', record.name, record.package, record.docPath);+ }+ for (const record of familyDocs) {+ if (list.claims(record.docPath)) continue;list.add('components', record.name, record.package, record.docPath);}diff --git a/packages/cli/foundation/doc-compiler/inputs.test.mjs b/packages/cli/foundation/doc-compiler/inputs.test.mjsindex 8a8ee97e23..2fde9abc42 100644--- a/packages/cli/foundation/doc-compiler/inputs.test.mjs+++ b/packages/cli/foundation/doc-compiler/inputs.test.mjs@@ -91,7 +91,6 @@ describe('collectDocInputs over what this repo ships', () => {'Chat','ChatComposerTokenElement','ContextMenuItem',- 'Heading','Indicator','Layer','NavMenu',diff --git a/packages/cli/foundation/xle/registry.mjs b/packages/cli/foundation/xle/registry.mjsindex 46a5c70d0b..8863c0a5f3 100644--- a/packages/cli/foundation/xle/registry.mjs+++ b/packages/cli/foundation/xle/registry.mjs@@ -20,6 +20,7 @@ import path from 'node:path';import {findCoreDir} from '../fs/paths.mjs';import {discoverComponents,+ familyMember,findComponentReadme,resolveImportPath,} from '../discovery/component-discovery.mjs';@@ -126,6 +127,9 @@ export async function buildRegistry({cwd = process.cwd()} = {}) {} catch {continue; // a malformed doc must not take down the whole language}+ // A member documented in its family's doc (VStack in Stack's doc) is+ // registered by the family's own folder, with every other member.+ if (familyMember(docs, dirName)) continue;const importPath = resolveImportPath(coreDir, dirName);const register = (/** @type {string} */ rawName, /** @type {import('./xle-ast').DocProp[]} */ props) => {diff --git a/packages/cli/foundation/xle/registry.test.mjs b/packages/cli/foundation/xle/registry.test.mjsnew file mode 100644index 0000000000..fa080c9fbc--- /dev/null+++ b/packages/cli/foundation/xle/registry.test.mjs@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The layout-language registry over the real @astryxdesign/core tree:+ * the import path it emits for each component.+ */++import {describe, it, expect} from 'vitest';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {buildRegistry} from './registry.mjs';++const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');++describe('buildRegistry import paths', () => {+ it('keeps the Stack family on the paths it registers from Stack\'s folder', async () => {+ // HStack and VStack are listed components whose docs live in Stack's doc.+ // Listing them must not let their folders re-register the family under+ // their own paths: a member's folder registers nothing, Stack's does.+ const {components} = await buildRegistry({cwd: REPO});+ const importOf = (/** @type {string} */ name) => components.get(name)?.importPath;+ for (const name of ['Stack', 'StackItem', 'HStack', 'VStack']) {+ expect(importOf(name), name).toBe('@astryxdesign/core/Stack');+ }+ expect(importOf('Heading')).toBe('@astryxdesign/core/Heading');+ expect(importOf('Text')).toBe('@astryxdesign/core/Text');+ }, 120_000);+});