Skip to content

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

TypeScript

feat(cli): integration family members are components under their own names (#7674)

Joey91cfb530b64f
diff --git a/.changeset/cli-component-family-members.md b/.changeset/cli-component-family-members.md
new file mode 100644
index 0000000000..759d67b36f
--- /dev/null
+++ b/.changeset/cli-component-family-members.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Each full entry an integration's family doc lists in `components`, such as `AcmeSlide` in an `AcmeCarousel` doc, is a component under its own name when the module the doc's `import` names exports it. Its source is the `.tsx` file in the family's folder that declares it; a member that only built output or a file outside that folder declares has no source to show or copy. `component --list`, `component <Name>`, `search`, `swizzle`, the `doctor integration` checks, `integration verify` and `integration add` know these members. A member's detail is scoped to its own entry, as a Core sub-component's is, and it never carries the family's `replaces`. A member named like a Core component or another doc's file opens with `--package`.
+
+@josephfarina
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
index e777331a49..98d8914f90 100644
--- a/packages/cli/api/component/_adapter.mjs
+++ b/packages/cli/api/component/_adapter.mjs
@@ -33,6 +33,9 @@ import {
findComponentSource,
findExternalComponentDoc,
findIntegrationComponent,
+ integrationMemberEntry,
+ isIntegrationMember,
+ recordedDocName,
resolveImportPath,
resolveIntegrationImportPath as resolveIntegrationImport,
unscopedComponentOwners,
@@ -621,3 +624,48 @@ export function scopeSubComponent(docs, dirName, coreDir) {
return {scoped, matchingComponent};
}
+
+/**
+ * The doc an integration owner shows for `dirName`: when `dirName` is a member
+ * its family doc lists under its own name (`AcmeSlide` in an `AcmeCarousel`
+ * doc), the doc scoped to that member as {@link scopeSubComponent} scopes
+ * Core's, keeping the import the family doc states; otherwise `docs` itself.
+ * @param {LoadedComponentDoc} docs
+ * @param {OwnershipSubject} owner
+ * @param {string} dirName
+ * @returns {LoadedComponentDoc & {parentDoc?: string, import?: string}}
+ */
+export function scopeIntegrationMember(docs, owner, dirName) {
+ const record = {name: dirName, docPath: owner.docPath ?? null};
+ if (!isIntegrationMember(record)) return docs;
+ const entry = integrationMemberEntry(docs, record);
+ // The files list the member but the doc this process loaded has no entry
+ // for it (the doc changed after it loaded): never answer with the family.
+ if (entry == null) {
+ throw new AstryxError(
+ `No component named "${dirName}": its family doc changed after this process loaded it.`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+ // Built from the entry, as scopeSubComponent scopes Core's, so a member that
+ // shares the doc's own `name` is scoped too.
+ /** @type {LoadedComponentDoc & {parentDoc?: string, import?: string}} */
+ const scoped = {
+ name: dirName,
+ description: entry.description,
+ props: entry.props,
+ components: [entry],
+ // The name the family doc opens under, for every member.
+ parentDoc:
+ owner.integration && record.docPath
+ ? recordedDocName(owner.integration, record.docPath)
+ : docs.name === dirName && record.docPath
+ ? docStem(record.docPath)
+ : docs.name,
+ };
+ if (docs.usage) scoped.usage = docs.usage;
+ if (docs.theming) scoped.theming = docs.theming;
+ if (docs.import) scoped.import = docs.import;
+ return scoped;
+}
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index 52bce5a8e7..81aaeb2321 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -19,6 +19,7 @@ import {
requireCoreDir,
loadIntegrationsSafely,
resolveOwners,
+ scopeIntegrationMember,
classifyScope,
assertUnambiguousOwners,
resolveLegacyExternalDoc,
@@ -429,7 +430,13 @@ export async function component(name, options = {}) {
if (blocks) {
return componentDetailBlocks(dirName, cwd, owner.package);
}
- const docs = await loadComponentDoc(owner.docPath, docOpts);
+ const loaded = await loadComponentDoc(owner.docPath, docOpts);
+ // A family member an integration lists under its own name reads as that
+ // member, the way a Core sub-component does below.
+ const docs =
+ scoped.kind === 'integration'
+ ? scopeIntegrationMember(loaded, owner, dirName)
+ : loaded;
if (props) return componentDetailProps(docs, owner.package);
return componentDetail(docs, owner, dirName, coreDir);
}
@@ -525,7 +532,8 @@ export async function component(name, options = {}) {
// Integration components don't carry showcases — fail without scanning.
return componentDetailShowcase(dirName, {cwd, name, resolve: false, ownerPackage: owner.package});
}
- const docs = await loadComponentDoc(owner.docPath, docOpts);
+ const loaded = await loadComponentDoc(owner.docPath, docOpts);
+ const docs = scopeIntegrationMember(loaded, owner, dirName);
if (props) return componentDetailProps(docs, owner.package);
return componentDetail(docs, owner, dirName, coreDir);
}
diff --git a/packages/cli/api/component/integration-export-name.test.mjs b/packages/cli/api/component/integration-export-name.test.mjs
index 0c6b5f303e..3010d05833 100644
--- a/packages/cli/api/component/integration-export-name.test.mjs
+++ b/packages/cli/api/component/integration-export-name.test.mjs
@@ -1,21 +1,25 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Every surface knows an integration component by the name its doc
- * documents. Fixtures live under a repo-local temp dir: Vite refuses to import
- * a module from outside the project root.
+ * @file Every surface knows an integration component, or a family member, by
+ * the name its doc documents. Fixtures live under a repo-local temp dir: Vite
+ * refuses to import a module from outside the project root.
*/
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {spawnSync} from 'node:child_process';
import {component} from './component.mjs';
import {search} from '../search/search.mjs';
import {validateIntegration} from '../integration/validate-integration.mjs';
import {integrationComponentConflicts} from '../integration/authoring-checks.mjs';
import {swizzleCopy} from '../swizzle/copy/copy.mjs';
import {gapReport} from '../gap-report/gap-report.mjs';
+import {Project} from '../../foundation/config/project.mjs';
+import {collectDocInputs} from '../../foundation/doc-compiler/inputs.mjs';
import {COMPONENT_REPLACES_CLI} from '../../foundation/integrations/cli-requirement.mjs';
+import {scopeIntegrationMember} from './_adapter.mjs';
const SLOW = 30_000;
@@ -76,6 +80,7 @@ beforeEach(() => {
'./gallery/Slides': './src/gallery/Slides.tsx',
'./gallery/Overlays': './src/gallery/Overlays.tsx',
'./AcmeBadge': './src/AcmeBadge.tsx',
+ './tabs': './src/tabs/AcmeTabs.tsx',
},
}),
);
@@ -95,6 +100,43 @@ beforeEach(() => {
'export function AcmeBadge() { return null; }\n',
'A small status label.',
);
+ // A family doc whose members the module it imports exports.
+ fs.mkdirSync(path.join(pkgDir, 'src', 'tabs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'src', 'tabs', 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\nexport function AcmeTab() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'src', 'tabs', 'AcmeTabs.doc.mjs'),
+ `export default ${JSON.stringify(
+ {
+ type: 'component',
+ name: 'AcmeTabs',
+ displayName: 'Acme Tabs',
+ import: '@acme/widgets/tabs',
+ keywords: ['tabs', 'navigation'],
+ usage: {description: 'Switches between views.'},
+ components: [
+ {
+ name: 'AcmeTabs',
+ displayName: 'Acme Tabs',
+ description: 'The tab list.',
+ props: [],
+ },
+ {
+ name: 'AcmeTab',
+ displayName: 'Acme Tab',
+ description: 'One labelled tab in the list.',
+ props: [
+ {name: 'label', type: 'string', description: 'The tab label.'},
+ ],
+ },
+ ],
+ },
+ null,
+ 2,
+ )};\n`,
+ );
});
afterEach(() => {
@@ -158,7 +200,7 @@ describe('a component doc that names another export of its file', () => {
async () => {
expect(
listedNames(await component(undefined, {cwd: tmpDir, list: true})),
- ).toEqual(['AcmeBadge', 'AcmeCarousel']);
+ ).toEqual(['AcmeBadge', 'AcmeCarousel', 'AcmeTab', 'AcmeTabs']);
const detail = await component('AcmeCarousel', {cwd: tmpDir});
expect(detail.type).toBe('component.detail');
@@ -198,15 +240,18 @@ describe('a component doc that names another export of its file', () => {
SLOW,
);
- it(
- "leaves a Core name to Core unless --package names it, and passes Doctor's package checks",
- async () => {
+ it.each(['the export its doc names', 'a member its family doc lists'])(
+ "leaves a Core name to Core unless --package names it, when it is %s, and passes Doctor's package checks",
+ async kind => {
// Overlays.tsx exports Dialog, a Core name, and nothing named Overlays.
+ const members = [{name: 'Dialog', description: 'A dialog.', props: []}];
+ const member = kind === 'a member its family doc lists';
writeComponent(
'gallery/Overlays',
- 'Dialog',
+ member ? 'AcmeOverlays' : 'Dialog',
'export function AcmeOverlays() { return null; }\nexport function Dialog() { return null; }\n',
'Overlays.',
+ member ? {components: members} : {},
);
const validation = await validateIntegration(undefined, {cwd: pkgDir});
@@ -416,4 +461,184 @@ describe('a component doc that names another export of its file', () => {
},
SLOW,
);
+
+ it(
+ "opens a member named like its family doc's own name as that member",
+ async () => {
+ // Overlays.tsx exports Overlays, so the doc keeps its file name, and
+ // AcmeChip, the doc's own name, is a member.
+ const label = {name: 'label', type: 'string', description: 'The label.'};
+ writeComponent(
+ 'gallery/Overlays',
+ 'AcmeChip',
+ 'export function Overlays() { return null; }\nexport function AcmeChip() { return null; }\nexport function AcmeChipIcon() { return null; }\n',
+ 'Chips.',
+ {
+ components: [
+ {name: 'AcmeChip', description: 'One chip.', props: [label]},
+ {name: 'AcmeChipIcon', description: 'An icon.', props: []},
+ ],
+ },
+ );
+ // Every member names the family by the name it opens under.
+ expect(
+ (await component('AcmeChipIcon', {cwd: tmpDir})).data.parentDoc,
+ ).toBe('Overlays');
+ const detail = await component('AcmeChip', {cwd: tmpDir});
+ expect(detail.data).toMatchObject({
+ name: 'AcmeChip',
+ description: 'One chip.',
+ parentDoc: 'Overlays',
+ });
+ const props = await component('AcmeChip', {cwd: tmpDir, props: true});
+ expect(props.data.map(prop => prop.name)).toEqual(['label']);
+ },
+ SLOW,
+ );
+
+ it(
+ 'opens, lists and finds a family member as itself, with the import its family states',
+ async () => {
+ const list = await component(undefined, {cwd: tmpDir, list: true});
+ const entry = Object.values(list.data.components)
+ .flat()
+ .find(item => item.name === 'AcmeTab');
+ expect(entry).toEqual({
+ name: 'AcmeTab',
+ package: '@acme/widgets',
+ import: '@acme/widgets/tabs',
+ });
+
+ const detail = await component('AcmeTab', {cwd: tmpDir});
+ expect(detail.data).toMatchObject({
+ name: 'AcmeTab',
+ description: 'One labelled tab in the list.',
+ parentDoc: 'AcmeTabs',
+ package: '@acme/widgets',
+ import: '@acme/widgets/tabs',
+ sourceAvailable: true,
+ });
+ expect(detail.data.props.map(prop => prop.name)).toEqual(['label']);
+ const props = await component('AcmeTab', {cwd: tmpDir, props: true});
+ expect(props.data.map(prop => prop.name)).toEqual(['label']);
+ // The family's own doc is unchanged.
+ expect((await component('AcmeTabs', {cwd: tmpDir})).data).toMatchObject({
+ name: 'AcmeTabs',
+ import: '@acme/widgets/tabs',
+ });
+
+ const hits = (await search('AcmeTab', {cwd: tmpDir, type: 'component'}))
+ .data.results;
+ expect(hits[0]).toMatchObject({
+ name: 'AcmeTab',
+ description: 'One labelled tab in the list.',
+ import: '@acme/widgets/tabs',
+ });
+ // The member does not carry the family's keywords.
+ const tabs = (
+ await search('navigation', {cwd: tmpDir, type: 'component'})
+ ).data.results;
+ expect(tabs.map(hit => hit.name)).toContain('AcmeTabs');
+ expect(tabs.map(hit => hit.name)).not.toContain('AcmeTab');
+ },
+ SLOW,
+ );
+
+ it(
+ 'leaves a member named like a Core sub-component to Core, and swizzle unknown',
+ async () => {
+ const tabs = path.join(pkgDir, 'src', 'tabs');
+ const doc = path.join(tabs, 'AcmeTabs.doc.mjs');
+ fs.writeFileSync(
+ doc,
+ fs
+ .readFileSync(doc, 'utf-8')
+ .replace(
+ '"components": [',
+ '"components": [{"name": "DialogHeader", "description": "x"},',
+ ),
+ );
+ fs.appendFileSync(
+ path.join(tabs, 'AcmeTabs.tsx'),
+ 'export function DialogHeader() { return null; }\n',
+ );
+ const cwd = tmpDir;
+ expect(
+ listedNames(await component(undefined, {cwd, list: true})),
+ ).toContain('DialogHeader');
+ expect((await component('DialogHeader', {cwd})).data.package).toBe(
+ '@astryxdesign/core',
+ );
+ await expect(swizzleCopy('DialogHeader', {cwd})).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_COMPONENT',
+ });
+ },
+ SLOW,
+ );
+
+ it('fails a member its family doc, as this process loaded it, does not list', async () => {
+ const owner = {
+ package: '@acme/widgets',
+ docPath: path.join(pkgDir, 'src', 'tabs', 'AcmeTabs.doc.mjs'),
+ sourcePath: null,
+ };
+ // The doc this process loaded before AcmeTab was added.
+ const stale = {type: 'component', name: 'AcmeTabs', components: []};
+ expect(() =>
+ scopeIntegrationMember(/** @type {any} */ (stale), owner, 'AcmeTab', ''),
+ ).toThrow(expect.objectContaining({code: 'ERR_UNKNOWN_COMPONENT'}));
+ });
+
+ it(
+ 'indexes a .doc.ts family member as a member when Node cannot load the doc',
+ () => {
+ const fam = path.join(pkgDir, 'src', 'fam');
+ fs.mkdirSync(fam, {recursive: true});
+ const manifest = path.join(pkgDir, 'package.json');
+ const pkg = JSON.parse(fs.readFileSync(manifest, 'utf-8'));
+ pkg.exports['./fam'] = './src/fam/AcmeFamTs.tsx';
+ fs.writeFileSync(manifest, JSON.stringify(pkg));
+ fs.writeFileSync(
+ path.join(fam, 'AcmeFamTs.doc.ts'),
+ "export default {type: 'component', name: 'AcmeFamTs', import: '@acme/widgets/fam', usage: {description: 'A family.'}, components: [{name: 'AcmeFamTs', description: 'x'}, {name: 'AcmeFamItem', description: 'One item.'}]};\n",
+ );
+ fs.writeFileSync(
+ path.join(fam, 'AcmeFamTs.tsx'),
+ 'export function AcmeFamTs() { return null; }\nexport function AcmeFamItem() { return null; }\n',
+ );
+ // The real CLI under Node, which does not strip types in node_modules.
+ const run = spawnSync(
+ process.execPath,
+ [
+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),
+ 'search',
+ 'AcmeFamTs',
+ '--json',
+ ],
+ {cwd: tmpDir, encoding: 'utf-8'},
+ );
+ const hits = JSON.parse(run.stdout).data.results.filter(
+ (/** @type {any} */ hit) => hit.domain === 'component',
+ );
+ expect(hits.map((/** @type {any} */ hit) => hit.name)).toEqual([
+ 'AcmeFamTs',
+ ]);
+ },
+ SLOW,
+ );
+
+ it(
+ 'reads a family doc once when the docs compile',
+ async () => {
+ const {inputs, problems} = await collectDocInputs(
+ await Project.load(tmpDir),
+ );
+ expect(problems).toEqual([]);
+ const tabsDoc = path.join(pkgDir, 'src', 'tabs', 'AcmeTabs.doc.mjs');
+ expect(
+ inputs.filter(input => input.file === tabsDoc).map(input => input.name),
+ ).toEqual(['AcmeTabs']);
+ },
+ SLOW,
+ );
});
diff --git a/packages/cli/api/gap-report/gap-report.mjs b/packages/cli/api/gap-report/gap-report.mjs
index f5b040a992..d85b8a3793 100644
--- a/packages/cli/api/gap-report/gap-report.mjs
+++ b/packages/cli/api/gap-report/gap-report.mjs
@@ -24,6 +24,7 @@ import {
findComponentReadme,
findIntegrationComponent,
integrationRecordHold,
+ isIntegrationMember,
unscopedComponentOwners,
} from '../../foundation/discovery/component-discovery.mjs';
import {legacyExternalKeeps} from '../component/_adapter.mjs';
@@ -197,7 +198,7 @@ async function selectTarget(project, component, packageName) {
discoverIntegrationComponents(integration).flatMap(r =>
r.name.toLowerCase() === wanted
? [{...r, hold: integrationRecordHold(r)}]
- : docStem(r.docPath).toLowerCase() === wanted
+ : docStem(r.docPath).toLowerCase() === wanted && !isIntegrationMember(r)
? [{...r, hold: 'doc'}]
: [],
),
diff --git a/packages/cli/api/integration/add-contribution.component-names.test.mjs b/packages/cli/api/integration/add-contribution.component-names.test.mjs
index 45f7baa5c0..4c874d034b 100644
--- a/packages/cli/api/integration/add-contribution.component-names.test.mjs
+++ b/packages/cli/api/integration/add-contribution.component-names.test.mjs
@@ -98,6 +98,72 @@ describe('integrationAddComponent name collisions', () => {
expect(snapshot()).toEqual(before);
});
+ it('adds a name a family doc lists but the module it imports does not export', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ `${JSON.stringify({name: '@acme/widgets', version: '1.0.0', files: ['dist'], exports: {'./tabs': './components/tabs/index.ts'}}, null, 2)}\n`,
+ );
+ const tabs = path.join(tmpDir, 'components', 'tabs');
+ fs.mkdirSync(tabs, {recursive: true});
+ fs.writeFileSync(
+ path.join(tabs, 'AcmeTabs.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTabExtra', description: 'x'}]};\n",
+ );
+ fs.writeFileSync(
+ path.join(tabs, 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\nexport function AcmeTabExtra() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(tabs, 'index.ts'),
+ "export {AcmeTabs} from './AcmeTabs';\n",
+ );
+
+ const result = await integrationAdd('component', 'AcmeTabExtra', {
+ cwd: tmpDir,
+ dryRun: true,
+ });
+ expect(result.data.files).toContain('components/AcmeTabExtra.doc.mjs');
+ });
+
+ it('refuses a member a family exports through built output', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ `${JSON.stringify({name: '@acme/widgets', version: '1.0.0', files: ['dist'], exports: {'./tabs': './dist/tabs/index.js'}}, null, 2)}\n`,
+ );
+ const tabs = path.join(tmpDir, 'components', 'tabs');
+ fs.mkdirSync(tabs, {recursive: true});
+ fs.writeFileSync(
+ path.join(tabs, 'AcmeTabs.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTab', description: 'x'}]};\n",
+ );
+ fs.writeFileSync(
+ path.join(tabs, 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(tabs, 'AcmeTab.tsx'),
+ 'export function AcmeTab() { return null; }\n',
+ );
+ const dist = path.join(tmpDir, 'dist', 'tabs');
+ fs.mkdirSync(dist, {recursive: true});
+ fs.writeFileSync(
+ path.join(dist, 'index.js'),
+ "export {AcmeTabs} from './tabs.js';\nexport {AcmeTab} from './tab.js';\n",
+ );
+ fs.writeFileSync(
+ path.join(dist, 'tabs.js'),
+ 'export function AcmeTabs() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(dist, 'tab.js'),
+ 'export function AcmeTab() { return null; }\n',
+ );
+
+ await expect(
+ integrationAdd('component', 'AcmeTab', {cwd: tmpDir, dryRun: true}),
+ ).rejects.toThrow('Refusing to add component "AcmeTab"');
+ });
+
it('still adds a component whose name is free', async () => {
writeAuthoredComponent('components/AcmeWidget/AcmeWidget.doc.mjs');
diff --git a/packages/cli/api/integration/add-contribution.mjs b/packages/cli/api/integration/add-contribution.mjs
index 05310b3b4b..e5c061b2f9 100644
--- a/packages/cli/api/integration/add-contribution.mjs
+++ b/packages/cli/api/integration/add-contribution.mjs
@@ -264,9 +264,13 @@ async function addComponent(name, options) {
ERROR_CODES.ERR_FILE_EXISTS,
);
}
- // Discovery keys components by doc stem anywhere under the root, so a second
- // doc with this name would shadow one of the two.
- const existingDoc = findIntegrationComponentDoc({components: root}, name);
+ // A second doc under a name discovery already records, by a doc's file name
+ // anywhere under the root or by a name a doc documents, would shadow one of
+ // the two.
+ const existingDoc = findIntegrationComponentDoc(
+ {name: owner, components: root, __packageDir: packageDir},
+ name,
+ );
if (existingDoc != null) {
throw new AstryxError(
`Refusing to add component "${name}": ${projectPath(path.relative(packageDir, existingDoc))} already defines it.`,
diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjs
index b08e549359..842e4cc5e3 100644
--- a/packages/cli/api/integration/pack-check.mjs
+++ b/packages/cli/api/integration/pack-check.mjs
@@ -52,6 +52,8 @@ import {
import {
discoverIntegrationComponents,
docStem,
+ familyImports,
+ isIntegrationMember,
resolveIntegrationImportPath,
} from '../../foundation/discovery/component-discovery.mjs';
import {loadComponentReplacements} from '../component/_adapter.mjs';
@@ -381,11 +383,16 @@ async function validatePackedComponentExports(integration, scratchBase) {
const issues = [];
/** @type {Array<{name: string, specifier: string}>} */
const components = [];
+ // A family doc backs several records: load it, and report it, once.
+ const loads = new Map();
for (const record of records) {
+ const first = !loads.has(record.docPath);
+ if (first) loads.set(record.docPath, loadComponentDoc(record.docPath));
let docs;
try {
- docs = await loadComponentDoc(record.docPath);
+ docs = await loads.get(record.docPath);
} catch (err) {
+ if (!first) continue;
issues.push(
error(
'component_doc_unloadable',
@@ -994,6 +1001,24 @@ export async function integrationPackCheck(options = {}) {
const fileInv = computeRequiredFiles(loaded);
const {identities: localIdentities, errors: localDiscoveryErrors} =
await collectIdentities(loaded);
+ // A family lists its members from the module its import names, which the
+ // pack lifecycle may build or rebuild, so they are compared as local
+ // discovery lists them after the pack.
+ const familiesBefore = familyImports(loaded).map(family => family.docPath);
+ /**
+ * @param {Array<{name: string, docPath: string|null}>} records
+ * @param {Set<string>} families
+ */
+ const membersOf = (records, families) =>
+ records
+ .filter(
+ r =>
+ r.docPath != null &&
+ families.has(r.docPath) &&
+ isIntegrationMember(r),
+ )
+ .map(r => r.name);
+ const recordsBefore = discoverIntegrationComponents(loaded);
for (const discoveryError of localDiscoveryErrors) {
issues.push(
error(
@@ -1254,7 +1279,27 @@ export async function integrationPackCheck(options = {}) {
);
}
- issues.push(...compareIdentities(localIdentities, packedIdentities));
+ const families = new Set([
+ ...familiesBefore,
+ ...familyImports(loaded).map(family => family.docPath),
+ ]);
+ let localComponents = localIdentities.components;
+ if (families.size > 0) {
+ const stale = new Set(membersOf(recordsBefore, families));
+ const built = new Set(
+ membersOf(discoverIntegrationComponents(loaded), families),
+ );
+ const {identities: afterPack} = await collectIdentities(loaded);
+ localComponents = [
+ ...new Set([
+ ...localComponents.filter(name => !stale.has(name)),
+ ...afterPack.components.filter(name => built.has(name)),
+ ]),
+ ].sort();
+ }
+ // The receipt reports the local inventory that was compared.
+ const comparedLocal = {...localIdentities, components: localComponents};
+ issues.push(...compareIdentities(comparedLocal, packedIdentities));
issues.push(
...(await validatePackedThemeExports(
loaded,
@@ -1276,7 +1321,7 @@ export async function integrationPackCheck(options = {}) {
pkgVersion,
fileInv,
packResult,
- localIdentities,
+ comparedLocal,
packedIdentities,
issues,
);
diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjs
index 49e3a893f1..1169c9ed91 100644
--- a/packages/cli/api/integration/pack-check.test.mjs
+++ b/packages/cli/api/integration/pack-check.test.mjs
@@ -786,6 +786,253 @@ describe('integrationPackCheck', () => {
]);
});
+ it('checks each family member against the module its family doc imports', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ `${JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ files: ['astryx.integration.mjs', 'components'],
+ exports: {'./tabs': './components/tabs/index.ts'},
+ })}\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ "export default {components: './components'};\n",
+ );
+ const dir = path.join(tmpDir, 'components', 'tabs');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\nexport function AcmeTabsLegacy() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(dir, 'tab.tsx'),
+ 'export function AcmeTab() { return null; }\n',
+ );
+ // The module apps import exports AcmeTabs and AcmeTab, not AcmeTabsLegacy.
+ fs.writeFileSync(
+ path.join(dir, 'index.ts'),
+ "export {AcmeTabs} from './AcmeTabs';\nexport {AcmeTab} from './tab';\n",
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTabs.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTabs', description: 'x', props: []}, {name: 'AcmeTab', description: 'x', props: []}, {name: 'AcmeTabsLegacy', description: 'x', props: []}]};\n",
+ );
+
+ const result = await integrationPackCheck({cwd: tmpDir});
+
+ expect(result.data.issues).toEqual([]);
+ expect(result.data.packable).toBe(true);
+ expect(result.data.contributions.packed.components).toEqual([
+ 'AcmeTab',
+ 'AcmeTabs',
+ ]);
+ });
+
+ it.each([
+ 'a clean checkout',
+ 'a stale build',
+ 'a stale build that exports more',
+ ])(
+ 'reads members a family imports from output its pack lifecycle builds, from %s',
+ async start => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ `${JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ files: ['astryx.integration.mjs', 'components', 'dist'],
+ exports: {'./tabs': './dist/tabs/index.mjs'},
+ scripts: {prepack: 'node build.mjs'},
+ })}\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ "export default {components: './components'};\n",
+ );
+ // The build writes the module the family imports; a clean checkout has none.
+ fs.writeFileSync(
+ path.join(tmpDir, 'build.mjs'),
+ "import fs from 'node:fs';\nfs.mkdirSync('dist/tabs', {recursive: true});\nfs.writeFileSync('dist/tabs/index.mjs', \"export {AcmeTabs, AcmeTab} from '../../components/tabs/AcmeTabs.tsx';\\n\");\n",
+ );
+ const dir = path.join(tmpDir, 'components', 'tabs');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\nexport function AcmeTab() { return null; }\nexport function AcmeTabLegacy() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTabs.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTabs', description: 'x', props: []}, {name: 'AcmeTab', description: 'x', props: []}, {name: 'AcmeTabLegacy', description: 'x', props: []}]};\n",
+ );
+
+ if (start !== 'a clean checkout') {
+ // An earlier build: before AcmeTab was exported, or while AcmeTabLegacy
+ // still was.
+ const names =
+ start === 'a stale build'
+ ? 'AcmeTabs'
+ : 'AcmeTabs, AcmeTab, AcmeTabLegacy';
+ fs.mkdirSync(path.join(tmpDir, 'dist', 'tabs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'dist', 'tabs', 'index.mjs'),
+ `export {${names}} from '../../components/tabs/AcmeTabs.tsx';\n`,
+ );
+ }
+
+ const result = await integrationPackCheck({cwd: tmpDir});
+
+ expect(result.data.issues).toEqual([]);
+ expect(result.data.packable).toBe(true);
+ expect(result.data.contributions.local.components).toEqual(
+ result.data.contributions.packed.components,
+ );
+ },
+ );
+
+ it.each(['a clean checkout', 'an incremental build'])(
+ 'reads members built output re-exports from compiled files, from %s',
+ async start => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ `${JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ files: ['astryx.integration.mjs', 'components', 'dist'],
+ exports: {'./tabs': './dist/tabs/index.mjs'},
+ scripts: {prepack: 'node build.mjs'},
+ })}\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ "export default {components: './components'};\n",
+ );
+ // The build compiles each source to its own file and, like an
+ // incremental build, rewrites only the files whose output changed.
+ const output = {
+ 'index.mjs':
+ "export {AcmeTabs} from './tabs.mjs';\nexport * from './tab.mjs';\n",
+ 'tabs.mjs': 'export function AcmeTabs() { return null; }\n',
+ 'tab.mjs': 'export function AcmeTab() { return null; }\n',
+ };
+ fs.writeFileSync(
+ path.join(tmpDir, 'build.mjs'),
+ `import fs from 'node:fs';\nconst output = ${JSON.stringify(output)};\nfs.mkdirSync('dist/tabs', {recursive: true});\nfor (const [file, text] of Object.entries(output)) {\n const target = 'dist/tabs/' + file;\n if (!fs.existsSync(target) || fs.readFileSync(target, 'utf-8') !== text) fs.writeFileSync(target, text);\n}\n`,
+ );
+ const dir = path.join(tmpDir, 'components', 'tabs');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTab.tsx'),
+ 'export function AcmeTab() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(dir, 'AcmeTabs.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeTabs', import: '@acme/widgets/tabs', description: 'x', components: [{name: 'AcmeTabs', description: 'x', props: []}, {name: 'AcmeTab', description: 'x', props: []}]};\n",
+ );
+ if (start === 'an incremental build') {
+ // An earlier build from before AcmeTab existed: the file the import
+ // names is already current, so the build leaves it untouched.
+ fs.mkdirSync(path.join(tmpDir, 'dist', 'tabs'), {recursive: true});
+ for (const [file, text] of Object.entries({...output, 'tab.mjs': ''})) {
+ fs.writeFileSync(path.join(tmpDir, 'dist', 'tabs', file), text);
+ }
+ }
+
+ const result = await integrationPackCheck({cwd: tmpDir});
+
+ expect(result.data.issues).toEqual([]);
+ expect(result.data.packable).toBe(true);
+ expect(result.data.contributions.packed.components).toEqual([
+ 'AcmeTab',
+ 'AcmeTabs',
+ ]);
+ expect(result.data.contributions.local.components).toEqual(
+ result.data.contributions.packed.components,
+ );
+ },
+ );
+
+ it('passes a member another folder declares, which has no source', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ `${JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ files: ['astryx.integration.mjs', 'components'],
+ exports: {'./menu': './components/menu/index.ts'},
+ })}\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ "export default {components: './components'};\n",
+ );
+ const menu = path.join(tmpDir, 'components', 'menu');
+ const shared = path.join(tmpDir, 'components', 'shared');
+ fs.mkdirSync(menu, {recursive: true});
+ fs.mkdirSync(shared, {recursive: true});
+ fs.writeFileSync(
+ path.join(menu, 'AcmeMenu.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeMenu', import: '@acme/widgets/menu', description: 'x', components: [{name: 'AcmeMenuItem', description: 'x', props: []}]};\n",
+ );
+ fs.writeFileSync(
+ path.join(menu, 'AcmeMenu.tsx'),
+ 'export function AcmeMenu() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(menu, 'index.ts'),
+ "export {AcmeMenu} from './AcmeMenu';\nexport {AcmeMenuItem} from '../shared/AcmeMenuItem';\n",
+ );
+ fs.writeFileSync(
+ path.join(shared, 'AcmeMenuItem.tsx'),
+ 'export function AcmeMenuItem() { return null; }\n',
+ );
+
+ const result = await integrationPackCheck({cwd: tmpDir});
+
+ expect(result.data.issues).toEqual([]);
+ expect(result.data.packable).toBe(true);
+ expect(result.data.contributions.packed.components).toEqual([
+ 'AcmeMenu',
+ 'AcmeMenuItem',
+ ]);
+ });
+
+ it('reports a family doc the loader rejects once, not once per member', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ `${JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.0.0',
+ files: ['astryx.integration.mjs', 'components'],
+ })}\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ "export default {components: './components'};\n",
+ );
+ fs.mkdirSync(path.join(tmpDir, 'components'));
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\nexport function AcmeTab() { return null; }\nexport function AcmeTabPanel() { return null; }\n',
+ );
+ // A displayName that is not a string makes the loader reject the doc.
+ fs.writeFileSync(
+ path.join(tmpDir, 'components', 'AcmeTabs.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeTabs', displayName: 1, description: 'x', components: [{name: 'AcmeTab', description: 'x', props: []}, {name: 'AcmeTabPanel', description: 'x', props: []}]};\n",
+ );
+
+ const result = await integrationPackCheck({cwd: tmpDir});
+ const codes = result.data.issues.map(issue => issue.code);
+
+ expect(codes).toContain('component_doc_unloadable');
+ expect(codes.length).toBe(new Set(codes).size);
+ });
+
it('passes a generated component through its exact packed export', async () => {
fs.writeFileSync(
path.join(tmpDir, 'package.json'),
diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjs
index 861a9f8750..0056685610 100644
--- a/packages/cli/api/search/search.mjs
+++ b/packages/cli/api/search/search.mjs
@@ -92,7 +92,9 @@ import {
familyMember,
findComponentReadme,
forEachIntegrationDoc,
+ integrationMemberEntry,
integrationRecordHold,
+ isIntegrationMember,
resolveImportPath,
resolveIntegrationImportPath,
CORE_PACKAGE,
@@ -1144,24 +1146,31 @@ async function gatherIntegrationComponents(loadedIntegrations) {
const renamed = new Set(
discovered
.filter(rec => integrationRecordHold(rec) === 'doc')
+ .filter(rec => !isIntegrationMember(rec))
.map(rec => rec.docPath),
);
forEachIntegrationDoc(integration.components, (docPath, stem) => {
if (!renamed.has(docPath)) hold(fileNamed, stem, docPath);
});
for (const rec of components) {
- const doc = await loadModuleDoc(rec.docPath);
+ const loaded = await loadModuleDoc(rec.docPath);
+ // A family member is indexed from its own entry: the family's keywords
+ // and guidance describe the family.
+ const member = isIntegrationMember(rec);
+ const doc = member ? integrationMemberEntry(loaded, rec) : loaded;
// A doc that names another export of its file still answers to the
// file's name, as `component <file name>` does.
const fileName = docStem(rec.docPath);
- if (renamed.has(rec.docPath)) {
+ if (integrationRecordHold(rec) === 'doc') {
hold(documented, rec.name, rec.docPath);
+ }
+ if (renamed.has(rec.docPath) && !member) {
hold(documented, fileName, rec.docPath);
}
candidates.push({
domain: 'component',
name: rec.name,
- aliases: fileName !== rec.name ? [fileName] : [],
+ aliases: !member && fileName !== rec.name ? [fileName] : [],
_hold: integrationRecordHold(rec),
_docPath: rec.docPath,
keywords: doc && Array.isArray(doc.keywords) ? doc.keywords : [],
@@ -1183,7 +1192,7 @@ async function gatherIntegrationComponents(loadedIntegrations) {
packageName: rec.package,
},
rec.name,
- doc?.import,
+ loaded?.import,
),
});
}
@@ -1319,10 +1328,13 @@ export async function componentKeywords(coreDir, cwd) {
const integrations = loadedIntegrations.map(async integration => {
const {components} = await discoverValidIntegrationComponents(integration);
return Promise.all(
- components.map(async rec => ({
- name: rec.name,
- keywords: keywordsOf(await loadModuleDoc(rec.docPath)),
- })),
+ components.map(async rec => {
+ const loaded = await loadModuleDoc(rec.docPath);
+ return {
+ name: rec.name,
+ keywords: keywordsOf(integrationMemberEntry(loaded, rec) ?? loaded),
+ };
+ }),
);
});
return [
diff --git a/packages/cli/assets/docs/tree/add-a-component.doc.mjs b/packages/cli/assets/docs/tree/add-a-component.doc.mjs
index e2ed1f648b..6aa374cb8a 100644
--- a/packages/cli/assets/docs/tree/add-a-component.doc.mjs
+++ b/packages/cli/assets/docs/tree/add-a-component.doc.mjs
@@ -71,5 +71,15 @@ Declare component root ./components in astryx.integration.mjs.
},
],
},
+ {
+ id: 'document-an-existing-component',
+ title: 'Document a component you already have',
+ content: [
+ {
+ type: 'prose',
+ text: "To document a component your package already has, write its doc beside the source file and name the doc after that file, such as `acme-gallery.doc.mjs` beside `acme-gallery.tsx`. Set `name` to the export apps import, such as `name: 'AcmeGallery'`, and keep both files inside the components root that `astryx.integration.mjs` declares. The file does not have to be named after the component; {@link generic:component-imports} shows how apps then find it.",
+ },
+ ],
+ },
],
};
diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjs
index d974fdab49..91bb2905d0 100644
--- a/packages/cli/assets/docs/tree/checks.doc.mjs
+++ b/packages/cli/assets/docs/tree/checks.doc.mjs
@@ -105,7 +105,7 @@ export const docs = {
'It runs `npm pack` the way `npm publish` would, including your `prepack` script.',
'It checks that every contribution file is in the `.tgz` file. A root missing from `files` fails with `Add "templates" to "files" in package.json.`',
'It lists the components, templates, themes, docs, and codemods the temporary app sees, and compares them with your source.',
- "It resolves each component's `import`, and each template's public import, the way Node does, and checks that the module exports the component, or a default export for a template.",
+ "It resolves each component's `import`, and each template's public import, the way Node does, and checks that the module exports the component under the name its doc documents, or a default export for a template. A type-only export does not count.",
'For each theme, it rebuilds the source, compares the built module and production CSS with the authored outputs, and proves the module, CSS, and optional font CSS exports resolve from the packed package.',
'It fails a package that needs an `@astryxdesign/cli` peer and lacks it: `>=0.6.6` for a template that sets `keywords`, and `>=0.6.4` for a template that sets `replaces`, a docs section, a placed guide, a doc section with an `id`, or a theme.',
],
diff --git a/packages/cli/assets/docs/tree/component-family.doc.mjs b/packages/cli/assets/docs/tree/component-family.doc.mjs
index 740cfe2723..dee4f1fb97 100644
--- a/packages/cli/assets/docs/tree/component-family.doc.mjs
+++ b/packages/cli/assets/docs/tree/component-family.doc.mjs
@@ -95,7 +95,11 @@ export default {
},
{
type: 'prose',
- text: 'The public module named by `import` must export every component or hook named by a full entry.',
+ text: "The public module named by `import` must export every component or hook named by a full entry. Apps then list, search and open each component in the family by its own name. A full entry the module does not export is not listed, and `integration verify` does not report it: check the family with `astryx component --list`. When `import` names output your pack lifecycle builds (such as `dist`), the members are listed once that output exists, and `integration verify` compares them as they are listed after the pack builds it.",
+ },
+ {
+ type: 'prose',
+ text: "A member's source is the `.tsx` file in the family doc's folder, or below it, that declares it: the one the family's own file or the module `import` names reaches, else the one in that folder that declares the name, as when `import` names built output. A member that only a bundle or a file outside that folder declares is still listed, with no source for `--source` or `swizzle`. A member is not listed when a doc's file or a Core name your package replaces already has its name. A member that shares a name with Core opens with `--package`.",
},
],
},
diff --git a/packages/cli/assets/docs/tree/component-imports.doc.mjs b/packages/cli/assets/docs/tree/component-imports.doc.mjs
index 023a1ec87b..2afd5dad40 100644
--- a/packages/cli/assets/docs/tree/component-imports.doc.mjs
+++ b/packages/cli/assets/docs/tree/component-imports.doc.mjs
@@ -37,7 +37,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'A file does not have to be named after its component. When `Slides.tsx` exports `AcmeCarousel` and nothing named `Slides`, keep the doc beside it as `Slides.doc.mjs` and set its `name` to `AcmeCarousel`: apps list, search and open the component by that name, and `integration verify` checks that its import exports `AcmeCarousel`. A file that exports its own name keeps that name.',
+ text: 'A file does not have to be named after its component. When `Slides.tsx` exports `AcmeCarousel` and nothing named `Slides`, keep the doc beside it as `Slides.doc.mjs` and set its `name` to `AcmeCarousel`: apps list, search and open the component by that name, and `integration verify` checks that its import exports `AcmeCarousel`. A file that exports its own name keeps that name. A package that names its files in kebab case works the same way: `acme-gallery.doc.mjs` beside `acme-gallery.tsx` sets `name: \'AcmeGallery\'`.',
},
{
type: 'prose',
diff --git a/packages/cli/assets/docs/tree/single-component.doc.mjs b/packages/cli/assets/docs/tree/single-component.doc.mjs
index 6f33e57a0b..27acdcef38 100644
--- a/packages/cli/assets/docs/tree/single-component.doc.mjs
+++ b/packages/cli/assets/docs/tree/single-component.doc.mjs
@@ -56,7 +56,7 @@ export default {
style: 'unordered',
items: [
'Keep `props` on the top-level doc. Private implementation helpers do not need entries.',
- 'Keep the doc beside the source and change both in the same pull request.',
+ 'Name the doc after the source file beside it, such as `AcmeCarousel.doc.mjs` beside `AcmeCarousel.tsx`, and change both in the same pull request.',
'If the module later exposes several related public exports, adapt this doc with {@link generic:component-family}.',
],
},
diff --git a/packages/cli/assets/docs/tree/troubleshooting.doc.mjs b/packages/cli/assets/docs/tree/troubleshooting.doc.mjs
index 354670a2cf..8698cbfdab 100644
--- a/packages/cli/assets/docs/tree/troubleshooting.doc.mjs
+++ b/packages/cli/assets/docs/tree/troubleshooting.doc.mjs
@@ -67,7 +67,7 @@ export const docs = {
rows: [
[
'`component_export_missing`: `Component "AcmeCarousel" advertises import "@acme/astryx-widgets/components/AcmeCarousel", but that packed module does not export "AcmeCarousel".`',
- "package.json has no `exports` map, or the module does not export the name. Keep `export function AcmeCarousel`, and add the entry: `npm pkg set 'exports[./components/AcmeCarousel]=./components/AcmeCarousel.tsx'`.",
+ "package.json has no `exports` map, or the module does not export the name. Keep `export function AcmeCarousel`, and add the entry: `npm pkg set 'exports[./components/AcmeCarousel]=./components/AcmeCarousel.tsx'`. When the quoted name is a file name, such as `acme-carousel`, set the doc's `name` to the component the file exports. A type-only export does not count.",
],
[
'`template_export_missing`: `Template "acme-dashboard" public import "@acme/astryx-widgets/templates/acme-dashboard" does not have a default export.`',
@@ -125,6 +125,14 @@ export const docs = {
type: 'table',
headers: ['Symptom', 'Fix'],
rows: [
+ [
+ '`Error: No component named "AcmeCarousel"` for a component your package documents.',
+ "Its doc still names its file. Set `name` to the export, such as `name: 'AcmeCarousel'` in `acme-carousel.doc.mjs`. A family member is listed only when the module its family doc imports exports it ({@link generic:component-family}).",
+ ],
+ [
+ '`npx astryx component Dialog` opens Core\'s `Dialog`, not yours.',
+ "A name that Core, a legacy docs package, or another package's file already has stays theirs. Run `npx astryx component Dialog --package @acme/astryx-widgets`, or give your component a name of its own.",
+ ],
[
'`Error: Template "dashboard" is ambiguous — narrow it with --type and/or --package.`',
"Your template id matches a Core id. Rename it, such as `acme-dashboard`, or set `replaces: 'dashboard'` to take its place. `npx astryx doctor integration templates` warns about this before you publish.",
diff --git a/packages/cli/assets/docs/tree/versioning.doc.mjs b/packages/cli/assets/docs/tree/versioning.doc.mjs
index 3513a9c341..56ea9e00c6 100644
--- a/packages/cli/assets/docs/tree/versioning.doc.mjs
+++ b/packages/cli/assets/docs/tree/versioning.doc.mjs
@@ -140,6 +140,7 @@ export const docs = {
'Published 0.6.3 and earlier reject a template that sets `replaces` or `keywords`, drop that template, and hide every doc topic your package ships. Published 0.6.4 and 0.6.5 still drop a template that sets `keywords`.',
'A stable CLI before 0.6.4 cannot read a docs section, a section `id`, or a theme folder that `integration add theme` writes. It can then hide every doc topic your package ships.',
'Stable 0.6.3 still loads your components, but 0.6.0 cannot read the component docs that `integration add component` writes: `component AcmeCarousel` fails there.',
+ 'An app on an older CLI lists a component whose doc names another export of its file under the file name, and lists no family members, so `component AcmeCarousel` fails there.',
],
},
{
diff --git a/packages/cli/authoring/doctypes/component/component.doc.mjs b/packages/cli/authoring/doctypes/component/component.doc.mjs
index 5cd3059cba..b8ff1d1832 100644
--- a/packages/cli/authoring/doctypes/component/component.doc.mjs
+++ b/packages/cli/authoring/doctypes/component/component.doc.mjs
@@ -187,7 +187,7 @@ export const doc = {
name: 'components',
type: '(ComponentEntry | ComponentRef)[]',
description:
- 'MultiComponentDoc variant (required there): one entry per public component/hook exported from the directory. Each entry is a full ComponentEntry (inline: name, displayName, description, props | params+returns) or a name-only ComponentRef pointing at a sibling {Name}.doc.mjs.',
+ 'MultiComponentDoc variant (required there): one entry per public component/hook exported from the directory. Each entry is a full ComponentEntry (inline: name, displayName, description, props | params+returns) or a name-only ComponentRef pointing at a sibling {Name}.doc.mjs. In an integration, each full entry the module named by `import` exports is a component under its own name.',
},
{
name: 'subComponentOf',
diff --git a/packages/cli/foundation/discovery/component-discovery.export-names.test.mjs b/packages/cli/foundation/discovery/component-discovery.export-names.test.mjs
index 479a5816c7..cc424b31d0 100644
--- a/packages/cli/foundation/discovery/component-discovery.export-names.test.mjs
+++ b/packages/cli/foundation/discovery/component-discovery.export-names.test.mjs
@@ -1,8 +1,8 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Integration components are found by the names their docs document;
- * every doc that works today reads exactly as before.
+ * @file Integration components, and the members a family doc lists, are found
+ * by the names their docs document; every doc that works today reads as before.
*/
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
@@ -291,3 +291,470 @@ describe('integration components whose doc names another export of its file', ()
expect(names()).toEqual([]);
});
});
+
+/**
+ * Write a family doc and its source.
+ * @param {string} file path under the root, without extension
+ * @param {{name: string, members: string, source: string, extra?: string}} options
+ * `members` is the `components` array, written as JavaScript
+ */
+function writeFamily(file, {name, members, source, extra = ''}) {
+ const target = path.join(root, file);
+ fs.mkdirSync(path.dirname(target), {recursive: true});
+ fs.writeFileSync(
+ `${target}.doc.mjs`,
+ `export default {\n type: 'component',\n name: '${name}',\n usage: {description: 'A family.'},${extra}\n components: ${members},\n};\n`,
+ );
+ fs.writeFileSync(`${target}.tsx`, source);
+}
+
+describe('integration components a family doc lists in components', () => {
+ it('records each exported full entry under its own name, with the file that declares it', async () => {
+ writeFamily('carousel/AcmeCarousel', {
+ name: 'AcmeCarousel',
+ members:
+ "[{name: 'AcmeCarousel', description: 'The carousel.'}, {name: 'AcmeSlide', description: 'One slide.'}, {name: 'AcmeDots', description: 'The dots.'}]",
+ source:
+ "export function AcmeCarousel() { return null; }\nexport function AcmeSlide() { return null; }\nexport {AcmeDots} from './dots';\n",
+ });
+ fs.writeFileSync(
+ path.join(root, 'carousel', 'dots.tsx'),
+ 'export const AcmeDots = () => null;\n',
+ );
+
+ const records = discoverIntegrationComponents(integration());
+ const docPath = path.join(root, 'carousel', 'AcmeCarousel.doc.mjs');
+ expect(records.map(record => record.name)).toEqual([
+ 'AcmeCarousel',
+ 'AcmeSlide',
+ 'AcmeDots',
+ ]);
+ expect(records.find(record => record.name === 'AcmeSlide')).toMatchObject({
+ docPath,
+ sourcePath: path.join(root, 'carousel', 'AcmeCarousel.tsx'),
+ });
+ expect(findIntegrationComponentDoc(integration(), 'AcmeDots')).toBe(
+ docPath,
+ );
+ expect(findIntegrationComponentSource(integration(), 'AcmeDots')).toBe(
+ path.join(root, 'carousel', 'dots.tsx'),
+ );
+ const {components, errors} =
+ await discoverValidIntegrationComponents(integration());
+ expect(errors).toEqual([]);
+ expect(components.map(record => record.name)).toEqual([
+ 'AcmeCarousel',
+ 'AcmeSlide',
+ 'AcmeDots',
+ ]);
+ });
+
+ it('reads members from the module the doc imports, through the package exports', () => {
+ // The components root inside a package whose exports publish the module.
+ const componentsRoot = path.join(root, 'src');
+ fs.mkdirSync(path.join(componentsRoot, 'carousel'), {recursive: true});
+ fs.writeFileSync(
+ path.join(root, 'package.json'),
+ JSON.stringify({
+ name: '@acme/widgets',
+ exports: {'./carousel': './src/carousel/index.ts'},
+ }),
+ );
+ fs.writeFileSync(
+ path.join(componentsRoot, 'carousel', 'AcmeCarousel.doc.mjs'),
+ "export default {type: 'component', name: 'AcmeCarousel', import: '@acme/widgets/carousel', usage: {description: 'x'}, components: [{name: 'AcmeCarousel', description: 'x'}, {name: 'AcmeSlide', description: 'x'}]};\n",
+ );
+ fs.writeFileSync(
+ path.join(componentsRoot, 'carousel', 'AcmeCarousel.tsx'),
+ 'export function AcmeCarousel() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(componentsRoot, 'carousel', 'index.ts'),
+ "export * from './AcmeCarousel';\nexport {AcmeSlide} from './slide';\n",
+ );
+ fs.writeFileSync(
+ path.join(componentsRoot, 'carousel', 'slide.tsx'),
+ 'export function AcmeSlide() { return null; }\n',
+ );
+
+ const loaded = {
+ name: '@acme/widgets',
+ components: componentsRoot,
+ __packageDir: root,
+ };
+ expect(
+ discoverIntegrationComponents(loaded).find(
+ record => record.name === 'AcmeSlide',
+ ),
+ ).toMatchObject({
+ sourcePath: path.join(componentsRoot, 'carousel', 'slide.tsx'),
+ });
+ // Without the package, only the doc's own source is read, and it lacks
+ // the member.
+ expect(
+ discoverIntegrationComponents({...loaded, __packageDir: undefined}).map(
+ record => record.name,
+ ),
+ ).toEqual(['AcmeCarousel']);
+ });
+
+ it('leaves every other entry as before', () => {
+ writeFamily('Gallery', {
+ name: 'AcmeGallery',
+ extra: "\n hiddenComponents: ['AcmeHidden'],",
+ members: [
+ '[',
+ " {name: 'AcmeGallery', description: 'x'},",
+ // Not exported by the source.
+ " {name: 'AcmeMissing', description: 'x'},",
+ // Hidden by the doc.
+ " {name: 'AcmeHidden', description: 'x'},",
+ // A hook.
+ " {name: 'useGallery', description: 'x'},",
+ // A name-only entry points at the member's own doc.
+ " {name: 'AcmeThumb'},",
+ // Another file already has the name.
+ " {name: 'AcmeBadge', description: 'x'},",
+ // A computed name.
+ " {name: `${'Acme'}Tile`, description: 'x'},",
+ ']',
+ ].join('\n'),
+ source: [
+ 'export function AcmeGallery() { return null; }',
+ 'export function AcmeHidden() { return null; }',
+ 'export function useGallery() { return []; }',
+ 'export function AcmeThumb() { return null; }',
+ 'export function AcmeBadge() { return null; }',
+ 'export function AcmeTile() { return null; }',
+ '',
+ ].join('\n'),
+ });
+ writeComponent('AcmeBadge', {
+ name: "'AcmeBadge'",
+ source: 'export function AcmeBadge() { return null; }\n',
+ });
+
+ // Gallery.tsx exports no `Gallery`, so the doc's own name is its export.
+ expect(names()).toEqual(['AcmeBadge', 'AcmeGallery']);
+ for (const name of [
+ 'AcmeMissing',
+ 'AcmeHidden',
+ 'useGallery',
+ 'AcmeThumb',
+ 'AcmeTile',
+ ]) {
+ expect(findIntegrationComponentDoc(integration(), name)).toBeNull();
+ }
+ });
+
+ it("does not hand a family's replaces to its members", async () => {
+ writeFamily('AcmeCarousel', {
+ name: 'AcmeCarousel',
+ extra: "\n replaces: 'Carousel',",
+ members:
+ "[{name: 'AcmeCarousel', description: 'x'}, {name: 'AcmeSlide', description: 'x'}]",
+ source:
+ 'export function AcmeCarousel() { return null; }\nexport function AcmeSlide() { return null; }\n',
+ });
+ const {components} =
+ await discoverValidIntegrationComponents(integration());
+ expect(components.map(record => [record.name, record.replaces])).toEqual([
+ ['AcmeCarousel', 'Carousel'],
+ ['AcmeSlide', undefined],
+ ]);
+ });
+
+ it('drops a member once the file its source re-exports stops exporting it', () => {
+ writeFamily('AcmeTabs', {
+ name: 'AcmeTabs',
+ members: "[{name: 'AcmeTab', description: 'x'}]",
+ source:
+ "export function AcmeTabs() { return null; }\nexport * from './tab';\n",
+ });
+ const tab = path.join(root, 'tab.tsx');
+ fs.writeFileSync(tab, 'export function AcmeTab() { return null; }\n');
+ expect(names()).toEqual(['AcmeTab', 'AcmeTabs']);
+ fs.writeFileSync(tab, 'export function AcmeTabLegacy() { return null; }\n');
+ expect(names()).toEqual(['AcmeTabs']);
+ });
+
+ it('reads members a doc lists through a shorthand property', () => {
+ fs.writeFileSync(
+ path.join(root, 'AcmeTabs.tsx'),
+ 'export function AcmeTabs() { return null; }\nexport function AcmeTab() { return null; }\n',
+ );
+ fs.writeFileSync(
+ path.join(root, 'AcmeTabs.doc.mjs'),
+ "const components = [{name: 'AcmeTab', description: 'x'}];\nexport default {type: 'component', name: 'AcmeTabs', usage: {description: 'x'}, components};\n",
+ );
+ expect(names()).toEqual(['AcmeTab', 'AcmeTabs']);
+ });
+
+ it('reports a family doc the loader rejects once, not once per member', async () => {
+ writeFamily('AcmeStrip', {
+ name: 'AcmeStrip',
+ extra: '\n displayName: 7,',
+ members:
+ "[{name: 'AcmeStrip', description: 'x'}, {name: 'AcmeStripItem', description: 'x'}]",
+ source:
+ 'export function AcmeStrip() { return null; }\nexport function AcmeStripItem() { return null; }\n',
+ });
+ const {components, errors} =
+ await discoverValidIntegrationComponents(integration());
+ expect(components).toEqual([]);
+ expect(errors.map(error => error.name)).toEqual(['AcmeStrip']);
+ });
+
+ /**
+ * A package around the components root `src/`, with these files.
+ * @param {Record<string, unknown>} manifest package.json fields
+ * @param {Record<string, string>} files paths under the package
+ */
+ function writePackage(manifest, files) {
+ fs.writeFileSync(
+ path.join(root, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', ...manifest}),
+ );
+ for (const [file, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});
+ fs.writeFileSync(path.join(root, file), text);
+ }
+ return {
+ name: '@acme/widgets',
+ components: path.join(root, 'src'),
+ __packageDir: root,
+ };
+ }
+
+ /** @param {object} loaded */
+ const namesIn = loaded =>
+ discoverIntegrationComponents(/** @type {any} */ (loaded))
+ .map(record => record.name)
+ .sort();
+
+ const family = (/** @type {string} */ name, /** @type {string} */ entries) =>
+ `export default {type: 'component', name: '${name}', usage: {description: 'x'}, components: [${entries}]};\n`;
+
+ it('reads members from the main file of a package without exports, and none it cannot resolve', () => {
+ const loaded = writePackage(
+ {main: './src/index.ts'},
+ {
+ 'src/list/AcmeList.doc.mjs': family(
+ 'AcmeList',
+ "{name: 'AcmeListRow', description: 'x'}, {name: 'AcmeListCell', description: 'x'}",
+ ).replace('usage:', "import: '@acme/widgets', usage:"),
+ 'src/list/AcmeList.tsx':
+ 'export function AcmeList() { return null; }\nexport function AcmeListRow() { return null; }\n',
+ 'src/list/cell.tsx':
+ 'export function AcmeListCell() { return null; }\n',
+ 'src/index.ts':
+ "export {AcmeList} from './list/AcmeList';\nexport {AcmeListCell} from './list/cell';\n",
+ },
+ );
+ expect(namesIn(loaded)).toEqual(['AcmeList', 'AcmeListCell']);
+ // An import the package cannot resolve lists no members, not the
+ // same-stem file's.
+ fs.rmSync(path.join(root, 'src', 'index.ts'));
+ expect(namesIn(loaded)).toEqual(['AcmeList']);
+ });
+
+ it("takes a member's source from the family's folder, never a bundle or the package root", () => {
+ const loaded = writePackage(
+ {exports: {'.': {import: './dist/index.mjs'}}},
+ {
+ 'src/tabs/AcmeTabs.doc.mjs': family(
+ 'AcmeTabs',
+ "{name: 'AcmeTab', description: 'x'}",
+ ),
+ 'src/tabs/AcmeTabs.tsx':
+ 'export function AcmeTabs() { return null; }\nexport function AcmeTab() { return null; }\n',
+ 'dist/index.mjs':
+ 'function AcmeTabs() { return null; }\nfunction AcmeTab() { return null; }\nexport {AcmeTabs, AcmeTab};\n',
+ // A member only the package's root file and the bundle declare is
+ // listed, with no source.
+ 'src/cards/AcmeCards.doc.mjs': family(
+ 'AcmeCards',
+ "{name: 'AcmeCard', description: 'x'}",
+ ),
+ 'src/cards/AcmeCards.tsx':
+ 'export function AcmeCards() { return null; }\n',
+ 'src/index.tsx':
+ "export {AcmeCards} from './cards/AcmeCards';\nexport function AcmeCard() { return null; }\n",
+ },
+ );
+ fs.writeFileSync(
+ path.join(root, 'dist', 'index.mjs'),
+ `${fs.readFileSync(path.join(root, 'dist', 'index.mjs'), 'utf-8')}export function AcmeCard() { return null; }\n`,
+ );
+
+ const records = discoverIntegrationComponents(loaded);
+ expect(records.map(record => record.name).sort()).toEqual([
+ 'AcmeCard',
+ 'AcmeCards',
+ 'AcmeTab',
+ 'AcmeTabs',
+ ]);
+ expect(findIntegrationComponentSource(loaded, 'AcmeTab')).toBe(
+ path.join(root, 'src', 'tabs', 'AcmeTabs.tsx'),
+ );
+ expect(findIntegrationComponentDoc(loaded, 'AcmeCard')).toBe(
+ path.join(root, 'src', 'cards', 'AcmeCards.doc.mjs'),
+ );
+ expect(findIntegrationComponentSource(loaded, 'AcmeCard')).toBeNull();
+ expect(
+ records.find(record => record.name === 'AcmeCard')?.sourcePath,
+ ).toBeNull();
+ });
+
+ it('lists a member only a bundle declares, with no source, when the family doc sits at the package root', () => {
+ const loaded = {
+ ...writePackage(
+ {exports: {'.': './dist/index.mjs'}},
+ {
+ 'AcmeStrip.doc.mjs': family(
+ 'AcmeStrip',
+ "{name: 'AcmeStripItem', description: 'x'}",
+ ).replace('usage:', "import: '@acme/widgets', usage:"),
+ 'AcmeStrip.tsx': 'export function AcmeStrip() { return null; }\n',
+ 'dist/index.mjs':
+ 'export function AcmeStrip() { return null; }\nexport function AcmeStripItem() { return null; }\n',
+ },
+ ),
+ components: root,
+ };
+ expect(namesIn(loaded)).toEqual(['AcmeStrip', 'AcmeStripItem']);
+ expect(findIntegrationComponentSource(loaded, 'AcmeStripItem')).toBeNull();
+ });
+
+ it('lists the members a family doc without its own source imports', () => {
+ const loaded = writePackage(
+ {exports: {'./group': './src/group/index.ts'}},
+ {
+ 'src/group/AcmeGroup.doc.mjs': family(
+ 'AcmeGroup',
+ "{name: 'AcmeGroupItem', description: 'x'}",
+ ).replace('usage:', "import: '@acme/widgets/group', usage:"),
+ 'src/group/index.ts':
+ "export {AcmeGroupItem} from './AcmeGroupItem';\n",
+ 'src/group/AcmeGroupItem.tsx':
+ 'export function AcmeGroupItem() { return null; }\n',
+ },
+ );
+ expect(namesIn(loaded)).toEqual(['AcmeGroup', 'AcmeGroupItem']);
+ expect(findIntegrationComponentSource(loaded, 'AcmeGroupItem')).toBe(
+ path.join(root, 'src', 'group', 'AcmeGroupItem.tsx'),
+ );
+ });
+
+ it("finds a member's source in the family's folder when the import names built output", () => {
+ const loaded = writePackage(
+ {exports: {'./list': './dist/list/index.js'}},
+ {
+ 'src/list/AcmeList.doc.mjs': family(
+ 'AcmeList',
+ "{name: 'AcmeListRow', description: 'x'}",
+ ).replace('usage:', "import: '@acme/widgets/list', usage:"),
+ 'src/list/AcmeList.tsx':
+ 'export function AcmeList() { return null; }\n',
+ 'src/list/row.tsx': 'export function AcmeListRow() { return null; }\n',
+ 'src/list/row.test.tsx':
+ 'export function AcmeListRow() { return null; }\n',
+ 'dist/list/index.js':
+ "export {AcmeList} from './list.js';\nexport * from './row.js';\n",
+ 'dist/list/list.js': 'export function AcmeList() { return null; }\n',
+ 'dist/list/row.js': 'export function AcmeListRow() { return null; }\n',
+ },
+ );
+ expect(namesIn(loaded)).toEqual(['AcmeList', 'AcmeListRow']);
+ expect(findIntegrationComponentSource(loaded, 'AcmeListRow')).toBe(
+ path.join(root, 'src', 'list', 'row.tsx'),
+ );
+ // Until the output exists, the import exports nothing.
+ fs.rmSync(path.join(root, 'dist'), {recursive: true});
+ expect(namesIn(loaded)).toEqual(['AcmeList']);
+ });
+
+ it('lists a member another folder declares, with no source', async () => {
+ const loaded = writePackage(
+ {exports: {'./menu': './src/menu/index.ts'}},
+ {
+ 'src/menu/AcmeMenu.doc.mjs': family(
+ 'AcmeMenu',
+ "{name: 'AcmeMenuItem', description: 'x'}",
+ ).replace('usage:', "import: '@acme/widgets/menu', usage:"),
+ 'src/menu/AcmeMenu.tsx':
+ 'export function AcmeMenu() { return null; }\n',
+ 'src/menu/index.ts':
+ "export {AcmeMenu} from './AcmeMenu';\nexport {AcmeMenuItem} from '../shared/AcmeMenuItem';\n",
+ 'src/shared/AcmeMenuItem.tsx':
+ 'export function AcmeMenuItem() { return null; }\n',
+ },
+ );
+ expect(namesIn(loaded)).toEqual(['AcmeMenu', 'AcmeMenuItem']);
+ expect(findIntegrationComponentDoc(loaded, 'AcmeMenuItem')).toBe(
+ path.join(root, 'src', 'menu', 'AcmeMenu.doc.mjs'),
+ );
+ expect(findIntegrationComponentSource(loaded, 'AcmeMenuItem')).toBeNull();
+ // A member without a source is valid: only a doc's own component needs
+ // its same-stem file.
+ const {components, errors} = await discoverValidIntegrationComponents(
+ /** @type {any} */ (loaded),
+ );
+ expect(errors).toEqual([]);
+ expect(components.map(component => component.name).sort()).toEqual([
+ 'AcmeMenu',
+ 'AcmeMenuItem',
+ ]);
+ });
+
+ it('reads members a binding holds and entries with computed fields', () => {
+ fs.writeFileSync(
+ path.join(root, 'AcmeRows.doc.mjs'),
+ "const describe = text => text;\nconst MEMBERS = [{name: 'AcmeRow', description: describe('A row.')}];\nexport default {type: 'component', name: 'AcmeRows', usage: {description: 'x'}, components: MEMBERS};\n",
+ );
+ fs.writeFileSync(
+ path.join(root, 'AcmeRows.tsx'),
+ 'export function AcmeRows() { return null; }\nexport function AcmeRow() { return null; }\n',
+ );
+ expect(names()).toEqual(['AcmeRow', 'AcmeRows']);
+ });
+
+ it("lists the doc's own name when its file keeps its own, and declares replaces once", async () => {
+ writeFamily('Chip', {
+ name: 'AcmeChip',
+ extra: "\n replaces: 'Badge',",
+ members:
+ "[{name: 'AcmeChip', description: 'x'}, {name: 'AcmeChipIcon', description: 'x'}]",
+ source:
+ 'export function Chip() { return null; }\nexport function AcmeChip() { return null; }\nexport function AcmeChipIcon() { return null; }\n',
+ });
+ const {components} =
+ await discoverValidIntegrationComponents(integration());
+ expect(components.map(record => [record.name, record.replaces])).toEqual([
+ ['Chip', 'Badge'],
+ ['AcmeChip', undefined],
+ ['AcmeChipIcon', undefined],
+ ]);
+ });
+
+ it('takes no member name a hidden doc or a replacement in the package claims', () => {
+ writeFamily('menu/AcmeMenu', {
+ name: 'AcmeMenu',
+ members:
+ "[{name: 'AcmeMenuDivider', description: 'x'}, {name: 'Carousel', description: 'x'}, {name: 'AcmeMenuItem', description: 'x'}]",
+ source:
+ 'export function AcmeMenu() { return null; }\nexport function AcmeMenuDivider() { return null; }\nexport function Carousel() { return null; }\nexport function AcmeMenuItem() { return null; }\n',
+ });
+ writeComponent('menu/AcmeMenuDivider', {
+ name: "'AcmeMenuDivider'",
+ extra: '\n hidden: true,',
+ });
+ writeComponent('Slides', {
+ name: "'AcmeCarousel'",
+ extra: "\n replaces: 'Carousel',",
+ source: 'export function AcmeCarousel() { return null; }\n',
+ });
+ expect(names()).toEqual(['AcmeCarousel', 'AcmeMenu', 'AcmeMenuItem']);
+ expect(findIntegrationComponentDoc(integration(), 'Carousel')).toBeNull();
+ });
+});
diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjs
index e85004b0dc..7b0729a364 100644
--- a/packages/cli/foundation/discovery/component-discovery.mjs
+++ b/packages/cli/foundation/discovery/component-discovery.mjs
@@ -12,7 +12,13 @@ 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';
-import {moduleExportsName, staticExportObject} from './module-exports.mjs';
+import {
+ HAS_COMPUTED,
+ moduleExportSource,
+ moduleExportsName,
+ staticExportObject,
+} from './module-exports.mjs';
+import {inspectPackageExport} from './package-exports.mjs';
const require = createRequire(import.meta.url);
@@ -87,22 +93,27 @@ const HIDDEN_RE = /(?:^|\n) {0,2}hidden:\s*true/;
// Every top-level `name: '...'` (or `"name": "..."`) in the file: a quick check
// that a doc is named after its file before anything parses it.
const NAME_FIELD_RE = /(?:^|\n) {0,2}['"]?name['"]?\s*:\s*['"]([^'"\n]+)['"]/g;
+// A `components` field anywhere in the file, written out or as a shorthand: the
+// quick check for a family doc, before anything parses it. A false match only
+// costs the parse.
+const MEMBERS_FIELD_RE = /\bcomponents\b/;
// A top-level `replaces: '...'`: the Core name a doc claims for its package.
const REPLACES_FIELD_RE =
/(?:^|\n) {0,2}['"]?replaces['"]?\s*:\s*['"]([^'"\n]+)['"]/;
/**
* What a quick scan of a doc's text finds before anything parses it: the
- * top-level `name` values it writes (none when a spread could set the name)
- * and the Core name it replaces.
+ * top-level `name` values it writes (none when a spread could set the name),
+ * whether it may list family members, and the Core name it replaces.
* @param {string} text
- * @returns {{names: string[], replaces: string | null}}
+ * @returns {{names: string[], hasMembers: boolean, replaces: string | null}}
*/
function scanDocText(text) {
return {
names: text.includes('...')
? []
: [...text.matchAll(NAME_FIELD_RE)].map(match => match[1]),
+ hasMembers: MEMBERS_FIELD_RE.test(text),
replaces: REPLACES_FIELD_RE.exec(text)?.[1] ?? null,
};
}
@@ -112,7 +123,7 @@ function scanDocText(text) {
* component's .doc.mjs file (synchronous), with what {@link scanDocText}
* finds in it.
* @param {string} docPath
- * @returns {{group: string | null, hiddenComponents: Set<string>, hidden: boolean, names: string[], replaces: string | null}}
+ * @returns {{group: string | null, hiddenComponents: Set<string>, hidden: boolean, names: string[], hasMembers: boolean, replaces: string | null}}
*/
function readDocMeta(docPath) {
try {
@@ -139,6 +150,7 @@ function readDocMeta(docPath) {
hiddenComponents: new Set(),
hidden: false,
names: [],
+ hasMembers: false,
replaces: null,
};
}
@@ -180,9 +192,12 @@ function docMemberNames(source) {
let ast;
try {
babelParser ??= require('@babel/parser');
- ast = /** @type {typeof import('@babel/parser')} */ (babelParser).parse(source, {
- sourceType: 'module',
- });
+ ast = /** @type {typeof import('@babel/parser')} */ (babelParser).parse(
+ source,
+ {
+ sourceType: 'module',
+ },
+ );
} catch {
return [];
}
@@ -197,12 +212,16 @@ function docMemberNames(source) {
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') {
+ if (
+ node.type === 'ExportNamedDeclaration' &&
+ declarator.id.name === 'docs'
+ ) {
docsExport = declarator.init;
}
}
}
- if (node.type === 'ExportDefaultDeclaration') defaultExport = node.declaration;
+ if (node.type === 'ExportDefaultDeclaration')
+ defaultExport = node.declaration;
}
let doc = defaultExport ?? docsExport;
if (doc?.type === 'Identifier') doc = constants.get(doc.name);
@@ -420,7 +439,9 @@ export function discoverComponents(coreDir) {
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'))) {
+ if (
+ listDir(path.join(srcDir, name)).some(file => file.endsWith('.doc.mjs'))
+ ) {
continue;
}
if (!hasOwnFolder(srcDir, name)) continue;
@@ -875,8 +896,8 @@ export function findExternalComponentDoc(docsDir, name) {
// commands — and the future integration-component swizzle — can disambiguate
// by package and route source/issues correctly.
-// A doc's `name` can name another export of its file; every other doc reads as
-// before.
+// A doc's `name` can name another export of its file, and a family doc's full
+// entries are components under their own names; every other doc reads as before.
const COMPONENT_NAME_RE = /^[A-Z][\w$]*$/;
/** @type {Map<string, {stamp: string, value: Record<string, any> | null}>} doc reads, reused while the doc file is unchanged */
@@ -940,6 +961,256 @@ function otherExportName({docPath, sourcePath, stem, names}) {
: null;
}
+/**
+ * The file Node loads for a package without `exports`: its `main`, else its
+ * `index` file.
+ * @param {string} packageDir
+ * @returns {string | null}
+ */
+function packageMain(packageDir) {
+ let main;
+ try {
+ main = JSON.parse(
+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),
+ ).main;
+ } catch {
+ return null;
+ }
+ const entry =
+ typeof main === 'string' && main !== ''
+ ? `./${path.posix.normalize(main).replace(/^\.\//, '')}`
+ : './index';
+ return inspectPackageExport({}, packageDir, entry).target;
+}
+
+/**
+ * The local module a doc's import names: the doc's own `import`, else the
+ * subpath its directory publishes, read through the package's `exports` (its
+ * `main` when it has none). Undefined when the package directory is unknown;
+ * null when the import names another package or resolves to no file.
+ *
+ * @param {{name?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
+ * @param {string} docPath
+ * @param {Record<string, any> | null} doc
+ * @returns {string | null | undefined}
+ */
+function importedModule(integration, docPath, doc) {
+ const packageName = integration?.name;
+ const packageDir = integration?.__packageDir;
+ if (!packageName || !packageDir) return undefined;
+ const exportsMap =
+ integration.__packageExports === undefined
+ ? readPackageExports(packageDir)
+ : integration.__packageExports;
+ const specifier = resolveIntegrationImportPath(
+ {exportsMap, packageDir, docPath, packageName},
+ docStem(docPath),
+ typeof doc?.import === 'string' ? doc.import : null,
+ );
+ if (specifier !== packageName && !specifier.startsWith(`${packageName}/`)) {
+ return null;
+ }
+ if (specifier === packageName && exportsMap == null) {
+ return packageMain(packageDir);
+ }
+ const subpath =
+ specifier === packageName
+ ? '.'
+ : `./${specifier.slice(packageName.length + 1)}`;
+ return inspectPackageExport(
+ {name: packageName, exports: exportsMap ?? undefined},
+ packageDir,
+ subpath,
+ ).target;
+}
+
+/**
+ * Whether `file` sits in `folder` or below it.
+ * @param {string} folder
+ * @param {string} file
+ */
+function isWithin(folder, file) {
+ const relative = path.relative(folder, file);
+ return (
+ relative !== '' &&
+ !path.isAbsolute(relative) &&
+ relative.split(path.sep)[0] !== '..'
+ );
+}
+
+/**
+ * The `.tsx` file in `folder`, or below it, that declares `name`, taking files
+ * in path order: the source of a member whose import never reaches a `.tsx`
+ * file, as when the import names built output.
+ *
+ * @param {string} folder
+ * @param {string} name
+ * @returns {string | null}
+ */
+function folderSourceFor(folder, name) {
+ /** @type {string[]} */
+ const files = [];
+ /** @param {string} dirPath */
+ const scan = dirPath => {
+ for (const entry of listDirEntries(dirPath)) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ if (entry.name.startsWith('.')) continue;
+ const fullPath = path.join(dirPath, entry.name);
+ if (entry.isDirectory()) scan(fullPath);
+ else if (
+ entry.name.endsWith('.tsx') &&
+ !/\.(?:test|spec|stories)\.tsx$/.test(entry.name)
+ ) {
+ files.push(fullPath);
+ }
+ }
+ };
+ scan(folder);
+ for (const file of files.sort(byCodeUnit)) {
+ const declared = moduleExportSource(file, name);
+ if (
+ declared != null &&
+ declared.endsWith('.tsx') &&
+ isWithin(folder, declared)
+ ) {
+ return declared;
+ }
+ }
+ return null;
+}
+
+/**
+ * The full entries a family doc lists in `components` that the module its
+ * import names exports, each with its source. An entry is full when it says
+ * more than its `name`; the name must be static PascalCase, not hidden, and
+ * neither the doc's stem nor the export the doc is recorded under. A member's
+ * source is the `.tsx` file in the family doc's folder, or below it, that
+ * declares it: the one the family's own source or the imported module reaches,
+ * else the one in that folder that declares the name, as when the import names
+ * built output. A member that only a bundle or a file outside the folder
+ * declares has no source.
+ *
+ * @param {{name?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
+ * @param {{docPath: string, sourcePath: string|null}} record the doc's own
+ * @param {string | null | undefined} ownName the export the doc is recorded
+ * under, when it names one
+ * @param {string} [only] look for this member alone
+ * @returns {Array<{name: string, sourcePath: string | null}>}
+ */
+function familyMembers(integration, record, ownName, only) {
+ const familySource = record.sourcePath;
+ const doc = docObject(record.docPath);
+ const entries = Array.isArray(doc?.components) ? doc.components : [];
+ const hidden = new Set(
+ Array.isArray(doc?.hiddenComponents) ? doc.hiddenComponents : [],
+ );
+ const stem = docStem(record.docPath);
+ /** @type {string[]} */
+ const names = [];
+ for (const entry of entries) {
+ if (entry == null || typeof entry !== 'object') continue;
+ const name = entry.name;
+ const full = Object.keys(entry).length > 1 || entry[HAS_COMPUTED] === true;
+ if (typeof name !== 'string' || !full) continue;
+ if (!COMPONENT_NAME_RE.test(name) || hidden.has(name)) continue;
+ if (name === stem || name === ownName) continue;
+ if (only != null && name !== only) continue;
+ names.push(name);
+ }
+ if (names.length === 0) return [];
+ const imported = importedModule(integration, record.docPath, doc);
+ const module = imported === undefined ? familySource : imported;
+ if (module == null) return [];
+ const folder = path.dirname(record.docPath);
+ /** @param {string | null} file */
+ const inFolder = file =>
+ file != null && file.endsWith('.tsx') && isWithin(folder, file);
+ return names.flatMap(name => {
+ const exported = moduleExportSource(module, name);
+ if (exported == null) return [];
+ // A member's source is a `.tsx` file in the family's folder, as a doc's own
+ // is: never a bundle, even one under a family at the package root.
+ const reached = [
+ familySource == null ? null : moduleExportSource(familySource, name),
+ exported,
+ ].find(inFolder);
+ return [{name, sourcePath: reached ?? folderSourceFor(folder, name)}];
+ });
+}
+
+/**
+ * Each family doc under an integration's components root that names an
+ * import, with the file the import resolves to: null when it resolves to none,
+ * such as build output that does not exist yet.
+ *
+ * @param {{name: string, components?: string, issuesUrl?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
+ * @returns {Array<{docPath: string, module: string | null}>}
+ */
+export function familyImports(integration) {
+ return discoverIntegrationComponents(integration).flatMap(record => {
+ if (record.docPath == null || !isOwnRecord(record)) return [];
+ const doc = docObject(record.docPath);
+ if (!Array.isArray(doc?.components) || doc.components.length === 0) {
+ return [];
+ }
+ const module = importedModule(integration, record.docPath, doc);
+ return module === undefined ? [] : [{docPath: record.docPath, module}];
+ });
+}
+
+/**
+ * Whether `record` is its doc's own component (under the doc's stem or the
+ * export its `name` documents) rather than a member the doc lists.
+ *
+ * @param {{name: string, docPath: string|null}} record
+ * @returns {boolean}
+ */
+function isOwnRecord(record) {
+ if (record.docPath == null) return true;
+ const stem = docStem(record.docPath);
+ if (stem === record.name) return true;
+ return (
+ otherExportName({
+ docPath: record.docPath,
+ sourcePath: integrationSourceForDoc(record.docPath),
+ stem,
+ names: [],
+ }) === record.name
+ );
+}
+
+/**
+ * Whether a discovered integration record is a member its family doc lists,
+ * decided from the files, not from whether the doc loads.
+ *
+ * @param {{name: string, docPath: string|null}} record
+ * @returns {boolean}
+ */
+export function isIntegrationMember(record) {
+ return !isOwnRecord(record);
+}
+
+/**
+ * The entry a family doc gives a member that discovery lists under its own
+ * name, or null when the record is the doc's own component or the loaded doc
+ * has no entry for it.
+ *
+ * @param {any} doc the doc loaded from `record.docPath`
+ * @param {{name: string, docPath: string|null}} record
+ * @returns {any}
+ */
+export function integrationMemberEntry(doc, record) {
+ if (doc == null || typeof doc !== 'object' || isOwnRecord(record)) {
+ return null;
+ }
+ if (!Array.isArray(doc.components)) return null;
+ return (
+ doc.components.find(
+ (/** @type {any} */ entry) => entry?.name === record.name,
+ ) ?? null
+ );
+}
+
/**
* Visit every component doc under an integration's components root, hidden
* ones included, in discovery order, with its stem.
@@ -983,10 +1254,11 @@ function integrationSourceForDoc(docPath) {
* integration. Scans the integration's resolved `components` dir for same-stem
* doc files and records each with owner package + issuesUrl + sourcePath. A doc
* that names a differently named export of its file is recorded under that
- * export unless the name is taken: every doc's file name (a hidden doc's too),
- * a Core name a doc in the package replaces, and a name an earlier doc records.
+ * export, and each family member it lists, under the member's name, unless the
+ * name is taken: every doc's file name (a hidden doc's too), a Core name a doc
+ * in the package replaces, and a name an earlier doc records.
*
- * @param {{name: string, components?: string, issuesUrl?: string}} integration
+ * @param {{name: string, components?: string, issuesUrl?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
* a single entry from `loadedIntegrations` (lib/integrations.mjs)
* @param {{documentedNames?: boolean}} [options] `documentedNames: false`
* records each doc under its file name alone, without reading the names
@@ -1002,14 +1274,14 @@ export function discoverIntegrationComponents(
/** @type {Map<string, {name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}>} */
const byName = new Map();
- /** @type {Map<string, {names: string[], replaces: string | null}>} stem → quick scan */
+ /** @type {Map<string, {names: string[], hasMembers: boolean, replaces: string | null}>} stem → quick scan */
const scans = new Map();
/** @type {Set<string>} names no doc can record under another name */
const taken = new Set();
forEachIntegrationDoc(componentsDir, (fullPath, name) => {
taken.add(name);
- const {group, hidden, names, replaces} = readDocMeta(fullPath);
+ const {group, hidden, names, hasMembers, replaces} = readDocMeta(fullPath);
if (hidden) return;
// First doc wins per name (precedence matches INTEGRATION_DOC_SUFFIXES).
if (byName.has(name)) return;
@@ -1021,12 +1293,13 @@ export function discoverIntegrationComponents(
issuesUrl: integration.issuesUrl,
group: group ?? null,
});
- scans.set(name, {names, replaces});
+ scans.set(name, {names, hasMembers, replaces});
});
if (!documentedNames) return [...byName.values()];
// A doc that names a differently named export of its file is listed under
- // that export, unless the name is taken.
+ // that export, and each member a family doc lists under the member's name,
+ // unless the name is taken.
for (const {replaces} of scans.values()) if (replaces) taken.add(replaces);
const records = [...byName.values()];
const byPath = [...records].sort((a, b) => byCodeUnit(a.docPath, b.docPath));
@@ -1042,10 +1315,22 @@ export function discoverIntegrationComponents(
taken.add(exportName);
exportNames.set(record.name, exportName);
}
- return records.map(record => {
+ /** @type {typeof records} */
+ const members = [];
+ for (const record of byPath) {
+ if (!scans.get(record.name)?.hasMembers) continue;
+ const ownName = exportNames.get(record.name);
+ for (const member of familyMembers(integration, record, ownName)) {
+ if (taken.has(member.name)) continue;
+ taken.add(member.name);
+ members.push({...record, ...member});
+ }
+ }
+ const named = records.map(record => {
const name = exportNames.get(record.name);
return name ? {...record, name} : record;
});
+ return [...named, ...members];
}
/**
@@ -1053,27 +1338,33 @@ export function discoverIntegrationComponents(
* Invalid metadata or a missing same-stem source removes only that component;
* callers can report the returned errors while retaining valid siblings. A
* component whose doc sets `replaces` carries the value as written; the
- * component replacement resolver decides what it means. A doc that fails to
- * load is reported under its file name: what it says cannot be trusted.
+ * component replacement resolver decides what it means. A family member is
+ * read through its family's doc: it never carries the family's `replaces`, and
+ * a family doc that fails to load is reported once. A doc that fails to load
+ * is reported under its file name: what it says cannot be trusted.
*
* @param {{name: string, components?: string, issuesUrl?: string}} integration
* @param {{documentedNames?: boolean}} [options] as for
* {@link discoverIntegrationComponents}
* @returns {Promise<{
- * components: Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null, replaces?: unknown}>,
+ * components: Array<{name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null, replaces?: unknown}>,
* discovered: Array<{name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}>,
* errors: Array<{name: string, message: string}>,
* }>}
*/
export async function discoverValidIntegrationComponents(integration, options) {
const discovered = discoverIntegrationComponents(integration, options);
- /** @type {Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null, replaces?: unknown}>} */
+ /** @type {Array<{name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null, replaces?: unknown}>} */
const components = [];
/** @type {Array<{name: string, message: string}>} */
const errors = [];
+ /** @type {Set<string>} docs that failed to load */
+ const failedDocs = new Set();
for (const record of discovered) {
- if (record.sourcePath == null) {
+ // A doc's own component needs its same-stem source. A member has none when
+ // only a bundle or a file outside its family's folder declares it.
+ if (record.sourcePath == null && isOwnRecord(record)) {
errors.push({
name: record.name,
message: `Component "${record.name}" is missing its same-stem source file ${record.name}.tsx.`,
@@ -1083,15 +1374,20 @@ export async function discoverValidIntegrationComponents(integration, options) {
try {
const doc = await loadComponentDoc(record.docPath);
const valid =
- /** @type {{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null}} */ (
+ /** @type {{name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}} */ (
record
);
components.push(
- doc != null && typeof doc === 'object' && doc.replaces !== undefined
+ isOwnRecord(record) &&
+ doc != null &&
+ typeof doc === 'object' &&
+ doc.replaces !== undefined
? {...valid, replaces: doc.replaces}
: valid,
);
} catch (err) {
+ if (failedDocs.has(record.docPath)) continue;
+ failedDocs.add(record.docPath);
const name = docStem(record.docPath);
errors.push({
name,
@@ -1109,8 +1405,8 @@ export async function discoverValidIntegrationComponents(integration, options) {
* How an owner holds a component name, which the owner rule
* ({@link unscopedComponentOwners}) reads: `core` when Core documents it;
* `file` when an integration doc named after its file is recorded under it;
- * `doc` when only a doc records it: an export name, or the file name of a doc
- * recorded under another export.
+ * `doc` when only a doc records it: an export name, a member, or the file name
+ * of a doc recorded under another export.
* @typedef {'core' | 'file' | 'doc'} NameHold
*/
@@ -1126,19 +1422,20 @@ export function integrationRecordHold(record) {
}
/**
- * The doc that records `name` though its file is named otherwise, with its
- * source, reading only docs that write the name as a string.
+ * The doc that records `name` as its export or a member though its file is
+ * named otherwise, with the source, reading only docs that write the name.
*
+ * @param {{name?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
* @param {string} componentsDir
* @param {string} name
* @returns {{docPath: string, sourcePath: string|null} | null}
*/
-function findDocumentedComponent(componentsDir, name) {
+function findDocumentedComponent(integration, componentsDir, name) {
if (!COMPONENT_NAME_RE.test(name)) return null;
const literals = [`'${name}'`, `"${name}"`, `\`${name}\``];
/** @type {Set<string>} */
const stems = new Set();
- /** @type {Array<{docPath: string, stem: string, names: string[], replaces: string | null, sourcePath: string|null}>} */
+ /** @type {Array<{docPath: string, stem: string, names: string[], hasMembers: boolean, replaces: string | null, sourcePath: string|null}>} */
const candidates = [];
forEachIntegrationDoc(componentsDir, (docPath, stem) => {
let text;
@@ -1161,17 +1458,28 @@ function findDocumentedComponent(componentsDir, name) {
// A Core name a doc in the package replaces is the replacement's to answer.
if (candidates.some(candidate => candidate.replaces === name)) return null;
candidates.sort((a, b) => byCodeUnit(a.docPath, b.docPath));
- const found = candidates.find(
- candidate => otherExportName(candidate) === name,
- );
- return found ? {docPath: found.docPath, sourcePath: found.sourcePath} : null;
+ for (const candidate of candidates) {
+ if (otherExportName(candidate) === name) {
+ return {docPath: candidate.docPath, sourcePath: candidate.sourcePath};
+ }
+ }
+ for (const candidate of candidates) {
+ if (!candidate.hasMembers) continue;
+ const ownName = otherExportName(candidate);
+ const [member] = familyMembers(integration, candidate, ownName, name);
+ if (member) {
+ return {docPath: candidate.docPath, sourcePath: member.sourcePath};
+ }
+ }
+ return null;
}
/**
* The integration component a name finds, as discovery records it, and its
- * hold: the same-stem doc first, then a doc that records the name.
+ * hold: the same-stem doc first, then a doc that records the name as an export
+ * or a member.
*
- * @param {{components?: string}} integration
+ * @param {{name?: string, components?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
* @param {string} name
* @returns {{docPath: string, sourcePath: string|null, hold: 'file' | 'doc'} | null}
*/
@@ -1189,24 +1497,48 @@ export function findIntegrationComponent(integration, name) {
const renamed =
exportName != null &&
findSameStemDoc(componentsDir, exportName) == null &&
- findDocumentedComponent(componentsDir, exportName)?.docPath === sameStem;
+ findDocumentedComponent(integration, componentsDir, exportName)
+ ?.docPath === sameStem;
return {
docPath: sameStem,
sourcePath: integrationSourceForDoc(sameStem),
hold: renamed ? 'doc' : 'file',
};
}
- const found = findDocumentedComponent(componentsDir, name);
+ const found = findDocumentedComponent(integration, componentsDir, name);
return found && {...found, hold: 'doc'};
}
+/**
+ * The name discovery records a component doc under: the export its `name`
+ * documents when the doc is recorded under it, else the doc's file name.
+ *
+ * @param {{name?: string, components?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
+ * @param {string} docPath
+ * @returns {string}
+ */
+export function recordedDocName(integration, docPath) {
+ const stem = docStem(docPath);
+ const found = findIntegrationComponent(integration, stem);
+ if (found?.docPath !== docPath || found.hold !== 'doc') return stem;
+ return (
+ otherExportName({
+ docPath,
+ sourcePath: integrationSourceForDoc(docPath),
+ stem,
+ names: readDocMeta(docPath).names,
+ }) ?? stem
+ );
+}
+
/**
* Find an integration component's doc file by name within a loaded
* integration's resolved `components` dir. Honors the same-stem convention
* (`{Name}.doc.{ts,mjs,js}`), preferring `.ts` → `.mjs` → `.js`, and finds a
- * doc that records the component under a differently named export of its file.
+ * doc that records the component under another name: a differently named
+ * export of its file, or a member its family doc lists.
*
- * @param {{components?: string}} integration
+ * @param {{name?: string, components?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
* @param {string} name bare component name (no `XDS`/`Astryx` prefix)
* @returns {string|null}
*/
@@ -1248,9 +1580,10 @@ function findSameStemDoc(componentsDir, name) {
/**
* Find an integration component's swizzleable source file by name within a
* loaded integration's resolved `components` dir: the same-stem `{Name}.tsx`
- * of its doc. Returns null when the integration ships docs without source.
+ * of its doc, or, for a family member, the file that declares it. Returns null
+ * when the integration ships docs without source.
*
- * @param {{components?: string}} integration
+ * @param {{name?: string, components?: string, __packageDir?: string, __packageExports?: Record<string, unknown>|null}} integration
* @param {string} name bare component name
* @returns {string|null}
*/
diff --git a/packages/cli/foundation/discovery/component-replacement.test.mjs b/packages/cli/foundation/discovery/component-replacement.test.mjs
index 4600459d25..13cf0edca7 100644
--- a/packages/cli/foundation/discovery/component-replacement.test.mjs
+++ b/packages/cli/foundation/discovery/component-replacement.test.mjs
@@ -279,6 +279,26 @@ describe('resolveComponentReplacements', () => {
});
});
+ it("counts a doc's replaces once when the doc lists its own name as a member", async () => {
+ // Chip.doc.mjs documents AcmeChip beside a Chip.tsx that exports both, and
+ // lists itself first, as the component-family guide asks.
+ const acme = integrationWithDocSource(
+ '@acme/chips',
+ 'Chip',
+ `export default {type: 'component', name: 'AcmeChip', replaces: 'Badge', usage: {description: 'Acme chip.'}, components: [{name: 'AcmeChip', description: 'A chip.', props: []}]};\n`,
+ );
+ fs.writeFileSync(
+ path.join(acme.components, 'Chip.tsx'),
+ 'export function Chip() { return null; }\nexport function AcmeChip() { return null; }\n',
+ );
+ const result = await resolveComponentReplacements(CORE_DIR, [acme]);
+ expect(result.findings).toEqual([]);
+ expect(result.forTarget('Badge')).toMatchObject({
+ name: 'Chip',
+ package: '@acme/chips',
+ });
+ });
+
it('lets a replacement keep the Core name it replaces', async () => {
const acme = integration(
'@acme/nav',
diff --git a/packages/cli/foundation/discovery/module-exports.mjs b/packages/cli/foundation/discovery/module-exports.mjs
index 4c96ffa8f7..b85cc9d387 100644
--- a/packages/cli/foundation/discovery/module-exports.mjs
+++ b/packages/cli/foundation/discovery/module-exports.mjs
@@ -309,6 +309,13 @@ export function moduleExportSource(file, exportName, seen = new Set()) {
return found;
}
+/**
+ * Marks an object {@link staticExportObject} returns (or one inside it) whose
+ * source also has properties or spreads it could not read as literals. Not
+ * enumerable, so the object compares and serializes as its literal properties.
+ */
+export const HAS_COMPUTED = Symbol('hasComputed');
+
const TS_WRAPPERS = new Set([
'TSSatisfiesExpression',
'TSAsExpression',
@@ -423,22 +430,28 @@ export function staticExportObject(file, exportNames) {
case 'ObjectExpression': {
/** @type {Record<string, unknown>} */
let object = {};
+ let computed = false;
for (const property of value.properties) {
if (property.type === 'SpreadElement') {
object = {};
+ computed = true;
continue;
}
const key = property.computed
? undefined
: (property.key?.name ?? property.key?.value);
- if (typeof key !== 'string') continue;
const item =
- property.type === 'ObjectProperty'
+ typeof key === 'string' && property.type === 'ObjectProperty'
? literal(property.value, following)
: undefined;
+ if (item === undefined) computed = true;
+ if (typeof key !== 'string') continue;
if (item === undefined) delete object[key];
else object[key] = item;
}
+ if (computed) {
+ Object.defineProperty(object, HAS_COMPUTED, {value: true});
+ }
return object;
}
default:
diff --git a/packages/cli/foundation/integrations/contribution-inventory.mjs b/packages/cli/foundation/integrations/contribution-inventory.mjs
index 118fad4725..3b7e88b5d8 100644
--- a/packages/cli/foundation/integrations/contribution-inventory.mjs
+++ b/packages/cli/foundation/integrations/contribution-inventory.mjs
@@ -248,11 +248,16 @@ export async function collectIdentities(loaded) {
if (loaded.components && fs.existsSync(loaded.components)) {
try {
const records = discoverIntegrationComponents(loaded) ?? [];
+ // A family doc backs several records: load it, and report it, once.
+ const loads = new Map();
for (const record of records) {
+ const first = !loads.has(record.docPath);
+ if (first) loads.set(record.docPath, loadComponentDoc(record.docPath));
try {
- await loadComponentDoc(record.docPath);
+ await loads.get(record.docPath);
identities.components.push(record.name);
} catch (err) {
+ if (!first) continue;
errors.push({
kind: 'components',
message: `${path.relative(loaded.components, record.docPath)}: ${