import { beforeEach, expect, test, vi } from 'vitest'; import { Tag } from 'storybook/internal/core-server'; import { vol } from 'memfs'; import { dedent } from 'ts-dedent'; import { ComponentMetaManager } from './componentMeta/ComponentMetaManager.ts'; import { indexJson } from './fixtures.ts'; import { manifests } from './generator.ts'; import { setupMemfsMocks } from './memfs-test-setup.ts'; // Opt into memfs for this file (loads from __mocks__/fs.cjs) vi.mock('node:fs'); vi.mock('node:fs/promises'); vi.mock(import('./utils.ts'), { spy: true }); vi.mock('storybook/internal/common', { spy: true }); vi.mock('empathic/find', { spy: true }); vi.mock('tsconfig-paths', { spy: true }); /** Call manifests with only the fields tests need (presets/watch are optional-chained at runtime). */ type ManifestOptions = Parameters[1]; type ManifestEntries = ManifestOptions['manifestEntries']; const createManifestOptions = ( manifestEntries: ManifestEntries, options: Partial = {} ): ManifestOptions => ({ watch: false, manifestEntries, ...options }) as ManifestOptions; const runManifests = (manifestEntries: ManifestEntries) => manifests(undefined, createManifestOptions(manifestEntries)); const runManifestsWithOptions = ( manifestEntries: ManifestEntries, options: Partial = {} ) => manifests(undefined, createManifestOptions(manifestEntries, options)); beforeEach(() => { setupMemfsMocks(); }); test('manifests generates correct id, name, description and examples ', async () => { const manifestEntries = Object.values(indexJson.entries).filter( (entry) => entry.tags?.includes(Tag.MANIFEST) ?? false ); const result = await runManifests(manifestEntries); const { meta: _meta, ...components } = result?.components ?? {}; expect(components).toMatchInlineSnapshot(` { "components": { "example-button": { "description": "Primary UI component for user interaction", "error": undefined, "id": "example-button", "import": "import { Button } from '@design-system/components/override'; import { fn } from 'storybook/test';", "jsDocTags": { "import": [ "import { Button } from '@design-system/components/override';", ], }, "name": "Button", "path": "./src/stories/Button.stories.ts", "reactComponentMeta": undefined, "reactDocgen": { "actualName": "Button", "definedInFile": "./src/stories/Button.tsx", "description": "Primary UI component for user interaction @import import { Button } from '@design-system/components/override';", "displayName": "Button", "exportName": "Button", "methods": [], "props": { "backgroundColor": { "description": "", "required": false, "tsType": { "name": "string", }, }, "label": { "description": "", "required": true, "tsType": { "name": "string", }, }, "onClick": { "description": "", "required": false, "tsType": { "name": "signature", "raw": "() => void", "signature": { "arguments": [], "return": { "name": "void", }, }, "type": "function", }, }, "primary": { "defaultValue": { "computed": false, "value": "false", }, "description": "Description of primary", "required": false, "tsType": { "name": "boolean", }, }, "size": { "defaultValue": { "computed": false, "value": "'medium'", }, "description": "", "required": false, "tsType": { "elements": [ { "name": "literal", "value": "'small'", }, { "name": "literal", "value": "'medium'", }, { "name": "literal", "value": "'large'", }, ], "name": "union", "raw": "'small' | 'medium' | 'large'", }, }, }, }, "reactDocgenTypescript": undefined, "stories": [ { "description": undefined, "id": "example-button--primary", "name": "Primary", "snippet": "const Primary = () => ); };`, }, '/app' ); const manifestEntries: ManifestEntries = [ { type: 'story', subtype: 'story', id: 'example-button--primary', name: 'Primary', title: 'Example/Button', importPath: './src/stories/Button.stories.tsx', componentPath: './src/stories/Button.tsx', tags: [Tag.DEV, Tag.TEST, 'vitest', Tag.AUTODOCS, Tag.MANIFEST], exportName: 'Primary', }, ]; const result = await runManifests(manifestEntries); return result?.components?.components?.['example-button']; } function withCSF3(body: string) { return dedent` import type { Meta } from '@storybook/react'; import { Button } from './Button'; const meta = { title: 'Example/Button', component: Button, args: { onClick: fn() }, } satisfies Meta; export default meta; ${body} `; } test('fall back to index title when no component name', async () => { const code = dedent` import type { Meta } from '@storybook/react'; import { Button } from './Button'; export default { title: 'Example/Button', args: { onClick: fn() }, tags: ['manifest'], }; export const Primary = () => ); `, ['./src/stories/Button.tsx']: dedent` import React from 'react'; export interface ButtonProps { label: string; } /** Parent button docs */ export const Button = ({ label, children }: React.PropsWithChildren) => ( ); `, ['./src/stories/ButtonIcon.tsx']: dedent` import React from 'react'; export interface ButtonIconProps { icon: string; tone?: 'primary' | 'secondary'; } /** Child item docs */ export const ButtonIcon = ({ icon, tone = 'primary' }: ButtonIconProps) => ( {icon} ); `, }, '/app' ); const manifestEntries: ManifestEntries = [ { type: 'story', subtype: 'story', id: 'example-button--default', name: 'Default', title: 'Example/Button', importPath: './src/stories/Button.stories.tsx', componentPath: './src/stories/Button.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Default', }, ]; const result = await runManifests(manifestEntries); const button = result?.components?.components?.['example-button'] as any; expect(button?.subcomponents?.ButtonIcon?.name).toBe('ButtonIcon'); expect(button?.subcomponents?.ButtonIcon?.path).toContain('ButtonIcon.tsx'); expect(button?.subcomponents?.ButtonIcon?.reactDocgen?.props?.tone).toBeDefined(); expect(button?.subcomponents?.ButtonIcon?.description).toBe('Child item docs'); }); test('includes declared subcomponents even when they are not used in JSX', async () => { vol.fromJSON( { ['./package.json']: JSON.stringify({ name: 'some-package' }), ['./src/stories/Button.stories.tsx']: dedent` import type { Meta } from '@storybook/react'; import { Button } from './Button'; import { ButtonIcon } from './ButtonIcon'; const meta = { title: 'Example/Button', component: Button, subcomponents: { ButtonIcon }, } satisfies Meta; export default meta; export const Default = () => ; `, ['./src/stories/ButtonIcon.tsx']: dedent` import React from 'react'; export interface ButtonIconProps { icon: string; textValue?: string; } /** Supplemental child docs */ export const ButtonIcon = ({ icon }: ButtonIconProps) => {icon}; `, }, '/app' ); const manifestEntries: ManifestEntries = [ { type: 'story', subtype: 'story', id: 'example-button--default', name: 'Default', title: 'Example/Button', importPath: './src/stories/Button.stories.tsx', componentPath: './src/stories/Button.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Default', }, ]; const result = await runManifests(manifestEntries); const button = result?.components?.components?.['example-button'] as any; expect(button?.subcomponents?.ButtonIcon?.reactDocgen?.props?.textValue).toBeDefined(); expect(button?.subcomponents?.ButtonIcon?.description).toBe('Supplemental child docs'); }); test('includes aliased member-expression subcomponents', async () => { vol.fromJSON( { ['./package.json']: JSON.stringify({ name: 'some-package' }), ['./src/stories/ComboBox.stories.tsx']: dedent` import type { Meta } from '@storybook/react'; import * as ComboBox from './ComboBox'; const meta = { title: 'Example/ComboBox', component: ComboBox.Root, subcomponents: { Item: ComboBox.Item }, } satisfies Meta; export default meta; export const Default = () => ; `, ['./src/stories/ComboBox.tsx']: dedent` import React from 'react'; type RootProps = { open?: boolean }; type ItemProps = { textValue?: string }; const Root = ({ open = false }: RootProps) =>
; const Item = ({ textValue }: ItemProps) =>
; export const ComboBox = { Root, Item }; `, }, '/app' ); const batchExtract = vi .spyOn(ComponentMetaManager.prototype, 'batchExtract') .mockImplementation((entries) => { for (const entry of entries) { if (!entry.component) { continue; } if (entry.component.componentName === 'ComboBox.Root') { entry.component.reactComponentMeta = { displayName: 'ComboBox.Root', exportName: 'Root', filePath: '/app/src/stories/ComboBox.tsx', description: 'Root docs', props: { open: { name: 'open', required: false, type: { name: 'boolean' }, description: 'Whether the list is open', defaultValue: null, }, }, }; continue; } if (entry.component.componentName === 'ComboBox.Item') { entry.component.reactComponentMeta = { displayName: 'ComboBox.Item', exportName: 'Item', filePath: '/app/src/stories/ComboBox.tsx', description: 'Item docs', props: { textValue: { name: 'textValue', required: false, type: { name: 'string' }, description: 'Used for type-ahead filtering', defaultValue: null, }, }, }; } } }); const presets = { apply: async (extension: string, config?: unknown) => { if (extension === 'typescript') { return {}; } if (extension === 'features') { return { experimentalReactComponentMeta: true }; } return config; }, } as NonNullable; const manifestEntries: ManifestEntries = [ { type: 'story', subtype: 'story', id: 'example-combo-box--default', name: 'Default', title: 'Example/ComboBox', importPath: './src/stories/ComboBox.stories.tsx', componentPath: './src/stories/ComboBox.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Default', }, ]; const result = await runManifestsWithOptions(manifestEntries, { presets }); const comboBox = result?.components?.components?.['example-combo-box'] as any; expect(comboBox?.subcomponents?.Item?.name).toBe('Item'); expect(comboBox?.subcomponents?.Item?.reactComponentMeta?.props?.textValue).toBeDefined(); expect(batchExtract).toHaveBeenCalled(); }); test('keeps the parent manifest when a declared subcomponent cannot be resolved', async () => { vol.fromJSON( { ['./package.json']: JSON.stringify({ name: 'some-package' }), ['./src/stories/Button.stories.tsx']: dedent` import type { Meta } from '@storybook/react'; import { Button } from './Button'; const MissingItem = () => null; const meta = { title: 'Example/Button', component: Button, subcomponents: { MissingItem }, } satisfies Meta; export default meta; export const Default = () => ; `, }, '/app' ); const manifestEntries: ManifestEntries = [ { type: 'story', subtype: 'story', id: 'example-button--default', name: 'Default', title: 'Example/Button', importPath: './src/stories/Button.stories.tsx', componentPath: './src/stories/Button.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Default', }, ]; const result = await runManifests(manifestEntries); const button = result?.components?.components?.['example-button'] as any; expect(button?.error).toBeUndefined(); expect(button?.description).toBe('Parent button docs'); expect(button?.subcomponents?.MissingItem?.error).toMatchObject({ name: 'No component import found', }); }); test('generator uses reactComponentMeta displayName from batch extraction', async () => { const batchExtract = vi .spyOn(ComponentMetaManager.prototype, 'batchExtract') .mockImplementation((entries) => { for (const entry of entries) { if (entry.component) { entry.component.reactComponentMeta = { displayName: 'Header', exportName: 'default', filePath: '/app/src/stories/Header.tsx', description: '', props: {}, }; } } }); const presets = { apply: async (extension: string, config?: unknown) => { if (extension === 'typescript') { return {}; } if (extension === 'features') { return { experimentalReactComponentMeta: true }; } return config; }, } as NonNullable; const manifestEntries: ManifestEntries = [indexJson.entries['example-header--logged-in']]; const result = await runManifestsWithOptions(manifestEntries, { presets }); const header = result?.components?.components?.['example-header']; expect( header && 'reactComponentMeta' in header ? (header as any).reactComponentMeta?.displayName : undefined ).toBe('Header'); expect(batchExtract).toHaveBeenCalled(); }); test('generator preserves @import override when reactComponentMeta is enabled', async () => { const batchExtract = vi .spyOn(ComponentMetaManager.prototype, 'batchExtract') .mockImplementation((entries) => { for (const entry of entries) { if (entry.component) { entry.component.reactComponentMeta = { displayName: 'Button', exportName: 'Button', filePath: '/app/src/stories/Button.tsx', description: 'Primary UI component for user interaction', props: {}, }; entry.component.componentJsDocTags = { import: ["import { Button } from '@design-system/components/override';"], summary: ['Fast summary'], }; entry.component.importOverride = "import { Button } from '@design-system/components/override';"; } } }); const presets = { apply: async (extension: string, config?: unknown) => { if (extension === 'typescript') { return {}; } if (extension === 'features') { return { experimentalReactComponentMeta: true }; } return config; }, } as NonNullable; const manifestEntries: ManifestEntries = [indexJson.entries['example-button--primary']]; const result = await runManifestsWithOptions(manifestEntries, { presets }); const button = result?.components?.components?.['example-button']; // `fn` joins the block because the story's args call it, so the snippet compiles as pasted. expect(button?.import).toBe( "import { Button } from '@design-system/components/override';\nimport { fn } from 'storybook/test';" ); expect(button?.jsDocTags.import).toEqual([ "import { Button } from '@design-system/components/override';", ]); expect(button?.description).toBe('Primary UI component for user interaction'); expect(button?.summary).toBe('Fast summary'); expect(batchExtract).toHaveBeenCalled(); }); test('generator falls back to title-based matching when meta.component aliases a compound member', async () => { vol.fromJSON( { ['./package.json']: JSON.stringify({ name: 'some-package' }), ['./src/stories/Accordion.stories.tsx']: dedent` import type { Meta } from '@storybook/react'; import * as Accordion from './accordion'; const Root = Accordion.Root; const meta = { title: 'Example/Accordion', component: Root, } satisfies Meta; export default meta; export const Default = () => ; `, ['./src/stories/accordion.tsx']: dedent` import React from 'react'; type RootProps = { /** Allow multiple items open */ multiple?: boolean; }; const Root = ({ multiple = false }: RootProps) =>
; export const Accordion = { Root }; `, }, '/app' ); const batchExtract = vi .spyOn(ComponentMetaManager.prototype, 'batchExtract') .mockImplementation((entries) => { for (const entry of entries) { if (entry.component?.componentName === 'Accordion.Root') { entry.component.reactComponentMeta = { displayName: 'Accordion.Root', exportName: 'Root', filePath: '/app/src/stories/accordion.tsx', description: '', props: {}, }; } } }); const presets = { apply: async (extension: string, config?: unknown) => { if (extension === 'typescript') { return {}; } if (extension === 'features') { return { experimentalReactComponentMeta: true }; } return config; }, } as NonNullable; const manifestEntries = [ { type: 'story' as const, subtype: 'story' as const, id: 'example-accordion--default', name: 'Default', title: 'Example/Accordion', importPath: './src/stories/Accordion.stories.tsx', componentPath: './src/stories/accordion.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Default', }, ] satisfies ManifestEntries; const result = await runManifestsWithOptions(manifestEntries, { presets }); const accordion = result?.components?.components?.['example-accordion']; expect(accordion?.error).toBeUndefined(); expect(accordion?.name).toBe('Root'); expect(accordion?.import).toBe("import { Root } from 'some-package';"); expect(batchExtract).toHaveBeenCalled(); }); test('should create component manifest when only attached-mdx docs have manifest tag', async () => { // This test verifies that the React renderer creates a component manifest entry // when only an attached-mdx docs entry has the 'manifest' tag (and no story entries do). // Note: The `docs` property of the component manifest is added by addon-docs, not by this generator, // so it is not part of this test's snapshot. vol.fromJSON( { ['./package.json']: JSON.stringify({ name: 'some-package' }), ['./src/stories/Button.stories.ts']: dedent` import type { Meta, StoryObj } from '@storybook/react'; import { fn } from 'storybook/test'; import { Button } from './Button'; const meta = { title: 'Example/Button', component: Button, args: { onClick: fn() }, } satisfies Meta; export default meta; type Story = StoryObj; export const Primary: Story = { args: { primary: true, label: 'Button', tags: ['!manifest'] } }; `, ['./src/stories/Button.tsx']: dedent` import React from 'react'; export interface ButtonProps { /** Description of primary */ primary?: boolean; label: string; } /** Primary UI component for user interaction */ export const Button = ({ primary = false, label, }: ButtonProps) => { return ; }; `, }, '/app' ); // Only docs entry has manifest tag, story does not const manifestEntries = [ { type: 'docs' as const, id: 'example-button--docs', name: 'Docs', title: 'Example/Button', importPath: './src/stories/Button.mdx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST, Tag.ATTACHED_MDX], storiesImports: ['./src/stories/Button.stories.ts'], }, ] satisfies ManifestEntries; const result = await runManifests(manifestEntries); const { meta: _meta, ...components } = result?.components ?? {}; expect({ components }).toMatchInlineSnapshot(` { "components": { "components": { "example-button": { "description": "Primary UI component for user interaction", "error": undefined, "id": "example-button", "import": "import { Button } from 'some-package';", "jsDocTags": {}, "name": "Button", "path": "./src/stories/Button.stories.ts", "reactComponentMeta": undefined, "reactDocgen": { "actualName": "Button", "definedInFile": "./src/stories/Button.tsx", "description": "Primary UI component for user interaction", "displayName": "Button", "exportName": "Button", "methods": [], "props": { "label": { "description": "", "required": true, "tsType": { "name": "string", }, }, "primary": { "defaultValue": { "computed": false, "value": "false", }, "description": "Description of primary", "required": false, "tsType": { "name": "boolean", }, }, }, }, "reactDocgenTypescript": undefined, "stories": [], "summary": undefined, }, }, "v": 0, }, } `); }); test('should prefer story entries over attached-mdx docs entries for the same component id', async () => { vol.fromJSON( { ['./package.json']: JSON.stringify({ name: 'some-package' }), ['./src/Primary/Primary.stories.tsx']: dedent` import type { Meta } from '@storybook/react'; import { Primary } from './Primary'; const meta = { title: 'Example/Primary', component: Primary, } satisfies Meta; export default meta; export const Default = () => ; `, ['./src/Primary/Primary.tsx']: dedent` import React from 'react'; export interface PrimaryProps { title: string; } /** Primary component description */ export const Primary = ({ title }: PrimaryProps) =>
{title}
; `, ['./src/OtherFile/OtherFile.stories.tsx']: dedent` import type { Meta } from '@storybook/react'; import { OtherFile } from './OtherFile'; const meta = { title: 'Example/Other File', component: OtherFile, } satisfies Meta; export default meta; export const Default = () => ; `, ['./src/OtherFile/OtherFile.tsx']: dedent` import React from 'react'; export interface OtherFileProps { label: string; } /** Other file component description */ export const OtherFile = ({ label }: OtherFileProps) => ( ); `, }, '/app' ); const manifestEntries: ManifestEntries = [ { type: 'docs' as const, id: 'example-primary--docs', name: 'Docs', title: 'Example/Primary', importPath: './src/Primary/Primary.mdx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST, Tag.ATTACHED_MDX], storiesImports: [ './src/OtherFile/OtherFile.stories.tsx', './src/Primary/Primary.stories.tsx', ], }, { type: 'story' as const, subtype: 'story' as const, id: 'example-primary--default', name: 'Default', title: 'Example/Primary', importPath: './src/Primary/Primary.stories.tsx', componentPath: './src/Primary/Primary.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Default', }, ]; const result = await runManifests(manifestEntries); const component = result?.components?.components?.['example-primary']; expect(component?.name).toBe('Primary'); expect(component?.path).toBe('./src/Primary/Primary.stories.tsx'); expect(component?.stories).toEqual( expect.arrayContaining([ expect.objectContaining({ id: 'example-primary--default', name: 'Default', }), ]) ); expect( component?.stories.find((story) => story.id === 'example-primary--default')?.snippet ).toContain(' { vol.fromJSON( { ['./package.json']: JSON.stringify({ name: 'some-package' }), ['./src/stories/Card.stories.ts']: dedent` import type { Meta, StoryObj } from '@storybook/react'; import { Card } from './Card'; const meta: Meta = { component: Card, }; export default meta; type Story = StoryObj; export const Default: Story = { args: { label: 'Click me' } }; export const Large: Story = { args: { label: 'Big button', size: 'large' } }; `, ['./src/stories/Card.tsx']: dedent` import React from 'react'; /** A simple card component */ export const Card = ({ label, size }) => { return
{label}
; }; `, }, '/app' ); const manifestEntries: ManifestEntries = [ { type: 'story', subtype: 'story', id: 'card--default', name: 'Default', title: 'Card', importPath: './src/stories/Card.stories.ts', componentPath: './src/stories/Card.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Default', }, { type: 'story', subtype: 'story', id: 'card--large', name: 'Large', title: 'Card', importPath: './src/stories/Card.stories.ts', componentPath: './src/stories/Card.tsx', tags: [Tag.DEV, Tag.TEST, Tag.MANIFEST], exportName: 'Large', }, ]; const result = await runManifests(manifestEntries); const component = result?.components?.components?.['card']; // When no explicit title is in the meta, stories should still be populated // because the generator should use the index entry's title as fallback expect(component?.stories).toMatchInlineSnapshot(` [ { "description": undefined, "id": "card--default", "name": "Default", "snippet": "const Default = () => ;", "summary": undefined, }, { "description": undefined, "id": "card--large", "name": "Large", "snippet": "const Large = () => ;", "summary": undefined, }, ] `); }); test('should extract story description and summary from JSDoc comments', async () => { const code = withCSF3(dedent` /** * This is a longer description of the Primary story * * @summary This is a brief summary */ export const Primary = () =>