From 781baa8ce7dcf49455d0647327d733e4a69ed57b Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sun, 16 Aug 2026 17:26:21 +0200 Subject: [PATCH 01/22] Initial tests --- .../tests/integration/fixtureCapabilities.ts | 60 +++++++++++++++++++ .../tests/integration/integration-test.ts | 3 + 2 files changed, 63 insertions(+) create mode 100644 packages/react-docgen/tests/integration/fixtureCapabilities.ts diff --git a/packages/react-docgen/tests/integration/fixtureCapabilities.ts b/packages/react-docgen/tests/integration/fixtureCapabilities.ts new file mode 100644 index 00000000000..5712e86f90d --- /dev/null +++ b/packages/react-docgen/tests/integration/fixtureCapabilities.ts @@ -0,0 +1,60 @@ +export type FixtureCapability = + 'babel-specific' | 'common' | 'flow' | 'typescript'; + +export const fixtureCapabilities: Record = { + 'class-without-id.tsx': 'typescript', + 'component_1.js': 'common', + 'component_2.js': 'common', + 'component_3.js': 'common', + 'component_4.js': 'common', + 'component_5.js': 'common', + 'component_6.js': 'common', + 'component_7.js': 'common', + 'component_8.js': 'common', + 'component_9.js': 'common', + 'component_10.js': 'common', + 'component_11.js': 'flow', + 'component_12.js': 'flow', + 'component_13.js': 'flow', + 'component_14.js': 'flow', + 'component_15.js': 'flow', + 'component_16.js': 'common', + 'component_17.js': 'common', + 'component_18.js': 'flow', + 'component_19.js': 'flow', + 'component_20.js': 'common', + 'component_21.tsx': 'typescript', + 'component_22.tsx': 'typescript', + 'component_23.tsx': 'typescript', + 'component_24.js': 'flow', + 'component_25.tsx': 'typescript', + 'component_26.js': 'flow', + 'component_27.tsx': 'typescript', + 'component_28.tsx': 'typescript', + 'component_29.js': 'flow', + 'component_30.js': 'flow', + 'component_31.js': 'flow', + 'component_32.js': 'flow', + 'component_33.tsx': 'typescript', + 'component_34.js': 'common', + 'component_35.js': 'common', + 'component_36.js': 'common', + 'component_37.js': 'common', + 'component_38.js': 'common', + 'component_39.tsx': 'typescript', + 'component_40.js': 'common', + 'component_41.tsx': 'typescript', + 'component_42.js': 'common', + 'component_43.tsx': 'typescript', + 'flow-export-type.js': 'flow', + 'flow-import-type.js': 'flow', + 'flow-spread-import-type.js': 'flow', + 'namespace-export.tsx': 'typescript', + 'test-all-imports.tsx': 'typescript', +}; + +export function assertFixtureIsClassified(filename: string): void { + if (!(filename in fixtureCapabilities)) { + throw new Error(`Integration fixture "${filename}" has no capability.`); + } +} diff --git a/packages/react-docgen/tests/integration/integration-test.ts b/packages/react-docgen/tests/integration/integration-test.ts index 48d0ba83ded..ab9c7e5eb76 100644 --- a/packages/react-docgen/tests/integration/integration-test.ts +++ b/packages/react-docgen/tests/integration/integration-test.ts @@ -3,6 +3,7 @@ import { dirname, join } from 'path'; import { describe, expect, test } from 'vitest'; import { parse, makeFsImporter } from '../../src/main'; import { fileURLToPath } from 'url'; +import { assertFixtureIsClassified } from './fixtureCapabilities'; describe('integration', () => { describe('fixtures', () => { @@ -18,6 +19,8 @@ describe('integration', () => { } const name = entry.name; + assertFixtureIsClassified(name); + const filePath = join(fixturePath, name); const fileContent = fs.readFileSync(filePath, 'utf8'); From b84cd6883b041369ff48dcd26a572962bf6c199c Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sun, 16 Aug 2026 17:26:53 +0200 Subject: [PATCH 02/22] core --- packages/core/package.json | 19 ++++ packages/core/src/AstNode.ts | 14 +++ packages/core/src/AstPath.ts | 62 ++++++++++++ packages/core/src/ProjectContext.ts | 55 +++++++++++ packages/core/src/Scope.ts | 42 ++++++++ .../core/src/__tests__/ProjectContext-test.ts | 30 ++++++ packages/core/src/__tests__/Scope-test.ts | 29 ++++++ packages/core/src/__tests__/traverse-test.ts | 97 +++++++++++++++++++ packages/core/src/index.ts | 20 ++++ packages/core/src/traverse.ts | 84 ++++++++++++++++ packages/core/tsconfig.json | 10 ++ packages/core/vitest.config.ts | 13 +++ pnpm-lock.yaml | 2 + 13 files changed, 477 insertions(+) create mode 100644 packages/core/package.json create mode 100644 packages/core/src/AstNode.ts create mode 100644 packages/core/src/AstPath.ts create mode 100644 packages/core/src/ProjectContext.ts create mode 100644 packages/core/src/Scope.ts create mode 100644 packages/core/src/__tests__/ProjectContext-test.ts create mode 100644 packages/core/src/__tests__/Scope-test.ts create mode 100644 packages/core/src/__tests__/traverse-test.ts create mode 100644 packages/core/src/index.ts create mode 100644 packages/core/src/traverse.ts create mode 100644 packages/core/tsconfig.json create mode 100644 packages/core/vitest.config.ts diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 00000000000..03fd32f7016 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,19 @@ +{ + "name": "@react-docgen/core", + "version": "0.0.0", + "private": true, + "description": "Parser-neutral foundations for react-docgen.", + "type": "module", + "files": [ + "dist" + ], + "engines": { + "node": "^22.13.0 || >=24" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + } +} diff --git a/packages/core/src/AstNode.ts b/packages/core/src/AstNode.ts new file mode 100644 index 00000000000..fba2f93c8c6 --- /dev/null +++ b/packages/core/src/AstNode.ts @@ -0,0 +1,14 @@ +export interface AstNode { + readonly type: string; + readonly [key: string]: unknown; +} + +export type VisitorKeys = Readonly>; + +export function isAstNode(value: unknown): value is AstNode { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { type?: unknown }).type === 'string' + ); +} diff --git a/packages/core/src/AstPath.ts b/packages/core/src/AstPath.ts new file mode 100644 index 00000000000..7fced6272c5 --- /dev/null +++ b/packages/core/src/AstPath.ts @@ -0,0 +1,62 @@ +import { isAstNode, type AstNode } from './AstNode.js'; +import type Scope from './Scope.js'; + +interface AstPathOptions { + node: N; + parentPath?: AstPath; + key?: number | string; + listKey?: string; + scope?: Scope; +} + +export default class AstPath { + readonly node: N; + readonly parentPath: AstPath | null; + readonly key: number | string | null; + readonly listKey: string | null; + readonly scope: Scope | null; + + shouldSkip = false; + shouldStop = false; + + constructor({ node, parentPath, key, listKey, scope }: AstPathOptions) { + this.node = node; + this.parentPath = parentPath ?? null; + this.key = key ?? null; + this.listKey = listKey ?? null; + this.scope = scope ?? parentPath?.scope ?? null; + } + + get(name: string): AstPath | AstPath[] | null { + const value = this.node[name]; + + if (isAstNode(value)) { + return new AstPath({ node: value, parentPath: this, key: name }); + } + + if (Array.isArray(value)) { + return value.flatMap((node, index) => + isAstNode(node) + ? [ + new AstPath({ + node, + parentPath: this, + key: index, + listKey: name, + }), + ] + : [], + ); + } + + return null; + } + + skip(): void { + this.shouldSkip = true; + } + + stop(): void { + this.shouldStop = true; + } +} diff --git a/packages/core/src/ProjectContext.ts b/packages/core/src/ProjectContext.ts new file mode 100644 index 00000000000..9ccb39b95bf --- /dev/null +++ b/packages/core/src/ProjectContext.ts @@ -0,0 +1,55 @@ +import type { AstNode } from './AstNode.js'; + +export interface SourceFile { + readonly code: string; + readonly filename: string; +} + +export interface Parser { + parse(source: SourceFile): AstNode; +} + +export type ParserSelector = (filename: string) => Parser; +export type Importer = (specifier: string, fromFilename: string) => SourceFile; + +export class FileState { + readonly ast: AstNode; + readonly source: SourceFile; + + readonly #project: ProjectContext; + + constructor(project: ProjectContext, source: SourceFile, ast: AstNode) { + this.#project = project; + this.source = source; + this.ast = ast; + } + + import(specifier: string): FileState { + return this.#project.import(specifier, this.source.filename); + } +} + +interface ProjectContextOptions { + importer: Importer; + selectParser: ParserSelector; +} + +export default class ProjectContext { + readonly #importer: Importer; + readonly #selectParser: ParserSelector; + + constructor({ importer, selectParser }: ProjectContextOptions) { + this.#importer = importer; + this.#selectParser = selectParser; + } + + parse(source: SourceFile): FileState { + const ast = this.#selectParser(source.filename).parse(source); + + return new FileState(this, source, ast); + } + + import(specifier: string, fromFilename: string): FileState { + return this.parse(this.#importer(specifier, fromFilename)); + } +} diff --git a/packages/core/src/Scope.ts b/packages/core/src/Scope.ts new file mode 100644 index 00000000000..3d01f6d3f52 --- /dev/null +++ b/packages/core/src/Scope.ts @@ -0,0 +1,42 @@ +import type AstPath from './AstPath.js'; + +export type BindingKind = 'type' | 'value'; + +export interface Binding { + readonly kind: BindingKind; + readonly name: string; + readonly path: AstPath; +} + +export default class Scope { + readonly parent: Scope | null; + + readonly #bindings = { + type: new Map(), + value: new Map(), + }; + + constructor(parent?: Scope) { + this.parent = parent ?? null; + } + + declare(name: string, path: AstPath, kind: BindingKind = 'value'): Binding { + const binding = { kind, name, path }; + + this.#bindings[kind].set(name, binding); + + return binding; + } + + getOwnBinding(name: string, kind: BindingKind = 'value'): Binding | null { + return this.#bindings[kind].get(name) ?? null; + } + + getBinding(name: string, kind: BindingKind = 'value'): Binding | null { + return ( + this.getOwnBinding(name, kind) ?? + this.parent?.getBinding(name, kind) ?? + null + ); + } +} diff --git a/packages/core/src/__tests__/ProjectContext-test.ts b/packages/core/src/__tests__/ProjectContext-test.ts new file mode 100644 index 00000000000..77a8aa6f623 --- /dev/null +++ b/packages/core/src/__tests__/ProjectContext-test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test, vi } from 'vitest'; +import { ProjectContext, type Parser } from '../index.js'; + +describe('ProjectContext', () => { + test('selects a parser for every imported file', () => { + const typescript: Parser = { + parse: ({ filename }) => ({ type: 'TypeScriptFile', filename }), + }; + const hermes: Parser = { + parse: ({ filename }) => ({ type: 'HermesFile', filename }), + }; + const selectParser = vi.fn((filename: string) => + filename.endsWith('.tsx') ? typescript : hermes, + ); + const importer = vi.fn(() => ({ + code: 'export default function Button() {}', + filename: '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/project/Button.js', + })); + const project = new ProjectContext({ importer, selectParser }); + + const entry = project.parse({ code: '', filename: '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/project/App.tsx' }); + const imported = entry.import('./Button.js'); + + expect(entry.ast.type).toBe('TypeScriptFile'); + expect(imported.ast.type).toBe('HermesFile'); + expect(selectParser).toHaveBeenCalledWith('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/project/App.tsx'); + expect(selectParser).toHaveBeenCalledWith('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/project/Button.js'); + expect(importer).toHaveBeenCalledWith('./Button.js', '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/project/App.tsx'); + }); +}); diff --git a/packages/core/src/__tests__/Scope-test.ts b/packages/core/src/__tests__/Scope-test.ts new file mode 100644 index 00000000000..7a3c286e1bf --- /dev/null +++ b/packages/core/src/__tests__/Scope-test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from 'vitest'; +import { AstPath, Scope } from '../index.js'; + +const path = new AstPath({ node: { type: 'Identifier', name: 'Props' } }); + +describe('Scope', () => { + test('keeps value and type bindings separate', () => { + const scope = new Scope(); + const value = scope.declare('Props', path); + const type = scope.declare('Props', path, 'type'); + + expect(scope.getBinding('Props')).toBe(value); + expect(scope.getBinding('Props', 'type')).toBe(type); + expect(scope.getBinding('missing')).toBeNull(); + }); + + test('resolves and shadows parent bindings', () => { + const parent = new Scope(); + const child = new Scope(parent); + const parentBinding = parent.declare('Component', path); + + expect(child.getBinding('Component')).toBe(parentBinding); + + const childBinding = child.declare('Component', path); + + expect(child.getOwnBinding('Component')).toBe(childBinding); + expect(child.getBinding('Component')).toBe(childBinding); + }); +}); diff --git a/packages/core/src/__tests__/traverse-test.ts b/packages/core/src/__tests__/traverse-test.ts new file mode 100644 index 00000000000..d4f5f4ca7b4 --- /dev/null +++ b/packages/core/src/__tests__/traverse-test.ts @@ -0,0 +1,97 @@ +import { describe, expect, test } from 'vitest'; +import { AstPath, traverse, type AstNode, type VisitorKeys } from '../index.js'; + +const visitorKeys: VisitorKeys = { + Identifier: [], + Program: ['body'], + Wrapper: ['value'], +}; + +const ast: AstNode = { + type: 'Program', + body: [ + { type: 'Identifier', name: 'first' }, + { + type: 'Wrapper', + value: { type: 'Identifier', name: 'nested' }, + }, + { type: 'Identifier', name: 'last' }, + ], +}; + +describe('AstPath', () => { + test('addresses node and list children', () => { + const root = new AstPath({ node: ast }); + const body = root.get('body'); + + expect(body).toHaveLength(3); + expect((body as AstPath[])[0]).toMatchObject({ + key: 0, + listKey: 'body', + parentPath: root, + }); + expect((body as AstPath[])[1]?.get('value')).toMatchObject({ + key: 'value', + listKey: null, + parentPath: (body as AstPath[])[1], + }); + expect(root.get('missing')).toBeNull(); + }); +}); + +describe('traverse', () => { + test('visits nodes in enter/exit order', () => { + const visited: string[] = []; + + traverse( + ast, + visitorKeys, + { + enter(path) { + visited.push(`enter:${path.node.type}`); + }, + exit(path) { + visited.push(`exit:${path.node.type}`); + }, + }, + undefined, + ); + + expect(visited).toEqual([ + 'enter:Program', + 'enter:Identifier', + 'exit:Identifier', + 'enter:Wrapper', + 'enter:Identifier', + 'exit:Identifier', + 'exit:Wrapper', + 'enter:Identifier', + 'exit:Identifier', + 'exit:Program', + ]); + }); + + test('supports type visitors, skip, stop, and state', () => { + const names: string[] = []; + + traverse( + ast, + visitorKeys, + { + Identifier(path, state) { + state.push(path.node.name as string); + + if (path.node.name === 'last') { + path.stop(); + } + }, + Wrapper(path) { + path.skip(); + }, + }, + names, + ); + + expect(names).toEqual(['first', 'last']); + }); +}); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 00000000000..50452f8f49f --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,20 @@ +export { default as AstPath } from './AstPath.js'; +export { isAstNode } from './AstNode.js'; +export { FileState, default as ProjectContext } from './ProjectContext.js'; +export { default as Scope } from './Scope.js'; +export { default as traverse } from './traverse.js'; + +export type { AstNode, VisitorKeys } from './AstNode.js'; +export type { + Importer, + Parser, + ParserSelector, + SourceFile, +} from './ProjectContext.js'; +export type { Binding, BindingKind } from './Scope.js'; +export type { + Visit, + Visitor, + VisitorEntry, + VisitorHandler, +} from './traverse.js'; diff --git a/packages/core/src/traverse.ts b/packages/core/src/traverse.ts new file mode 100644 index 00000000000..10d3e246ef9 --- /dev/null +++ b/packages/core/src/traverse.ts @@ -0,0 +1,84 @@ +import AstPath from './AstPath.js'; +import type { AstNode, VisitorKeys } from './AstNode.js'; +import type Scope from './Scope.js'; + +export type Visit = (path: AstPath, state: State) => void; + +export interface VisitorHandler { + enter?: Visit; + exit?: Visit; +} + +export type VisitorEntry = Visit | VisitorHandler; + +export type Visitor = Record | undefined> & { + enter?: Visit; + exit?: Visit; +}; + +function callVisitor( + entry: VisitorEntry | undefined, + phase: keyof VisitorHandler, + path: AstPath, + state: State, +): void { + if (typeof entry === 'function') { + if (phase === 'enter') { + entry(path, state); + } + } else { + entry?.[phase]?.(path, state); + } +} + +export default function traverse( + node: AstNode, + visitorKeys: VisitorKeys, + visitor: Visitor, + state: State, + scope?: Scope, +): void { + let stopped = false; + + function visit(path: AstPath): void { + visitor.enter?.(path, state); + callVisitor(visitor[path.node.type], 'enter', path, state); + + if (path.shouldStop) { + stopped = true; + } + + if (stopped || path.shouldSkip) { + return; + } + + for (const name of visitorKeys[path.node.type] ?? []) { + const childPaths = path.get(name); + + if (Array.isArray(childPaths)) { + for (const childPath of childPaths) { + visit(childPath); + + if (stopped) { + return; + } + } + } else if (childPaths) { + visit(childPaths); + + if (stopped) { + return; + } + } + } + + callVisitor(visitor[path.node.type], 'exit', path, state); + visitor.exit?.(path, state); + + if (path.shouldStop) { + stopped = true; + } + } + + visit(new AstPath({ node, scope })); +} diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 00000000000..a1f3d920bb4 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "exclude": ["**/__tests__/**/*"], + "include": ["src/**/*"] +} diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts new file mode 100644 index 00000000000..af1231c7ceb --- /dev/null +++ b/packages/core/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'core', + include: ['**/__tests__/**/*-test.ts'], + coverage: { + include: ['src/**'], + provider: 'v8', + reporter: ['text', 'lcov'], + }, + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3e5e59c4f6d..902e7f0bdc4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -254,6 +254,8 @@ importers: specifier: npm:react-docgen@6.0.0 version: react-docgen@6.0.0(supports-color@7.2.0) + packages/core: {} + packages/react-docgen: dependencies: '@babel/core': From 8fbcbeebd17733c9e29916f7db83a1ec342f3de6 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sun, 16 Aug 2026 18:27:00 +0200 Subject: [PATCH 03/22] add core and typescript --- PLAN.md | 200 ++++++++++++++++++ packages/core/package.json | 13 +- packages/core/src/AstNode.ts | 2 +- packages/core/src/ProjectContext.ts | 24 ++- .../core/src/__tests__/ProjectContext-test.ts | 2 + packages/core/src/extract.ts | 52 +++++ packages/core/src/guards.ts | 61 ++++++ packages/core/src/index.ts | 11 + packages/core/src/nodes.ts | 93 ++++++++ packages/typescript/package.json | 33 +++ .../src/__fixtures__/function-component.tsx | 11 + .../typescript/src/__tests__/parse-test.ts | 107 ++++++++++ .../src/extractFunctionComponent.ts | 194 +++++++++++++++++ packages/typescript/src/index.ts | 28 +++ packages/typescript/src/normalize.ts | 29 +++ packages/typescript/src/parser.ts | 23 ++ packages/typescript/tsconfig.json | 10 + packages/typescript/vitest.config.ts | 13 ++ pnpm-lock.yaml | 12 ++ 19 files changed, 912 insertions(+), 6 deletions(-) create mode 100644 PLAN.md create mode 100644 packages/core/src/extract.ts create mode 100644 packages/core/src/guards.ts create mode 100644 packages/core/src/nodes.ts create mode 100644 packages/typescript/package.json create mode 100644 packages/typescript/src/__fixtures__/function-component.tsx create mode 100644 packages/typescript/src/__tests__/parse-test.ts create mode 100644 packages/typescript/src/extractFunctionComponent.ts create mode 100644 packages/typescript/src/index.ts create mode 100644 packages/typescript/src/normalize.ts create mode 100644 packages/typescript/src/parser.ts create mode 100644 packages/typescript/tsconfig.json create mode 100644 packages/typescript/vitest.config.ts diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 00000000000..371697a288c --- /dev/null +++ b/PLAN.md @@ -0,0 +1,200 @@ +# Parser-Neutral react-docgen Roadmap + +## Status + +- Current milestone: 3 — JavaScript and TypeScript parity +- Overall status: in progress +- Last updated: 2026-08-16 + +## Decisions + +1. `@react-docgen/core` will not depend on Babel, Hermes, or TypeScript. +2. The core will own the smallest path, traversal, and scope implementation + needed by react-docgen. +3. Parser adapters will normalize their ASTs into an ESTree-inspired internal + representation. +4. TypeScript will be the first production adapter. Hermes and Flow will follow. +5. Parser selection will happen per file, including imported files. +6. The next `react-docgen` major will be a parser-neutral facade with no default + parser. +7. Babel-shaped extension APIs may break in that major. `react-docgen@8` remains + the legacy line during migration. +8. Documentation output, not raw AST equality, is the compatibility contract. + +## Target packages + +- `@react-docgen/core`: normalized AST, paths, traversal, scopes, extraction, + and parser routing. +- `@react-docgen/typescript`: `typescript-estree` adapter and preconfigured + `parse()`. +- `@react-docgen/hermes`: Hermes adapter and preconfigured `parse()`. +- `@react-docgen/babel`: optional compatibility adapter and differential-test + reference. +- `react-docgen@8`: maintained legacy Babel implementation. +- Next `react-docgen` major: facade over `@react-docgen/core` composition APIs. + +## Milestone 0 — Stabilize and specify + +- [x] Keep the existing package build and test suite green while experimental + work proceeds separately. +- [x] Record architecture and package decisions in this plan. +- [x] Classify fixtures as `common`, `typescript`, `flow`, or `babel-specific`. +- [x] Reuse the existing integration snapshot harness as parser-independent + golden output. +- [x] Use the current Babel integration snapshots as the migration reference. + +Exit criteria: existing build and tests pass; fixtures have explicit +capabilities and stable expected documentation output. + +## Milestone 1 — Core foundation + +- [x] Add `@react-docgen/core` without a parser dependency. +- [x] Define the parser-neutral base node; add concrete normalized nodes only + with their first TypeScript caller. +- [x] Implement `AstPath`, visitor keys, traversal controls, and minimal + value/type scope services. +- [x] Add the parser-neutral `Parser`, `FileState`, `ProjectContext`, and + `Importer` contracts needed for import routing. +- [x] Route imported files back through `ProjectContext` so each file can select + its parser. + +Exit criteria: focused synthetic tests cover paths, traversal, scopes, bindings, +and import routing. + +## Milestone 2 — TypeScript vertical slice + +- [x] Add `@react-docgen/typescript` using + `@typescript-eslint/typescript-estree`. +- [x] Normalize JS, JSX, TS, TSX, imports, exports, and required TypeScript type + nodes. +- [x] Add parser-neutral `Handler` and `Resolver` contracts with their first + callers. +- [x] Support one complete exported function-component flow: props, + descriptions, defaults, and documentation output. +- [x] Export both a composable `parser` and a preconfigured `parse()`. + +Exit criteria: selected common and TypeScript fixtures match legacy output; +production dependencies contain no Babel package. Scoped `0.x` packages are +ready for an explicitly requested release. + +## Milestone 3 — JavaScript and TypeScript parity + +- [ ] Port resolvers, imports, value resolution, PropTypes, defaults, classes, + methods, docblocks, and TypeScript type extraction. +- [ ] Add normalized Babel adapter for differential testing. +- [ ] Define public neutral extension APIs and compile-test custom handlers, + resolvers, and importers. + +Exit criteria: all applicable `common` and `typescript` fixtures match legacy +output; no Babel types leak from new APIs. + +## Milestone 4 — Hermes and Flow + +- [ ] Add `@react-docgen/hermes` and normalize Hermes ESTree and Flow nodes. +- [ ] Port Flow extraction and component patterns. +- [ ] Run common fixtures through TypeScript, Hermes, and Babel adapters. +- [ ] Report unsupported syntax as explicit parser capability errors. + +Exit criteria: common JS/JSX output agrees across adapters and Flow output +matches the legacy implementation. + +## Milestone 5 — Mixed-parser projects + +- [ ] Add ordered `createParserRouter()` rules using filename, glob, or a custom + selector. +- [ ] Require filenames when multiple parsers are configured. +- [ ] Route every imported file independently. +- [ ] Support parser-specific options per route and explicit no-match errors. +- [ ] Add CLI config for single-parser and mixed-parser projects. + +Exit criteria: TypeScript and Hermes files can import each other while +preserving exports, bindings, descriptions, and props. + +## Milestone 6 — Stable release and migration + +- [ ] Stabilize scoped packages after parity and extension API validation. +- [ ] Release the next `react-docgen` major as a parser-neutral facade with no + implicit `parse()` backend. +- [ ] Remove Babel-specific extension contracts from the new major. +- [ ] Publish migration guide, README guidance, release notes, and CLI + documentation. +- [ ] Keep `react-docgen@8` available for legacy Babel behavior. + +Exit criteria: users must explicitly install/select a parser, and every legacy +public extension point has a documented replacement. + +## Public API direction + +```ts +import { createDocgen, createParserRouter } from '@react-docgen/core'; +import { parser as typescript } from '@react-docgen/typescript'; +import { parser as hermes } from '@react-docgen/hermes'; + +const parser = createParserRouter([ + { test: /\.(?:ts|tsx|mts|cts)$/, parser: typescript }, + { test: /\.(?:js|jsx|mjs|cjs)$/, parser: hermes }, +]); + +const docgen = createDocgen({ parser }); +``` + +Convenience packages will also expose preconfigured APIs: + +```ts +import { parse } from '@react-docgen/typescript'; +``` + +## Test policy + +- Core tests use synthetic normalized ASTs and load no parser. +- Every adapter runs shared conformance tests for comments, visitor keys, paths, + scopes, imports, locations, and errors. +- Golden documentation fixtures define compatibility. +- Differential tests compare applicable fixtures across legacy Babel, normalized + Babel, TypeScript, and Hermes. +- Raw AST equality is never required. + +## Plan change log + +Record every material plan change here before or with implementation. + +### 2026-08-16 — Initial roadmap + +- Added parser-neutral package architecture and six delivery milestones. +- Chose TypeScript as first adapter to validate the smallest useful vertical + slice before adding Hermes. +- Chose an owned minimal path/traversal/scope layer because react-docgen needs + only a subset of general AST tooling and has custom type-binding behavior. +- Chose a breaking parser-neutral `react-docgen` major so new APIs do not + preserve Babel types indefinitely. +- Deferred detailed normalized node schemas, router fallback rules, and parser + capability matrices until a real milestone needs them; defining them now would + be speculative. + +### 2026-08-16 — Reused existing golden harness + +- Replaced planned new golden-output infrastructure with the existing + integration snapshot suite. +- Added explicit fixture capability metadata and a guard that fails when a new + fixture is not classified. +- Reason: existing snapshots already capture the compatibility contract; a + second harness would duplicate behavior and maintenance. + +### 2026-08-16 — Deferred caller-shaped contracts + +- Moved concrete normalized node fields and `Handler`/`Resolver` contracts from + the core-foundation milestone to their first TypeScript vertical-slice + callers. +- Kept only the generic node, path, traversal, scope, parser, file, project, and + importer mechanics in Milestone 1. +- Reason: defining adapter and extraction shapes before a real caller would + create speculative API surface. + +### 2026-08-16 — Separated implementation from publication + +- Changed the Milestone 2 exit criterion from publishing experimental packages + to making them publish-ready. +- Added public package metadata while leaving the actual npm release as a + separate explicit action. +- Reason: publishing is an external, irreversible release decision and is not + implied by implementing the milestone. diff --git a/packages/core/package.json b/packages/core/package.json index 03fd32f7016..69379c765b2 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,8 +1,16 @@ { "name": "@react-docgen/core", "version": "0.0.0", - "private": true, "description": "Parser-neutral foundations for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/core" + }, "type": "module", "files": [ "dist" @@ -15,5 +23,6 @@ "scripts": { "build": "rimraf dist/ && tsc", "test": "vitest run" - } + }, + "license": "MIT" } diff --git a/packages/core/src/AstNode.ts b/packages/core/src/AstNode.ts index fba2f93c8c6..1bb1d965d42 100644 --- a/packages/core/src/AstNode.ts +++ b/packages/core/src/AstNode.ts @@ -3,7 +3,7 @@ export interface AstNode { readonly [key: string]: unknown; } -export type VisitorKeys = Readonly>; +export type VisitorKeys = Readonly>>; export function isAstNode(value: unknown): value is AstNode { return ( diff --git a/packages/core/src/ProjectContext.ts b/packages/core/src/ProjectContext.ts index 9ccb39b95bf..6b674c868f8 100644 --- a/packages/core/src/ProjectContext.ts +++ b/packages/core/src/ProjectContext.ts @@ -1,4 +1,7 @@ import type { AstNode } from './AstNode.js'; +import AstPath from './AstPath.js'; +import type { VisitorKeys } from './AstNode.js'; +import traverse, { type Visitor } from './traverse.js'; export interface SourceFile { readonly code: string; @@ -6,6 +9,7 @@ export interface SourceFile { } export interface Parser { + readonly visitorKeys: VisitorKeys; parse(source: SourceFile): AstNode; } @@ -14,19 +18,32 @@ export type Importer = (specifier: string, fromFilename: string) => SourceFile; export class FileState { readonly ast: AstNode; + readonly path: AstPath; readonly source: SourceFile; + readonly visitorKeys: VisitorKeys; readonly #project: ProjectContext; - constructor(project: ProjectContext, source: SourceFile, ast: AstNode) { + constructor( + project: ProjectContext, + source: SourceFile, + ast: AstNode, + visitorKeys: VisitorKeys, + ) { this.#project = project; this.source = source; this.ast = ast; + this.path = new AstPath({ node: ast }); + this.visitorKeys = visitorKeys; } import(specifier: string): FileState { return this.#project.import(specifier, this.source.filename); } + + traverse(visitor: Visitor, state: State): void { + traverse(this.ast, this.visitorKeys, visitor, state); + } } interface ProjectContextOptions { @@ -44,9 +61,10 @@ export default class ProjectContext { } parse(source: SourceFile): FileState { - const ast = this.#selectParser(source.filename).parse(source); + const parser = this.#selectParser(source.filename); + const ast = parser.parse(source); - return new FileState(this, source, ast); + return new FileState(this, source, ast, parser.visitorKeys); } import(specifier: string, fromFilename: string): FileState { diff --git a/packages/core/src/__tests__/ProjectContext-test.ts b/packages/core/src/__tests__/ProjectContext-test.ts index 77a8aa6f623..14530d7123f 100644 --- a/packages/core/src/__tests__/ProjectContext-test.ts +++ b/packages/core/src/__tests__/ProjectContext-test.ts @@ -5,9 +5,11 @@ describe('ProjectContext', () => { test('selects a parser for every imported file', () => { const typescript: Parser = { parse: ({ filename }) => ({ type: 'TypeScriptFile', filename }), + visitorKeys: {}, }; const hermes: Parser = { parse: ({ filename }) => ({ type: 'HermesFile', filename }), + visitorKeys: {}, }; const selectParser = vi.fn((filename: string) => filename.endsWith('.tsx') ? typescript : hermes, diff --git a/packages/core/src/extract.ts b/packages/core/src/extract.ts new file mode 100644 index 00000000000..af44b4cdeec --- /dev/null +++ b/packages/core/src/extract.ts @@ -0,0 +1,52 @@ +import type AstPath from './AstPath.js'; +import type { FileState } from './ProjectContext.js'; + +export interface TypeDescriptor { + readonly name: string; +} + +export interface DefaultValueDescriptor { + readonly computed: boolean; + readonly value: string; +} + +export interface PropDescriptor { + defaultValue?: DefaultValueDescriptor; + description: string; + required: boolean; + tsType: TypeDescriptor; +} + +export interface ComponentDocumentation { + description: string; + displayName: string; + methods: unknown[]; + props?: Record; +} + +export type Resolver = (file: FileState) => AstPath[]; +export type Handler = ( + documentation: ComponentDocumentation, + path: AstPath, + file: FileState, +) => void; + +export default function extract( + file: FileState, + resolver: Resolver, + handlers: readonly Handler[], +): ComponentDocumentation[] { + return resolver(file).map((path) => { + const documentation: ComponentDocumentation = { + description: '', + displayName: '', + methods: [], + }; + + for (const handler of handlers) { + handler(documentation, path, file); + } + + return documentation; + }); +} diff --git a/packages/core/src/guards.ts b/packages/core/src/guards.ts new file mode 100644 index 00000000000..acc5e93fca6 --- /dev/null +++ b/packages/core/src/guards.ts @@ -0,0 +1,61 @@ +import type { AstNode } from './AstNode.js'; +import type { + AssignmentPattern, + ExportNamedDeclaration, + FunctionDeclaration, + Identifier, + Literal, + ObjectPattern, + Program, + Property, + TSBooleanKeyword, + TSPropertySignature, + TSStringKeyword, + TSTypeAliasDeclaration, + TSTypeAnnotation, + TSTypeLiteral, + TSTypeReference, +} from './nodes.js'; + +function isType(node: AstNode, type: T['type']): node is T { + return node.type === type; +} + +export const isAssignmentPattern = (node: AstNode): node is AssignmentPattern => + isType(node, 'AssignmentPattern'); +export const isExportNamedDeclaration = ( + node: AstNode, +): node is ExportNamedDeclaration => isType(node, 'ExportNamedDeclaration'); +export const isFunctionDeclaration = ( + node: AstNode, +): node is FunctionDeclaration => isType(node, 'FunctionDeclaration'); +export const isIdentifier = ( + node: AstNode, + options?: { name?: string }, +): node is Identifier => + isType(node, 'Identifier') && + (options?.name === undefined || node.name === options.name); +export const isLiteral = (node: AstNode): node is Literal => + isType(node, 'Literal'); +export const isObjectPattern = (node: AstNode): node is ObjectPattern => + isType(node, 'ObjectPattern'); +export const isProgram = (node: AstNode): node is Program => + isType(node, 'Program'); +export const isProperty = (node: AstNode): node is Property => + isType(node, 'Property'); +export const isTSBooleanKeyword = (node: AstNode): node is TSBooleanKeyword => + isType(node, 'TSBooleanKeyword'); +export const isTSPropertySignature = ( + node: AstNode, +): node is TSPropertySignature => isType(node, 'TSPropertySignature'); +export const isTSStringKeyword = (node: AstNode): node is TSStringKeyword => + isType(node, 'TSStringKeyword'); +export const isTSTypeAliasDeclaration = ( + node: AstNode, +): node is TSTypeAliasDeclaration => isType(node, 'TSTypeAliasDeclaration'); +export const isTSTypeAnnotation = (node: AstNode): node is TSTypeAnnotation => + isType(node, 'TSTypeAnnotation'); +export const isTSTypeLiteral = (node: AstNode): node is TSTypeLiteral => + isType(node, 'TSTypeLiteral'); +export const isTSTypeReference = (node: AstNode): node is TSTypeReference => + isType(node, 'TSTypeReference'); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 50452f8f49f..303c982254e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,10 +1,21 @@ export { default as AstPath } from './AstPath.js'; export { isAstNode } from './AstNode.js'; +export { default as extract } from './extract.js'; +export * from './guards.js'; export { FileState, default as ProjectContext } from './ProjectContext.js'; export { default as Scope } from './Scope.js'; export { default as traverse } from './traverse.js'; export type { AstNode, VisitorKeys } from './AstNode.js'; +export type { + ComponentDocumentation, + DefaultValueDescriptor, + Handler, + PropDescriptor, + Resolver, + TypeDescriptor, +} from './extract.js'; +export type * from './nodes.js'; export type { Importer, Parser, diff --git a/packages/core/src/nodes.ts b/packages/core/src/nodes.ts new file mode 100644 index 00000000000..a76f0bdaea4 --- /dev/null +++ b/packages/core/src/nodes.ts @@ -0,0 +1,93 @@ +import type { AstNode } from './AstNode.js'; + +export interface RangedNode extends AstNode { + readonly range: readonly [number, number]; +} + +export interface Identifier extends RangedNode { + readonly type: 'Identifier'; + readonly name: string; + readonly typeAnnotation?: TSTypeAnnotation; +} + +export interface Program extends RangedNode { + readonly type: 'Program'; + readonly body: AstNode[]; + readonly comments?: Comment[]; +} + +export interface Comment extends RangedNode { + readonly type: 'Block' | 'Line'; + readonly value: string; +} + +export interface ExportNamedDeclaration extends RangedNode { + readonly type: 'ExportNamedDeclaration'; + readonly declaration: AstNode | null; +} + +export interface FunctionDeclaration extends RangedNode { + readonly type: 'FunctionDeclaration'; + readonly id: Identifier | null; + readonly params: AstNode[]; +} + +export interface ObjectPattern extends RangedNode { + readonly type: 'ObjectPattern'; + readonly properties: AstNode[]; + readonly typeAnnotation?: TSTypeAnnotation; +} + +export interface Property extends RangedNode { + readonly type: 'Property'; + readonly key: AstNode; + readonly value: AstNode; +} + +export interface AssignmentPattern extends RangedNode { + readonly type: 'AssignmentPattern'; + readonly left: AstNode; + readonly right: AstNode; +} + +export interface Literal extends RangedNode { + readonly type: 'Literal'; + readonly raw?: string; + readonly value: boolean | number | string | null; +} + +export interface TSTypeAliasDeclaration extends RangedNode { + readonly type: 'TSTypeAliasDeclaration'; + readonly id: Identifier; + readonly typeAnnotation: AstNode; +} + +export interface TSTypeAnnotation extends RangedNode { + readonly type: 'TSTypeAnnotation'; + readonly typeAnnotation: AstNode; +} + +export interface TSTypeReference extends RangedNode { + readonly type: 'TSTypeReference'; + readonly typeName: AstNode; +} + +export interface TSTypeLiteral extends RangedNode { + readonly type: 'TSTypeLiteral'; + readonly members: AstNode[]; +} + +export interface TSPropertySignature extends RangedNode { + readonly type: 'TSPropertySignature'; + readonly key: AstNode; + readonly optional: boolean; + readonly typeAnnotation?: TSTypeAnnotation; +} + +export interface TSBooleanKeyword extends RangedNode { + readonly type: 'TSBooleanKeyword'; +} + +export interface TSStringKeyword extends RangedNode { + readonly type: 'TSStringKeyword'; +} diff --git a/packages/typescript/package.json b/packages/typescript/package.json new file mode 100644 index 00000000000..0bf216a7f95 --- /dev/null +++ b/packages/typescript/package.json @@ -0,0 +1,33 @@ +{ + "name": "@react-docgen/typescript", + "version": "0.0.0", + "description": "TypeScript parser adapter for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/typescript" + }, + "type": "module", + "files": [ + "dist" + ], + "engines": { + "node": "^22.13.0 || >=24" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + }, + "dependencies": { + "@react-docgen/core": "workspace:*", + "@typescript-eslint/typescript-estree": "8.67.0", + "@typescript-eslint/visitor-keys": "8.67.0" + }, + "license": "MIT" +} diff --git a/packages/typescript/src/__fixtures__/function-component.tsx b/packages/typescript/src/__fixtures__/function-component.tsx new file mode 100644 index 00000000000..c2f1897677b --- /dev/null +++ b/packages/typescript/src/__fixtures__/function-component.tsx @@ -0,0 +1,11 @@ +type Props = { + /** Text shown inside the button. */ + label: string; + /** Prevents interaction. */ + disabled?: boolean; +}; + +/** Renders a button. */ +export function Button({ label, disabled = false }: Props) { + return ; +} diff --git a/packages/typescript/src/__tests__/parse-test.ts b/packages/typescript/src/__tests__/parse-test.ts new file mode 100644 index 00000000000..5527603d81e --- /dev/null +++ b/packages/typescript/src/__tests__/parse-test.ts @@ -0,0 +1,107 @@ +import fs from 'fs'; +import { fileURLToPath } from 'url'; +import { describe, expect, test } from 'vitest'; +import { + isIdentifier, + isProgram, + traverse, + type AstNode, +} from '@react-docgen/core'; +import { parse, parser } from '../index.js'; + +const filename = fileURLToPath( + new URL('../__fixtures__/function-component.tsx', import.meta.url), +); +const source = fs.readFileSync(filename, 'utf8'); + +describe('@react-docgen/typescript', () => { + test.each([ + [ + 'input.js', + "import value from './value.js'; export const result = value;", + 'ImportDeclaration', + ], + ['input.jsx', 'export const View = () =>
;', 'JSXElement'], + [ + 'input.ts', + 'export type Props = { value: string };', + 'TSTypeAliasDeclaration', + ], + [ + 'input.tsx', + 'export function View(props: { value: string }) { return
{props.value}
; }', + 'TSPropertySignature', + ], + ])('normalizes and traverses %s', (testFilename, code, expectedType) => { + const ast = parser.parse({ code, filename: testFilename }); + const nodeTypes: string[] = []; + + traverse( + ast, + parser.visitorKeys, + { + enter(path, state) { + state.push(path.node.type); + }, + }, + nodeTypes, + ); + + expect(isProgram(ast)).toBe(true); + expect(nodeTypes).toContain('ExportNamedDeclaration'); + expect(nodeTypes).toContain(expectedType); + }); + + test('normalizes parser nodes behind core guards', () => { + const ast = parser.parse({ + code: 'const answer = 42;', + filename: 'input.ts', + }); + const declaration = (ast.body as AstNode[])[0]; + const identifier = (declaration.declarations as AstNode[])[0] + ?.id as AstNode; + + expect(isIdentifier(identifier, { name: 'answer' })).toBe(true); + }); + + test('extracts an exported function component', () => { + expect(parse(source, { filename })).toEqual([ + { + description: 'Renders a button.', + displayName: 'Button', + methods: [], + props: { + disabled: { + defaultValue: { + computed: false, + value: 'false', + }, + description: 'Prevents interaction.', + required: false, + tsType: { name: 'boolean' }, + }, + label: { + description: 'Text shown inside the button.', + required: true, + tsType: { name: 'string' }, + }, + }, + }, + ]); + }); + + test('extracts a JavaScript function component', () => { + expect( + parse( + '/** Greets the user. */ export function Greeting() { return
; }', + { filename: 'component.jsx' }, + ), + ).toEqual([ + { + description: 'Greets the user.', + displayName: 'Greeting', + methods: [], + }, + ]); + }); +}); diff --git a/packages/typescript/src/extractFunctionComponent.ts b/packages/typescript/src/extractFunctionComponent.ts new file mode 100644 index 00000000000..d03ac0e384e --- /dev/null +++ b/packages/typescript/src/extractFunctionComponent.ts @@ -0,0 +1,194 @@ +import { + isAssignmentPattern, + isExportNamedDeclaration, + isFunctionDeclaration, + isIdentifier, + isLiteral, + isObjectPattern, + isProgram, + isProperty, + isTSBooleanKeyword, + isTSPropertySignature, + isTSStringKeyword, + isTSTypeAliasDeclaration, + isTSTypeAnnotation, + isTSTypeLiteral, + isTSTypeReference, + type AstNode, + type AstPath, + type Comment, + type FileState, + type Handler, + type ObjectPattern, + type Resolver, + type TSTypeLiteral, +} from '@react-docgen/core'; + +function getBody(file: FileState): AstPath[] { + const body = file.path.get('body'); + + return Array.isArray(body) ? body : []; +} + +export const resolver: Resolver = (file) => + getBody(file).flatMap((path) => { + if (!isExportNamedDeclaration(path.node) || !path.node.declaration) { + return []; + } + + const declaration = path.get('declaration'); + + return declaration && + !Array.isArray(declaration) && + isFunctionDeclaration(declaration.node) + ? [declaration] + : []; + }); + +function getDescription(file: FileState, node: AstNode): string { + if (!isProgram(file.ast) || !('range' in node)) { + return ''; + } + + const start = (node.range as readonly [number, number])[0]; + const comments = (file.ast.comments ?? []).filter( + (comment): comment is Comment => + comment.type === 'Block' && + comment.value.startsWith('*') && + comment.range[1] <= start && + /^[\s,;]*$/.test(file.source.code.slice(comment.range[1], start)), + ); + const comment = comments.at(-1); + + return comment + ? comment.value + .split('\n') + .map((line) => line.replace(/^\s*\* ?/, '')) + .join('\n') + .trim() + : ''; +} + +function getPropsType( + file: FileState, + parameter: AstNode, +): TSTypeLiteral | null { + const annotation = + (isIdentifier(parameter) || isObjectPattern(parameter)) && + parameter.typeAnnotation && + isTSTypeAnnotation(parameter.typeAnnotation) + ? parameter.typeAnnotation.typeAnnotation + : null; + + if (!annotation) { + return null; + } + + if (isTSTypeLiteral(annotation)) { + return annotation; + } + + if (!isTSTypeReference(annotation) || !isIdentifier(annotation.typeName)) { + return null; + } + + for (const path of getBody(file)) { + if ( + isTSTypeAliasDeclaration(path.node) && + path.node.id.name === annotation.typeName.name && + isTSTypeLiteral(path.node.typeAnnotation) + ) { + return path.node.typeAnnotation; + } + } + + return null; +} + +function getDefaults(pattern: ObjectPattern | null): Map { + const defaults = new Map(); + + for (const property of pattern?.properties ?? []) { + if ( + isProperty(property) && + isIdentifier(property.key) && + isAssignmentPattern(property.value) + ) { + defaults.set(property.key.name, property.value.right); + } + } + + return defaults; +} + +function getTypeName(node: AstNode | undefined): string | null { + if (!node || !isTSTypeAnnotation(node)) { + return null; + } + + if (isTSStringKeyword(node.typeAnnotation)) { + return 'string'; + } + + if (isTSBooleanKeyword(node.typeAnnotation)) { + return 'boolean'; + } + + return null; +} + +export const handler: Handler = (documentation, path, file) => { + if (!isFunctionDeclaration(path.node) || !path.node.id) { + return; + } + + const parameter = path.node.params[0]; + const propsType = parameter ? getPropsType(file, parameter) : null; + const pattern = parameter && isObjectPattern(parameter) ? parameter : null; + const defaults = getDefaults(pattern); + + documentation.displayName = path.node.id.name; + documentation.description = getDescription( + file, + path.parentPath?.node ?? path.node, + ); + + if (!propsType) { + return; + } + + documentation.props = {}; + + for (const member of propsType.members) { + if (!isTSPropertySignature(member) || !isIdentifier(member.key)) { + continue; + } + + const typeName = getTypeName(member.typeAnnotation); + + if (!typeName) { + continue; + } + + const defaultNode = defaults.get(member.key.name); + + documentation.props[member.key.name] = { + description: getDescription(file, member), + required: !member.optional, + tsType: { name: typeName }, + ...(defaultNode && isLiteral(defaultNode) + ? { + defaultValue: { + computed: false, + value: + defaultNode.raw ?? + file.source.code.slice( + defaultNode.range[0], + defaultNode.range[1], + ), + }, + } + : {}), + }; + } +}; diff --git a/packages/typescript/src/index.ts b/packages/typescript/src/index.ts new file mode 100644 index 00000000000..ab41d1a0e60 --- /dev/null +++ b/packages/typescript/src/index.ts @@ -0,0 +1,28 @@ +import { + extract, + ProjectContext, + type ComponentDocumentation, +} from '@react-docgen/core'; +import { handler, resolver } from './extractFunctionComponent.js'; +import parser from './parser.js'; + +export { default as parser, visitorKeys } from './parser.js'; + +export interface ParseOptions { + filename?: string; +} + +export function parse( + code: string, + { filename = 'component.tsx' }: ParseOptions = {}, +): ComponentDocumentation[] { + const project = new ProjectContext({ + importer() { + throw new Error('Imports are not supported by this vertical slice.'); + }, + selectParser: () => parser, + }); + const file = project.parse({ code, filename }); + + return extract(file, resolver, [handler]); +} diff --git a/packages/typescript/src/normalize.ts b/packages/typescript/src/normalize.ts new file mode 100644 index 00000000000..bdb638d4615 --- /dev/null +++ b/packages/typescript/src/normalize.ts @@ -0,0 +1,29 @@ +import { isAstNode, type AstNode } from '@react-docgen/core'; + +function normalizeValue(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(normalizeValue); + } + + if (typeof value !== 'object' || value === null) { + return value; + } + + const normalized: Record = {}; + + for (const [key, child] of Object.entries(value)) { + normalized[key] = normalizeValue(child); + } + + return normalized; +} + +export default function normalize(node: unknown): AstNode { + const normalized = normalizeValue(node); + + if (!isAstNode(normalized)) { + throw new TypeError('Parser did not return an AST node.'); + } + + return normalized; +} diff --git a/packages/typescript/src/parser.ts b/packages/typescript/src/parser.ts new file mode 100644 index 00000000000..2e5deb207f8 --- /dev/null +++ b/packages/typescript/src/parser.ts @@ -0,0 +1,23 @@ +import { parse } from '@typescript-eslint/typescript-estree'; +import { visitorKeys as typescriptVisitorKeys } from '@typescript-eslint/visitor-keys'; +import type { Parser, VisitorKeys } from '@react-docgen/core'; +import normalize from './normalize.js'; + +export const visitorKeys: VisitorKeys = typescriptVisitorKeys; + +const parser: Parser = { + parse(source) { + return normalize( + parse(source.code, { + comment: true, + filePath: source.filename, + jsx: true, + loc: true, + range: true, + }), + ); + }, + visitorKeys, +}; + +export default parser; diff --git a/packages/typescript/tsconfig.json b/packages/typescript/tsconfig.json new file mode 100644 index 00000000000..e9f14970c69 --- /dev/null +++ b/packages/typescript/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "exclude": ["**/__tests__/**/*", "**/__fixtures__/**/*"], + "include": ["src/**/*"] +} diff --git a/packages/typescript/vitest.config.ts b/packages/typescript/vitest.config.ts new file mode 100644 index 00000000000..9bdaf160de2 --- /dev/null +++ b/packages/typescript/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'typescript', + include: ['**/__tests__/**/*-test.ts'], + coverage: { + include: ['src/**'], + provider: 'v8', + reporter: ['text', 'lcov'], + }, + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 902e7f0bdc4..2865e771be3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -308,6 +308,18 @@ importers: specifier: 4.1.13 version: 4.1.13 + packages/typescript: + dependencies: + '@react-docgen/core': + specifier: workspace:* + version: link:../core + '@typescript-eslint/typescript-estree': + specifier: 8.67.0 + version: 8.67.0(supports-color@7.2.0)(typescript@6.0.3) + '@typescript-eslint/visitor-keys': + specifier: 8.67.0 + version: 8.67.0 + packages/website: dependencies: '@codemirror/lang-javascript': From 3cba93518c6ccc6563d26dbc056801573bf64d45 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sun, 16 Aug 2026 19:40:16 +0200 Subject: [PATCH 04/22] Better portable integration tests # Conflicts: # packages/react-docgen/vitest.config.ts --- .github/workflows/build.yml | 4 +- PLAN.md | 69 + eslint.config.mjs | 3 +- {benchmark => packages/benchmark}/index.mjs | 2 +- .../benchmark}/package.json | 0 packages/integration-tests/AUDIT.md | 128 + .../defaults/forward-ref-proptypes/index.js} | 0 .../forward-ref-proptypes/output.json | 31 + .../forward-ref-display-name/index.js} | 0 .../forward-ref-display-name/output.json | 17 + .../flow/definitions/pure-component/index.js} | 0 .../definitions/pure-component/output.json | 22 + .../flow/exports/exported-type/index.js} | 0 .../flow/exports/exported-type/output.json | 55 + .../imports/imported-type/flow-export-type.js | 26 + .../flow/imports/imported-type/index.js} | 0 .../flow/imports/imported-type/output.json | 16 + .../spread-imported-type/flow-export-type.js | 26 + .../spread-imported-type/flow-import-type.js | 18 + .../imports/spread-imported-type/index.js} | 0 .../imports/spread-imported-type/output.json | 23 + .../flow/methods/generic-class/index.js} | 0 .../flow/methods/generic-class/output.json | 58 + .../regressions/material-ui-paper/index.js} | 0 .../regressions/material-ui-paper/output.json | 180 ++ .../cases/flow/types/advanced-props/index.js | 38 + .../flow/types/advanced-props/output.json | 311 +++ .../flow/types/comprehensive-props/index.js | 22 + .../types/comprehensive-props/output.json | 154 ++ .../flow/types/concrete-identity/index.js} | 0 .../flow/types/concrete-identity/output.json | 16 + .../flow/types/generic-identity/index.js} | 0 .../flow/types/generic-identity/output.json | 16 + .../generic-interface-extension/index.js} | 0 .../generic-interface-extension/output.json | 36 + .../types/interface-composition/index.js} | 0 .../types/interface-composition/output.json | 66 + .../types/intersection-composition/index.js} | 0 .../intersection-composition/output.json | 33 + .../types/nested-generic-identity/index.js} | 0 .../types/nested-generic-identity/output.json | 16 + .../flow/types/react-and-dom-types/index.js} | 0 .../types/react-and-dom-types/output.json | 254 ++ .../flow/types/spread-composition/index.js} | 0 .../flow/types/spread-composition/output.json | 62 + .../js/defaults/computed-property/index.js} | 0 .../js/defaults/computed-property/output.json | 20 + .../defaults/destructured-bindings/index.jsx | 24 + .../destructured-bindings/output.json | 31 + .../defaults/function-default-props/index.js} | 0 .../function-default-props/output.json | 21 + .../js/defaults/memo-forward-ref/index.js} | 0 .../js/defaults/memo-forward-ref/output.json | 15 + .../defaults/spreads-and-parameters/index.jsx | 20 + .../spreads-and-parameters/output.json | 42 + .../js/defaults/unresolved-enum/index.js} | 0 .../js/defaults/unresolved-enum/output.json | 22 + .../js/defaults/value-serialization/index.jsx | 37 + .../defaults/value-serialization/output.json | 131 + .../definitions/annotated-function/index.jsx | 4 + .../annotated-function/output.json | 7 + .../index.jsx | 17 + .../output.json | 15 + .../index.jsx | 17 + .../output.json | 20 + .../configured-nested-hoc/index.jsx | 18 + .../configured-nested-hoc/output.json | 16 + .../custom-base-class-render/index.js} | 0 .../custom-base-class-render/output.json | 7 + .../display-name-resolution/index.jsx | 14 + .../display-name-resolution/output.json | 18 + .../function-declaration/index.jsx | 4 + .../function-declaration/output.json | 7 + .../hoc-wrapped-component/index.js} | 0 .../hoc-wrapped-component/output.json | 16 + .../numeric-display-name/index.jsx | 5 + .../numeric-display-name/output.json | 7 + .../react-create-class-assignment/index.js} | 0 .../react-create-class-assignment/output.json | 7 + .../react-create-class-variable/index.js} | 0 .../react-create-class-variable/output.json | 7 + .../js/errors/missing-definition/error.json | 3 + .../js/errors/missing-definition/index.jsx | 1 + .../js/errors/multiple-definitions/error.json | 3 + .../js/errors/multiple-definitions/index.jsx | 7 + .../js/exports/commonjs-module/index.jsx | 11 + .../js/exports/commonjs-module/output.json | 16 + .../cases/js/exports/commonjs-named/index.jsx | 9 + .../js/exports/commonjs-named/output.json | 7 + .../js/exports/computed-commonjs/error.json | 3 + .../js/exports/computed-commonjs/index.jsx | 7 + .../export-star-chain}/component_34.js | 0 .../export-star-chain}/component_35.js | 0 .../export-star-chain}/component_36.js | 0 .../imports/export-star-chain}/component_6.js | 0 .../js/imports/export-star-chain/index.js | 9 + .../js/imports/export-star-chain/output.json | 30 + .../imported-defaults-and-enums/index.jsx | 17 + .../imported-defaults-and-enums/output.json | 52 + .../imported-defaults-and-enums/values.js | 9 + .../imports/member-proptypes/component_34.js | 13 + .../imports/member-proptypes/component_35.js | 10 + .../imports/member-proptypes/component_36.js | 9 + .../imports/member-proptypes}/component_37.js | 0 .../imports/member-proptypes/component_6.js | 26 + .../js/imports/member-proptypes/index.js} | 0 .../js/imports/member-proptypes/output.json | 30 + .../namespace-reexport/component_34.js | 13 + .../namespace-reexport/component_35.js | 10 + .../namespace-reexport/component_36.js | 9 + .../imports/namespace-reexport/component_6.js | 26 + .../js/imports/namespace-reexport/index.js | 9 + .../js/imports/namespace-reexport/output.json | 30 + .../reexported-proptypes/component_34.js | 13 + .../reexported-proptypes/component_35.js | 10 + .../reexported-proptypes/component_36.js | 9 + .../reexported-proptypes/component_6.js | 26 + .../js/imports/reexported-proptypes/index.js | 10 + .../imports/reexported-proptypes/output.json | 30 + .../imports/spread-proptypes/component_6.js | 26 + .../js/imports/spread-proptypes/index.js | 13 + .../js/imports/spread-proptypes/output.json | 37 + .../class-method-documentation/index.js} | 0 .../class-method-documentation/output.json | 46 + .../cases/js/methods/class-methods/index.js} | 0 .../js/methods/class-methods/output.json | 21 + .../js/methods/imperative-handle/index.jsx | 12 + .../js/methods/imperative-handle/output.json | 24 + .../cases/js/methods/jsdoc-variants/index.jsx | 38 + .../js/methods/jsdoc-variants/output.json | 111 + .../js/methods/parameter-shapes/index.jsx | 20 + .../js/methods/parameter-shapes/output.json | 42 + .../cases/js/props/all-proptypes/index.jsx | 24 + .../cases/js/props/all-proptypes/output.json | 144 ++ .../composed-and-custom-validators/index.jsx | 25 + .../output.json | 65 + .../js/props/literal-computed-keys/index.jsx | 13 + .../props/literal-computed-keys/output.json | 23 + .../props/nested-shape-inheritance/index.js} | 0 .../nested-shape-inheritance/output.json | 60 + .../object-key-and-value-enums/index.jsx | 22 + .../object-key-and-value-enums/output.json | 51 + .../props/package-proptypes-context/index.js | 26 + .../package-proptypes-context/output.json | 50 + .../props/react-proptypes-context/index.js} | 0 .../props/react-proptypes-context/output.json | 50 + .../js/props/shape-exact-and-union/index.js} | 0 .../props/shape-exact-and-union/output.json | 61 + .../class-static-getters/index.js} | 0 .../class-static-getters/output.json | 37 + .../forward-ref-parameter-default/index.tsx} | 0 .../forward-ref-parameter-default/output.json | 20 + .../function-default-parameters/index.tsx} | 0 .../function-default-parameters/output.json | 27 + .../anonymous-default-class/index.tsx} | 0 .../anonymous-default-class/output.json | 15 + .../exports/namespace-reexport/index.tsx} | 0 .../exports/namespace-reexport/output.json | 15 + .../support/other-exports.ts | 0 .../imports/extended-props}/component_27.tsx | 0 .../imports/extended-props}/component_39.tsx | 0 .../imports/extended-props/index.tsx} | 0 .../imports/extended-props/output.json | 23 + .../imports/imported-props/component_27.tsx | 35 + .../imports/imported-props/index.tsx | 13 + .../imports/imported-props/output.json | 16 + .../reexported-default-values/index.tsx} | 0 .../reexported-default-values/output.json | 23 + .../support/other-exports.ts | 1 + .../support/some-exports.ts | 0 .../methods/class-methods/index.tsx | 35 + .../methods/class-methods/output.json | 57 + .../methods/modifiers-and-types/index.tsx | 34 + .../methods/modifiers-and-types/output.json | 135 + .../polymorphic-forward-ref/index.tsx} | 0 .../polymorphic-forward-ref/output.json | 37 + .../typescript/types/advanced-props/index.tsx | 41 + .../types/advanced-props/output.json | 231 ++ .../types/comprehensive-props/index.tsx | 27 + .../types/comprehensive-props/output.json | 224 ++ .../generic-interface-extension/index.tsx} | 0 .../generic-interface-extension/output.json | 36 + .../types/indexed-access-constant/index.tsx} | 0 .../types/indexed-access-constant/output.json | 17 + .../types/interface-composition/index.tsx} | 0 .../types/interface-composition/output.json | 66 + .../types/nested-object-and-union/index.tsx} | 0 .../types/nested-object-and-union/output.json | 92 + .../types/react-prop-wrappers/index.tsx | 15 + .../types/react-prop-wrappers/output.json | 16 + .../types/type-alias-intersection/index.tsx} | 0 .../types/type-alias-intersection/output.json | 63 + packages/integration-tests/package.json | 23 + packages/integration-tests/src/index.ts | 146 ++ packages/integration-tests/tsconfig.json | 9 + packages/react-docgen/package.json | 3 + .../__snapshots__/integration-test.ts.snap | 2165 ----------------- .../tests/integration/fixtureCapabilities.ts | 60 - .../tests/integration/integration-test.ts | 55 +- packages/react-docgen/vitest.config.ts | 13 +- packages/typescript/package.json | 3 + .../typescript/src/__tests__/parse-test.ts | 50 +- .../tests/integration/integration-test.ts | 22 + packages/typescript/vitest.config.ts | 2 +- pnpm-lock.yaml | 12 +- pnpm-workspace.yaml | 1 - renovate.json | 6 +- 207 files changed, 5342 insertions(+), 2321 deletions(-) rename {benchmark => packages/benchmark}/index.mjs (97%) rename {benchmark => packages/benchmark}/package.json (100%) create mode 100644 packages/integration-tests/AUDIT.md rename packages/{react-docgen/tests/integration/__fixtures__/component_18.js => integration-tests/cases/flow/defaults/forward-ref-proptypes/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_14.js => integration-tests/cases/flow/definitions/forward-ref-display-name/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/definitions/forward-ref-display-name/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_19.js => integration-tests/cases/flow/definitions/pure-component/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/definitions/pure-component/output.json rename packages/{react-docgen/tests/integration/__fixtures__/flow-export-type.js => integration-tests/cases/flow/exports/exported-type/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/exports/exported-type/output.json create mode 100644 packages/integration-tests/cases/flow/imports/imported-type/flow-export-type.js rename packages/{react-docgen/tests/integration/__fixtures__/flow-import-type.js => integration-tests/cases/flow/imports/imported-type/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/imports/imported-type/output.json create mode 100644 packages/integration-tests/cases/flow/imports/spread-imported-type/flow-export-type.js create mode 100644 packages/integration-tests/cases/flow/imports/spread-imported-type/flow-import-type.js rename packages/{react-docgen/tests/integration/__fixtures__/flow-spread-import-type.js => integration-tests/cases/flow/imports/spread-imported-type/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/imports/spread-imported-type/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_32.js => integration-tests/cases/flow/methods/generic-class/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/methods/generic-class/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_12.js => integration-tests/cases/flow/regressions/material-ui-paper/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/regressions/material-ui-paper/output.json create mode 100644 packages/integration-tests/cases/flow/types/advanced-props/index.js create mode 100644 packages/integration-tests/cases/flow/types/advanced-props/output.json create mode 100644 packages/integration-tests/cases/flow/types/comprehensive-props/index.js create mode 100644 packages/integration-tests/cases/flow/types/comprehensive-props/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_30.js => integration-tests/cases/flow/types/concrete-identity/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/concrete-identity/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_29.js => integration-tests/cases/flow/types/generic-identity/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/generic-identity/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_26.js => integration-tests/cases/flow/types/generic-interface-extension/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/generic-interface-extension/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_24.js => integration-tests/cases/flow/types/interface-composition/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/interface-composition/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_11.js => integration-tests/cases/flow/types/intersection-composition/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/intersection-composition/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_31.js => integration-tests/cases/flow/types/nested-generic-identity/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/nested-generic-identity/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_13.js => integration-tests/cases/flow/types/react-and-dom-types/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/react-and-dom-types/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_15.js => integration-tests/cases/flow/types/spread-composition/index.js} (100%) create mode 100644 packages/integration-tests/cases/flow/types/spread-composition/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_20.js => integration-tests/cases/js/defaults/computed-property/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/defaults/computed-property/output.json create mode 100644 packages/integration-tests/cases/js/defaults/destructured-bindings/index.jsx create mode 100644 packages/integration-tests/cases/js/defaults/destructured-bindings/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_16.js => integration-tests/cases/js/defaults/function-default-props/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/defaults/function-default-props/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_42.js => integration-tests/cases/js/defaults/memo-forward-ref/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/defaults/memo-forward-ref/output.json create mode 100644 packages/integration-tests/cases/js/defaults/spreads-and-parameters/index.jsx create mode 100644 packages/integration-tests/cases/js/defaults/spreads-and-parameters/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_40.js => integration-tests/cases/js/defaults/unresolved-enum/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/defaults/unresolved-enum/output.json create mode 100644 packages/integration-tests/cases/js/defaults/value-serialization/index.jsx create mode 100644 packages/integration-tests/cases/js/defaults/value-serialization/output.json create mode 100644 packages/integration-tests/cases/js/definitions/annotated-function/index.jsx create mode 100644 packages/integration-tests/cases/js/definitions/annotated-function/output.json create mode 100644 packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/index.jsx create mode 100644 packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/output.json create mode 100644 packages/integration-tests/cases/js/definitions/class-expression-static-assignments/index.jsx create mode 100644 packages/integration-tests/cases/js/definitions/class-expression-static-assignments/output.json create mode 100644 packages/integration-tests/cases/js/definitions/configured-nested-hoc/index.jsx create mode 100644 packages/integration-tests/cases/js/definitions/configured-nested-hoc/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_9.js => integration-tests/cases/js/definitions/custom-base-class-render/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/definitions/custom-base-class-render/output.json create mode 100644 packages/integration-tests/cases/js/definitions/display-name-resolution/index.jsx create mode 100644 packages/integration-tests/cases/js/definitions/display-name-resolution/output.json create mode 100644 packages/integration-tests/cases/js/definitions/function-declaration/index.jsx create mode 100644 packages/integration-tests/cases/js/definitions/function-declaration/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_3.js => integration-tests/cases/js/definitions/hoc-wrapped-component/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/definitions/hoc-wrapped-component/output.json create mode 100644 packages/integration-tests/cases/js/definitions/numeric-display-name/index.jsx create mode 100644 packages/integration-tests/cases/js/definitions/numeric-display-name/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_1.js => integration-tests/cases/js/definitions/react-create-class-assignment/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/definitions/react-create-class-assignment/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_7.js => integration-tests/cases/js/definitions/react-create-class-variable/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/definitions/react-create-class-variable/output.json create mode 100644 packages/integration-tests/cases/js/errors/missing-definition/error.json create mode 100644 packages/integration-tests/cases/js/errors/missing-definition/index.jsx create mode 100644 packages/integration-tests/cases/js/errors/multiple-definitions/error.json create mode 100644 packages/integration-tests/cases/js/errors/multiple-definitions/index.jsx create mode 100644 packages/integration-tests/cases/js/exports/commonjs-module/index.jsx create mode 100644 packages/integration-tests/cases/js/exports/commonjs-module/output.json create mode 100644 packages/integration-tests/cases/js/exports/commonjs-named/index.jsx create mode 100644 packages/integration-tests/cases/js/exports/commonjs-named/output.json create mode 100644 packages/integration-tests/cases/js/exports/computed-commonjs/error.json create mode 100644 packages/integration-tests/cases/js/exports/computed-commonjs/index.jsx rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/js/imports/export-star-chain}/component_34.js (100%) rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/js/imports/export-star-chain}/component_35.js (100%) rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/js/imports/export-star-chain}/component_36.js (100%) rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/js/imports/export-star-chain}/component_6.js (100%) create mode 100644 packages/integration-tests/cases/js/imports/export-star-chain/index.js create mode 100644 packages/integration-tests/cases/js/imports/export-star-chain/output.json create mode 100644 packages/integration-tests/cases/js/imports/imported-defaults-and-enums/index.jsx create mode 100644 packages/integration-tests/cases/js/imports/imported-defaults-and-enums/output.json create mode 100644 packages/integration-tests/cases/js/imports/imported-defaults-and-enums/values.js create mode 100644 packages/integration-tests/cases/js/imports/member-proptypes/component_34.js create mode 100644 packages/integration-tests/cases/js/imports/member-proptypes/component_35.js create mode 100644 packages/integration-tests/cases/js/imports/member-proptypes/component_36.js rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/js/imports/member-proptypes}/component_37.js (100%) create mode 100644 packages/integration-tests/cases/js/imports/member-proptypes/component_6.js rename packages/{react-docgen/tests/integration/__fixtures__/component_38.js => integration-tests/cases/js/imports/member-proptypes/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/imports/member-proptypes/output.json create mode 100644 packages/integration-tests/cases/js/imports/namespace-reexport/component_34.js create mode 100644 packages/integration-tests/cases/js/imports/namespace-reexport/component_35.js create mode 100644 packages/integration-tests/cases/js/imports/namespace-reexport/component_36.js create mode 100644 packages/integration-tests/cases/js/imports/namespace-reexport/component_6.js create mode 100644 packages/integration-tests/cases/js/imports/namespace-reexport/index.js create mode 100644 packages/integration-tests/cases/js/imports/namespace-reexport/output.json create mode 100644 packages/integration-tests/cases/js/imports/reexported-proptypes/component_34.js create mode 100644 packages/integration-tests/cases/js/imports/reexported-proptypes/component_35.js create mode 100644 packages/integration-tests/cases/js/imports/reexported-proptypes/component_36.js create mode 100644 packages/integration-tests/cases/js/imports/reexported-proptypes/component_6.js create mode 100644 packages/integration-tests/cases/js/imports/reexported-proptypes/index.js create mode 100644 packages/integration-tests/cases/js/imports/reexported-proptypes/output.json create mode 100644 packages/integration-tests/cases/js/imports/spread-proptypes/component_6.js create mode 100644 packages/integration-tests/cases/js/imports/spread-proptypes/index.js create mode 100644 packages/integration-tests/cases/js/imports/spread-proptypes/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_10.js => integration-tests/cases/js/methods/class-method-documentation/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/methods/class-method-documentation/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_8.js => integration-tests/cases/js/methods/class-methods/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/methods/class-methods/output.json create mode 100644 packages/integration-tests/cases/js/methods/imperative-handle/index.jsx create mode 100644 packages/integration-tests/cases/js/methods/imperative-handle/output.json create mode 100644 packages/integration-tests/cases/js/methods/jsdoc-variants/index.jsx create mode 100644 packages/integration-tests/cases/js/methods/jsdoc-variants/output.json create mode 100644 packages/integration-tests/cases/js/methods/parameter-shapes/index.jsx create mode 100644 packages/integration-tests/cases/js/methods/parameter-shapes/output.json create mode 100644 packages/integration-tests/cases/js/props/all-proptypes/index.jsx create mode 100644 packages/integration-tests/cases/js/props/all-proptypes/output.json create mode 100644 packages/integration-tests/cases/js/props/composed-and-custom-validators/index.jsx create mode 100644 packages/integration-tests/cases/js/props/composed-and-custom-validators/output.json create mode 100644 packages/integration-tests/cases/js/props/literal-computed-keys/index.jsx create mode 100644 packages/integration-tests/cases/js/props/literal-computed-keys/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_4.js => integration-tests/cases/js/props/nested-shape-inheritance/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/props/nested-shape-inheritance/output.json create mode 100644 packages/integration-tests/cases/js/props/object-key-and-value-enums/index.jsx create mode 100644 packages/integration-tests/cases/js/props/object-key-and-value-enums/output.json create mode 100644 packages/integration-tests/cases/js/props/package-proptypes-context/index.js create mode 100644 packages/integration-tests/cases/js/props/package-proptypes-context/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_5.js => integration-tests/cases/js/props/react-proptypes-context/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/props/react-proptypes-context/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_17.js => integration-tests/cases/js/props/shape-exact-and-union/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/props/shape-exact-and-union/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_2.js => integration-tests/cases/js/regressions/class-static-getters/index.js} (100%) create mode 100644 packages/integration-tests/cases/js/regressions/class-static-getters/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_28.tsx => integration-tests/cases/typescript/defaults/forward-ref-parameter-default/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/output.json rename packages/{typescript/src/__fixtures__/function-component.tsx => integration-tests/cases/typescript/defaults/function-default-parameters/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/defaults/function-default-parameters/output.json rename packages/{react-docgen/tests/integration/__fixtures__/class-without-id.tsx => integration-tests/cases/typescript/definitions/anonymous-default-class/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/definitions/anonymous-default-class/output.json rename packages/{react-docgen/tests/integration/__fixtures__/namespace-export.tsx => integration-tests/cases/typescript/exports/namespace-reexport/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/exports/namespace-reexport/output.json rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/typescript/exports/namespace-reexport}/support/other-exports.ts (100%) rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/typescript/imports/extended-props}/component_27.tsx (100%) rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/typescript/imports/extended-props}/component_39.tsx (100%) rename packages/{react-docgen/tests/integration/__fixtures__/component_33.tsx => integration-tests/cases/typescript/imports/extended-props/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/imports/extended-props/output.json create mode 100644 packages/integration-tests/cases/typescript/imports/imported-props/component_27.tsx create mode 100644 packages/integration-tests/cases/typescript/imports/imported-props/index.tsx create mode 100644 packages/integration-tests/cases/typescript/imports/imported-props/output.json rename packages/{react-docgen/tests/integration/__fixtures__/test-all-imports.tsx => integration-tests/cases/typescript/imports/reexported-default-values/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/imports/reexported-default-values/output.json create mode 100644 packages/integration-tests/cases/typescript/imports/reexported-default-values/support/other-exports.ts rename packages/{react-docgen/tests/integration/__fixtures__ => integration-tests/cases/typescript/imports/reexported-default-values}/support/some-exports.ts (100%) create mode 100644 packages/integration-tests/cases/typescript/methods/class-methods/index.tsx create mode 100644 packages/integration-tests/cases/typescript/methods/class-methods/output.json create mode 100644 packages/integration-tests/cases/typescript/methods/modifiers-and-types/index.tsx create mode 100644 packages/integration-tests/cases/typescript/methods/modifiers-and-types/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_43.tsx => integration-tests/cases/typescript/regressions/polymorphic-forward-ref/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/output.json create mode 100644 packages/integration-tests/cases/typescript/types/advanced-props/index.tsx create mode 100644 packages/integration-tests/cases/typescript/types/advanced-props/output.json create mode 100644 packages/integration-tests/cases/typescript/types/comprehensive-props/index.tsx create mode 100644 packages/integration-tests/cases/typescript/types/comprehensive-props/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_25.tsx => integration-tests/cases/typescript/types/generic-interface-extension/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/types/generic-interface-extension/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_41.tsx => integration-tests/cases/typescript/types/indexed-access-constant/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/types/indexed-access-constant/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_23.tsx => integration-tests/cases/typescript/types/interface-composition/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/types/interface-composition/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_22.tsx => integration-tests/cases/typescript/types/nested-object-and-union/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/types/nested-object-and-union/output.json create mode 100644 packages/integration-tests/cases/typescript/types/react-prop-wrappers/index.tsx create mode 100644 packages/integration-tests/cases/typescript/types/react-prop-wrappers/output.json rename packages/{react-docgen/tests/integration/__fixtures__/component_21.tsx => integration-tests/cases/typescript/types/type-alias-intersection/index.tsx} (100%) create mode 100644 packages/integration-tests/cases/typescript/types/type-alias-intersection/output.json create mode 100644 packages/integration-tests/package.json create mode 100644 packages/integration-tests/src/index.ts create mode 100644 packages/integration-tests/tsconfig.json delete mode 100644 packages/react-docgen/tests/integration/__snapshots__/integration-test.ts.snap delete mode 100644 packages/react-docgen/tests/integration/fixtureCapabilities.ts create mode 100644 packages/typescript/tests/integration/integration-test.ts diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 620981446b8..3ed2aa99ca8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -43,11 +43,11 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Unit tests with coverage + - name: Tests with coverage if: "${{ matrix.node == env.NODE_VERSION }}" run: pnpm test -- --coverage - - name: Unit tests + - name: Tests if: "${{ matrix.node != env.NODE_VERSION }}" run: pnpm test diff --git a/PLAN.md b/PLAN.md index 371697a288c..ccbe9869599 100644 --- a/PLAN.md +++ b/PLAN.md @@ -88,6 +88,22 @@ ready for an explicitly requested release. Exit criteria: all applicable `common` and `typescript` fixtures match legacy output; no Babel types leak from new APIs. +## Sidestep — Portable integration fixture corpus + +- [x] Move legacy fixtures into a private parser-free workspace package. +- [x] Organize cases by language, behavior, and descriptive case ID. +- [x] Replace the monolithic snapshot with one JSON outcome per case. +- [x] Run all cases through legacy `react-docgen` and a temporary supported-case + allowlist through `@react-docgen/typescript`. +- [x] Map disabled unit-test behaviors to portable fixtures or narrow, evidenced exclusions. +- [x] Add coverage-driven fixtures without production changes or coverage hints. +- [x] Record the integration-only plateau and enforce its integer-floor coverage + thresholds. + +Exit criteria: migrated output remains unchanged; all public behavior represented +by disabled unit tests is covered or classified; legacy integration coverage +cannot silently regress. + ## Milestone 4 — Hermes and Flow - [ ] Add `@react-docgen/hermes` and normalize Hermes ESTree and Flow nodes. @@ -198,3 +214,56 @@ Record every material plan change here before or with implementation. separate explicit action. - Reason: publishing is an external, irreversible release decision and is not implied by implementing the milestone. + +### 2026-08-16 — Hardened portable integration corpus before Milestone 3 + +- Paused Milestone 3 to move 49 legacy fixtures and golden outputs into + `@react-docgen-internal/integration-tests`, grouped by language and behavior. +- Replaced parser capability metadata with language directories and added a + validating dependency-free loader. +- Added coverage-driven public behavior cases and a TypeScript adapter allowlist; + the legacy package remains the complete reference runner. +- Started disabled unit-test dispositions in the corpus audit and expanded + integration-only coverage from 71.33% to 79.28% statements. +- Reason: parser implementations need one portable observable-output contract; + unit tests tied to Babel paths cannot provide that contract. + +### 2026-08-16 — Reopened coverage expansion + +- Removed the initial 79/68/89/79 thresholds and withdrew the claimed behavioral + plateau. +- Kept 92% coverage from the complete unit-and-integration suite as the practical + reachability benchmark for the integration corpus. +- Reason: the earlier audit classified broad utility groups too aggressively; + the existing unit suite proves substantially more production code is reachable. + +### 2026-08-16 — Established default-parse coverage plateau + +- Expanded the corpus to 79 cases and reached 84.05% statements, 74.06% + branches, 94.62% functions, and 84.61% lines without production changes. +- Set integer-floor thresholds at 84/74/94/84 after the final batch gained only + 0.20 statement points and remaining regions were classified by reachability. +- Explained the difference from the former 92% combined suite: unit tests cover + custom resolvers, directly exported helpers, and synthetic invalid AST states + excluded from the default parser corpus. + +### 2026-08-16 — Converted internal tooling packages + +- Converted `@react-docgen-internal/integration-tests` from handwritten MJS plus + declarations to a compiled TypeScript package. +- Moved `@react-docgen-internal/benchmark` from the workspace root to + `packages/benchmark` and updated workspace, Renovate, lint, lockfile, and + runtime paths. +- Reason: internal packages now follow the same workspace layout and TypeScript + build conventions as the parser packages. + +### 2026-08-16 — Recorded separate coverage contracts + +- Recorded 84.05/74.06/94.62/84.61 as the portable default-parse integration + baseline and 95.03/88.78/98.41/95.45 as the complete unit-and-integration + baseline. +- Kept integration thresholds tied to the portable corpus rather than raising + them to complete-suite values. +- Reason: unit tests additionally cover Babel-specific internals, public helper + APIs, custom resolvers, and synthetic AST states that parser adapters should + not need to reproduce through integration fixtures. diff --git a/eslint.config.mjs b/eslint.config.mjs index 620f7d4815a..bae9e519167 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -6,8 +6,9 @@ import tseslint from 'typescript-eslint'; export default tseslint.config([ globalIgnores([ - 'benchmark/suites/', + 'packages/benchmark/suites/', '**/__fixtures__/', + 'packages/integration-tests/cases/', '**/dist/', '**/.nx/', '**/coverage', diff --git a/benchmark/index.mjs b/packages/benchmark/index.mjs similarity index 97% rename from benchmark/index.mjs rename to packages/benchmark/index.mjs index 68408bf2844..914e31eb0b4 100644 --- a/benchmark/index.mjs +++ b/packages/benchmark/index.mjs @@ -4,7 +4,7 @@ import { fileURLToPath } from 'url'; import Table from 'cli-table'; import glob from 'fast-glob'; import Benchmark from 'benchmark'; -import { parse } from '../packages/react-docgen/dist/main.js'; +import { parse } from '../react-docgen/dist/main.js'; import { parse as parse5 } from 'react-docgen5'; import { parse as parse6 } from 'react-docgen6'; diff --git a/benchmark/package.json b/packages/benchmark/package.json similarity index 100% rename from benchmark/package.json rename to packages/benchmark/package.json diff --git a/packages/integration-tests/AUDIT.md b/packages/integration-tests/AUDIT.md new file mode 100644 index 00000000000..a69451be0c9 --- /dev/null +++ b/packages/integration-tests/AUDIT.md @@ -0,0 +1,128 @@ +# Disabled unit-test behavior audit + +This audit maps each disabled legacy unit-test suite to its portable integration +disposition. Parameterized cases are grouped when one readable fixture exposes +the same public JSON. Invalid `NodePath` inputs and helper-only intermediate +values are internal implementation details, not public `parse()` behavior. + +Disposition vocabulary: + +- **existing integration case**: represented by a migrated golden case. +- **new integration case**: represented by a case added during this audit. +- **duplicate observable behavior**: another named case already asserts the same + public JSON or error. +- **internal-only implementation detail**: no distinct public output exists. +- **excluded custom configuration**: requires a non-default resolver, handler, + importer, or parser option. + +## Public facade and resolvers + +| Disabled suite | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `main-test.ts`, `parse-test.ts` | new integration case | `js/definitions/function-declaration`, `js/errors/missing-definition`, and `js/errors/multiple-definitions` cover default parse output and stable public errors. Parser/options validation is excluded custom configuration. | +| `FindExportedDefinitionsResolver-test.ts` | existing integration case | Definition, default/named/CommonJS export, re-export, HOC, and error cases. | +| `FindAnnotatedDefinitionsResolver-test.ts` | new integration case | `js/definitions/annotated-function`. | +| `FindAllDefinitionsResolver-test.ts` | excluded custom configuration | Public only when callers replace the default resolver. | +| `ChainResolver-test.ts` | internal-only implementation detail | Resolver composition has no independent documentation output. | +| `runResolver-test.ts` | internal-only implementation detail | Adapter for resolver return shapes; covered transitively by every case. | + +## Handlers + +| Disabled suite | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `codeTypeHandler-test.ts` | new integration case | `typescript/types/comprehensive-props`, `typescript/types/advanced-props`, and `flow/types/comprehensive-props`. | +| `componentDocblockHandler-test.ts` | existing integration case | Component descriptions across JS, Flow, TypeScript, HOCs, and imported definitions. | +| `componentMethodsHandler-test.ts` | existing integration case | JS/TypeScript class and imperative-handle method cases. | +| `componentMethodsJsDocHandler-test.ts` | new integration case | `js/methods/parameter-shapes` plus migrated `js/methods/class-method-documentation`. | +| `defaultPropsHandler-test.ts` | new integration case | Migrated static/function/default cases plus `js/defaults/spreads-and-parameters` and `typescript/defaults/function-default-parameters`. | +| `displayNameHandler-test.ts` | existing integration case | Function/class/CreateClass/forwardRef/HOC display names. Unresolvable artificial expressions are duplicate observable behavior: absent `displayName`. | +| `propDocblockHandler-test.ts` | duplicate observable behavior | Descriptions are asserted throughout JS PropTypes and typed prop cases. | +| `propTypeCompositionHandler-test.ts` | existing integration case | Flow/TypeScript intersections, interface extension, spreads, and imported types. | +| `propTypeHandler-test.ts` | new integration case | `js/props/all-proptypes`, `js/props/object-key-and-value-enums`, and migrated shape/context cases cover public validators and requiredness. Custom PropTypes aliases are excluded custom configuration. | + +## Utility suites with distinct public output + +| Disabled suite(s) | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `docblock-test.ts`, `parseJsDoc-test.ts`, `setPropDescription-test.ts` | new integration case | Documentation, prop descriptions, method descriptions, parameters, returns, and nested return docs are asserted by documentation/method/type cases. Malformed raw doctrine input is internal-only. | +| `getParameterName-test.ts`, `getMethodDocumentation-test.ts` | new integration case | `js/methods/parameter-shapes` asserts identifiers, defaults, object/array patterns, rest parameters, and JSDoc association. TypeScript parameter properties are constructor-only and do not produce public method docs. | +| `getPropType-test.ts`, `isRequiredPropType-test.ts` | new integration case | Full validator families, nested shapes, unions, enums from object keys/values, and required validators. Invalid direct helper arguments are internal-only. | +| `getFlowType-test.ts`, `flowUtilityTypes-test.ts`, `isUnreachableFlowType-test.ts`, `resolveGenericTypeAnnotations-test.ts` | existing integration case | Comprehensive props, utility types, React/DOM types, generics, intersections, spreads, interfaces, imports, and historical regressions. Unsupported/unreachable annotations have no distinct public field. | +| `getTSType-test.ts`, `unwrapBuiltinTSPropTypes-test.ts` | new integration case | Comprehensive and advanced TypeScript props cover primitives, literals, arrays, tuples, unions, intersections, objects, functions, `typeof`, `keyof`, indexed access, mapped types, qualified React types, call/index/method signatures, and built-ins. | +| `resolveObjectKeysToArray-test.ts`, `resolveObjectValuesToArray-test.ts` | new integration case | `js/props/object-key-and-value-enums`; unresolved expressions are already represented by unresolved enum behavior. | +| `printValue-test.ts`, `expressionTo-test.ts`, `getNameOrValue-test.ts` | existing integration case | Defaults, literals, enum values, computed properties, and imported/re-exported constants assert their reachable serialized forms. Invalid isolated AST kinds are internal-only. | +| `resolveToValue-test.ts`, `resolveFunctionDefinitionToReturnValue-test.ts`, `findFunctionReturn-test.ts` | existing integration case | Function components, HOCs, forwardRef/memo, default values, and imported values cover successful public resolution. Ambiguous helper states have no separate output. | +| `resolveHOC-test.ts`, `normalizeClassDefinition-test.ts`, `getTypeFromReactComponent-test.ts` | existing integration case | HOC-wrapped, custom base, PureComponent, forwardRef, memo, generic class, and polymorphic forwardRef cases. | +| `getMemberValuePath-test.ts`, `getClassMemberValuePath-test.ts`, `getMemberExpressionValuePath-test.ts`, `getPropertyValuePath-test.ts`, `getMembers-test.ts`, `getPropertyName-test.ts` | existing integration case | Static/member/default/PropTypes/computed/spread cases cover all publicly observable successful lookups. Invalid or missing members yield the already-covered absent field. | +| `resolveExportDeclaration-test.ts`, `resolveToModule-test.ts` | existing integration case | ESM, CommonJS, namespace, star, member, imported-type, and re-export chains. Importer failures beyond default filesystem behavior are excluded custom configuration. | +| `resolveObjectPatternPropertyToValue-test.ts` | new integration case | Function parameter defaults and destructured defaults. Missing properties produce the same absent default output. | + +## Predicate and structural utility suites + +These suites decide which already-covered component/export path is selected. +Their false branches do not create distinct public output, so isolated predicate +matrices would only reproduce implementation tests. + +| Disabled suites | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `isReactChildrenElementCall-test.ts`, `isReactCreateElementCall-test.ts`, `isReactCloneElementCall-test.ts` | duplicate observable behavior | React node/element PropTypes and JSX component cases. | +| `isReactForwardRefCall-test.ts`, `isReactCreateClassCall-test.ts`, `isStatelessComponent-test.ts`, `isReactComponentClass-test.ts`, `isReactComponentMethod-test.ts` | duplicate observable behavior | Existing definitions, defaults, methods, Flow, TypeScript, forwardRef, memo, and class cases. | +| `isReactBuiltinReference-test.ts`, `isReactModuleName-test.ts` | duplicate observable behavior | `React.PropTypes`, package `prop-types`, React classes, and namespace/import cases. Custom module aliases are excluded custom configuration. | +| `isDestructuringAssignment-test.ts`, `isExportsOrModuleAssignment-test.ts`, `getMemberExpressionRoot-test.ts` | duplicate observable behavior | Destructured defaults, CommonJS exports, and member/re-export cases. | +| `getTypeAnnotation-test.ts`, `getTypeParameters-test.ts` | duplicate observable behavior | Generic Flow/TypeScript, function, array, React, and imported type cases. | + +## Coverage batches + +| Batch | Cases added | Statements | Branches | Functions | Lines | +| --- | ---: | ---: | ---: | ---: | ---: | +| Migrated legacy baseline | 49 | 71.33% | 61.78% | 79.43% | 71.99% | +| First expansion: definitions, exports, errors, props, defaults, methods, TypeScript, Flow | 12 | 74.81% | 63.38% | 85.44% | 75.47% | +| Object enums, method parameter shapes, advanced TypeScript | 3 | 79.28% | 68.18% | 89.55% | 79.86% | +| Advanced Flow, value serialization, display-name resolution | 3 | 81.47% | 70.38% | 93.35% | 82.08% | +| Typed method modifiers and signatures | 1 | 81.81% | 71.21% | 93.35% | 82.44% | +| React prop wrappers, class normalization, computed keys/exports, display names | 6 | 83.35% | 73.05% | 93.35% | 83.90% | +| JSDoc variants, composed validators, imported defaults/enums | 3 | 83.85% | 73.70% | 94.62% | 84.40% | +| Nested configured HOCs and destructured bindings | 2 | 84.05% | 74.06% | 94.62% | 84.61% | + +The final default-configuration plateau is 84.05% statements, 74.06% branches, +94.62% functions, and 84.61% lines. Enforced integer floors are 84%, 74%, 94%, +and 84%, respectively. The former unit-and-integration suite reached about 92% +statements because it directly exercised custom resolvers, public helper APIs, +and synthetic invalid AST paths outside default `parse()`. + +After unit-test discovery was restored, the complete suite established the +following baseline: + +| Suite | Statements | Branches | Functions | Lines | +| --- | ---: | ---: | ---: | ---: | +| Portable integration corpus | 84.05% | 74.06% | 94.62% | 84.61% | +| Complete unit and integration suite | 95.03% | 88.78% | 98.41% | 95.45% | + +These are separate contracts. Integration coverage measures parser-portable +observable behavior through default `parse()`. Complete-suite coverage also +measures Babel-specific internals, extension helpers, custom resolvers, and +synthetic invalid AST states. The integration thresholds therefore remain based +on the portable corpus rather than the complete-suite percentages. + +## Remaining audit + +Remaining uncovered regions were checked against default `parse()` reachability. +Valid final exclusions are: + +1. False/error branches of internal AST helpers whose public result duplicates + an absent documentation field. +2. Custom resolver, handler, importer, and parser-option paths excluded from the + default parse corpus. +3. Parser-version-specific syntax/error behavior excluded from parser-neutral + goldens. +4. Defensive branches requiring invalid or manually constructed Babel paths, + unreachable through public parsing. + +The largest excluded regions are `FindAllDefinitionsResolver`, which requires a +custom resolver; `expressionTo` object/array serialization, exposed as a direct +helper API; invalid-input branches in `getNameOrValue`; and internal resolution +states that only unit tests can construct. The final HOC/destructuring batch +added only 0.20 statement points, and the destructuring helper remained +unchanged, confirming diminishing default-flow coverage. + +No production source or coverage-directive comment was added. diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_18.js b/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_18.js rename to packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/index.js diff --git a/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/output.json b/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/output.json new file mode 100644 index 00000000000..c4240f01f9b --- /dev/null +++ b/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/output.json @@ -0,0 +1,31 @@ +[ + { + "description": "", + "displayName": "UncoloredView", + "methods": [], + "props": { + "color": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "flowType": { + "name": "string", + "nullable": true + } + }, + "id": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'test-forward-ref-default'", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_14.js b/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_14.js rename to packages/integration-tests/cases/flow/definitions/forward-ref-display-name/index.js diff --git a/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/output.json b/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/output.json new file mode 100644 index 00000000000..1e04e72a3cc --- /dev/null +++ b/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/output.json @@ -0,0 +1,17 @@ +[ + { + "description": "", + "displayName": "UncoloredView", + "methods": [], + "props": { + "color": { + "required": false, + "flowType": { + "name": "string", + "nullable": true + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_19.js b/packages/integration-tests/cases/flow/definitions/pure-component/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_19.js rename to packages/integration-tests/cases/flow/definitions/pure-component/index.js diff --git a/packages/integration-tests/cases/flow/definitions/pure-component/output.json b/packages/integration-tests/cases/flow/definitions/pure-component/output.json new file mode 100644 index 00000000000..73bd29e3f85 --- /dev/null +++ b/packages/integration-tests/cases/flow/definitions/pure-component/output.json @@ -0,0 +1,22 @@ +[ + { + "description": "", + "displayName": "Component", + "methods": [], + "props": { + "data": { + "required": false, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "mixed" + } + ], + "raw": "Array" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/flow-export-type.js b/packages/integration-tests/cases/flow/exports/exported-type/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/flow-export-type.js rename to packages/integration-tests/cases/flow/exports/exported-type/index.js diff --git a/packages/integration-tests/cases/flow/exports/exported-type/output.json b/packages/integration-tests/cases/flow/exports/exported-type/output.json new file mode 100644 index 00000000000..f9ded0fe001 --- /dev/null +++ b/packages/integration-tests/cases/flow/exports/exported-type/output.json @@ -0,0 +1,55 @@ +[ + { + "description": "This is a Flow class component", + "displayName": "FlowComponent", + "methods": [ + { + "name": "foo", + "docblock": null, + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + } + }, + { + "name": "bar", + "docblock": null, + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + } + } + ], + "props": { + "foo": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/flow/imports/imported-type/flow-export-type.js b/packages/integration-tests/cases/flow/imports/imported-type/flow-export-type.js new file mode 100644 index 00000000000..ad227ba6897 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/imported-type/flow-export-type.js @@ -0,0 +1,26 @@ +/** + * @flow + */ + +import React, { Component } from 'react'; + +export type Props = { + foo: string +} + +/** + * This is a Flow class component + */ +export default class FlowComponent extends Component { + render() { + return

Hello world

; + } + + foo(a: string): string { + return a; + } + + bar(a: string): string { + return a; + } +} diff --git a/packages/react-docgen/tests/integration/__fixtures__/flow-import-type.js b/packages/integration-tests/cases/flow/imports/imported-type/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/flow-import-type.js rename to packages/integration-tests/cases/flow/imports/imported-type/index.js diff --git a/packages/integration-tests/cases/flow/imports/imported-type/output.json b/packages/integration-tests/cases/flow/imports/imported-type/output.json new file mode 100644 index 00000000000..db120def951 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/imported-type/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "This is a Flow component with imported prop types", + "displayName": "ImportedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-export-type.js b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-export-type.js new file mode 100644 index 00000000000..ad227ba6897 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-export-type.js @@ -0,0 +1,26 @@ +/** + * @flow + */ + +import React, { Component } from 'react'; + +export type Props = { + foo: string +} + +/** + * This is a Flow class component + */ +export default class FlowComponent extends Component { + render() { + return

Hello world

; + } + + foo(a: string): string { + return a; + } + + bar(a: string): string { + return a; + } +} diff --git a/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-import-type.js b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-import-type.js new file mode 100644 index 00000000000..c5a4dfec45e --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-import-type.js @@ -0,0 +1,18 @@ +/** + * @flow + */ + +import React, { Component } from 'react'; +import type { Props as ImportedProps } from './flow-export-type.js'; + +export type ExtendedProps = { + ...ImportedProps, + bar: number +} + +/** + * This is a Flow component with imported prop types + */ +export function ImportedComponent(props: ImportedProps) { + return

Hello world

; +} diff --git a/packages/react-docgen/tests/integration/__fixtures__/flow-spread-import-type.js b/packages/integration-tests/cases/flow/imports/spread-imported-type/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/flow-spread-import-type.js rename to packages/integration-tests/cases/flow/imports/spread-imported-type/index.js diff --git a/packages/integration-tests/cases/flow/imports/spread-imported-type/output.json b/packages/integration-tests/cases/flow/imports/spread-imported-type/output.json new file mode 100644 index 00000000000..71a7b67c365 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/spread-imported-type/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "This is a Flow component with imported prop types", + "displayName": "ImportedExtendedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + }, + "bar": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_32.js b/packages/integration-tests/cases/flow/methods/generic-class/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_32.js rename to packages/integration-tests/cases/flow/methods/generic-class/index.js diff --git a/packages/integration-tests/cases/flow/methods/generic-class/output.json b/packages/integration-tests/cases/flow/methods/generic-class/output.json new file mode 100644 index 00000000000..dea2d495bd1 --- /dev/null +++ b/packages/integration-tests/cases/flow/methods/generic-class/output.json @@ -0,0 +1,58 @@ +[ + { + "description": "", + "displayName": "Segments", + "methods": [ + { + "name": "foo", + "docblock": null, + "modifiers": [], + "params": [ + { + "name": "props", + "optional": false, + "type": { + "name": "signature", + "type": "object", + "raw": "{\n segments: Array,\n}", + "signature": { + "properties": [ + { + "key": "segments", + "value": { + "name": "Array", + "elements": [ + { + "name": "T" + } + ], + "raw": "Array", + "required": true + } + } + ] + }, + "alias": "Props" + } + } + ], + "returns": null + } + ], + "props": { + "segments": { + "required": true, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "T" + } + ], + "raw": "Array" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_12.js b/packages/integration-tests/cases/flow/regressions/material-ui-paper/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_12.js rename to packages/integration-tests/cases/flow/regressions/material-ui-paper/index.js diff --git a/packages/integration-tests/cases/flow/regressions/material-ui-paper/output.json b/packages/integration-tests/cases/flow/regressions/material-ui-paper/output.json new file mode 100644 index 00000000000..9cfbc990998 --- /dev/null +++ b/packages/integration-tests/cases/flow/regressions/material-ui-paper/output.json @@ -0,0 +1,180 @@ +[ + { + "description": "", + "displayName": "Paper", + "methods": [], + "props": { + "classes": { + "required": false, + "flowType": { + "name": "Object" + }, + "description": "Useful to extend the style applied to components." + }, + "anchorOrigin": { + "required": false, + "flowType": { + "name": "signature", + "type": "object", + "raw": "{\n horizontal: 'left' | 'center' | 'right' | number,\n vertical: 'top' | 'center' | 'bottom' | number,\n}", + "signature": { + "properties": [ + { + "key": "horizontal", + "value": { + "name": "union", + "raw": "'left' | 'center' | 'right' | number", + "elements": [ + { + "name": "literal", + "value": "'left'" + }, + { + "name": "literal", + "value": "'center'" + }, + { + "name": "literal", + "value": "'right'" + }, + { + "name": "number" + } + ], + "required": true + } + }, + { + "key": "vertical", + "value": { + "name": "union", + "raw": "'top' | 'center' | 'bottom' | number", + "elements": [ + { + "name": "literal", + "value": "'top'" + }, + { + "name": "literal", + "value": "'center'" + }, + { + "name": "literal", + "value": "'bottom'" + }, + { + "name": "number" + } + ], + "required": true + } + } + ] + } + }, + "description": "This is the point on the anchor where the popover's\n`anchorEl` will attach to. This is not used when the\nanchorReference is 'anchorPosition'.\n\nOptions:\nvertical: [top, center, bottom];\nhorizontal: [left, center, right].", + "defaultValue": { + "value": "{\n vertical: 'top',\n horizontal: 'left',\n}", + "computed": false + } + }, + "children": { + "required": false, + "flowType": { + "name": "Node" + }, + "description": "@ignore" + }, + "component": { + "required": false, + "flowType": { + "name": "ElementType" + }, + "description": "The component used for the root node.\nThis currently has to be flow cast in defaultProps as of flow 0.59.0", + "defaultValue": { + "value": "'div'", + "computed": false + } + }, + "elevation": { + "required": false, + "flowType": { + "name": "number" + }, + "description": "Shadow depth, corresponds to `dp` in the spec.\nIt's accepting values between 0 and 24 inclusive.", + "defaultValue": { + "value": "2", + "computed": false + } + }, + "labelRowsPerPage": { + "required": false, + "flowType": { + "name": "Node" + }, + "description": "Useful to customize the rows per page label. Invoked with a `{ from, to, count, page }`\nobject.", + "defaultValue": { + "value": "'Rows per page:'", + "computed": false + } + }, + "transition": { + "required": true, + "flowType": { + "name": "ComponentType", + "elements": [ + { + "name": "unknown" + } + ], + "raw": "ComponentType<*>" + }, + "description": "Transition component." + }, + "timeout": { + "required": false, + "flowType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "The duration for the transition, in milliseconds.\nYou may specify a single timeout for all transitions, or individually with an object.\n\nSet to 'auto' to automatically calculate transition time based on height.", + "defaultValue": { + "value": "300", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/flow/types/advanced-props/index.js b/packages/integration-tests/cases/flow/types/advanced-props/index.js new file mode 100644 index 00000000000..a9dd058288f --- /dev/null +++ b/packages/integration-tests/cases/flow/types/advanced-props/index.js @@ -0,0 +1,38 @@ +// @flow + +type NamedFunction = ( + count: number, + label: ?string, + ...rest: Array +) => boolean; + +type Callable = { + (value: string): number, + /** Values stored by key. */ + [key: string]: number, + token: 'a' | 'b', +}; + +const sizes = { small: 's', large: 'l' }; +type Shape = { left: string, right: number }; + +type Props = { + namedFunction: NamedFunction, + unnamedFunction: (number, ?string) => boolean, + singleFunction: string => boolean, + callable: Callable, + tupleUnion: [string, number] | [number, string], + intersection: { left: string } & { right: number }, + classType: Class, + optionalArray?: string[], + keys: $Keys, + qualified: React.Node, + objectType: typeof sizes, + indexed: Shape['left'], + missingIndex: Shape['missing'], +}; + +/** Exercises advanced Flow prop type extraction. */ +export function AdvancedFlowTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/flow/types/advanced-props/output.json b/packages/integration-tests/cases/flow/types/advanced-props/output.json new file mode 100644 index 00000000000..a76c8d9d0d6 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/advanced-props/output.json @@ -0,0 +1,311 @@ +[ + { + "description": "Exercises advanced Flow prop type extraction.", + "displayName": "AdvancedFlowTypes", + "methods": [], + "props": { + "namedFunction": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "(\n count: number,\n label: ?string,\n ...rest: Array\n) => boolean", + "signature": { + "arguments": [ + { + "name": "count", + "type": { + "name": "number" + } + }, + { + "name": "label", + "type": { + "name": "string", + "nullable": true + } + }, + { + "name": "rest", + "type": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "Array" + }, + "rest": true + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "unnamedFunction": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "(number, ?string) => boolean", + "signature": { + "arguments": [ + { + "name": "", + "type": { + "name": "number" + } + }, + { + "name": "", + "type": { + "name": "string", + "nullable": true + } + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "singleFunction": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "string => boolean", + "signature": { + "arguments": [ + { + "name": "", + "type": { + "name": "string" + } + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "callable": { + "required": true, + "flowType": { + "name": "signature", + "type": "object", + "raw": "{\n (value: string): number,\n /** Values stored by key. */\n [key: string]: number,\n token: 'a' | 'b',\n}", + "signature": { + "properties": [ + { + "key": { + "name": "string" + }, + "value": { + "name": "number", + "required": true + }, + "description": "Values stored by key." + }, + { + "key": "token", + "value": { + "name": "union", + "raw": "'a' | 'b'", + "elements": [ + { + "name": "literal", + "value": "'a'" + }, + { + "name": "literal", + "value": "'b'" + } + ], + "required": true + } + } + ], + "constructor": { + "name": "signature", + "type": "function", + "raw": "(value: string): number", + "signature": { + "arguments": [ + { + "name": "value", + "type": { + "name": "string" + } + } + ], + "return": { + "name": "number" + } + } + } + } + }, + "description": "" + }, + "tupleUnion": { + "required": true, + "flowType": { + "name": "union", + "raw": "[string, number] | [number, string]", + "elements": [ + { + "name": "tuple", + "raw": "[string, number]", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + { + "name": "tuple", + "raw": "[number, string]", + "elements": [ + { + "name": "number" + }, + { + "name": "string" + } + ] + } + ] + }, + "description": "" + }, + "intersection": { + "required": true, + "flowType": { + "name": "intersection", + "raw": "{ left: string } & { right: number }", + "elements": [ + { + "name": "signature", + "type": "object", + "raw": "{ left: string }", + "signature": { + "properties": [ + { + "key": "left", + "value": { + "name": "string", + "required": true + } + } + ] + } + }, + { + "name": "signature", + "type": "object", + "raw": "{ right: number }", + "signature": { + "properties": [ + { + "key": "right", + "value": { + "name": "number", + "required": true + } + } + ] + } + } + ] + }, + "description": "" + }, + "classType": { + "required": true, + "flowType": { + "name": "Class", + "elements": [ + { + "name": "boolean" + } + ], + "raw": "Class" + }, + "description": "" + }, + "optionalArray": { + "required": false, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "string[]" + }, + "description": "" + }, + "keys": { + "required": true, + "flowType": { + "name": "union", + "raw": "$Keys", + "elements": [ + { + "name": "literal", + "value": "small" + }, + { + "name": "literal", + "value": "large" + } + ] + }, + "description": "" + }, + "qualified": { + "required": true, + "flowType": { + "name": "ReactNode", + "raw": "React.Node" + }, + "description": "" + }, + "objectType": { + "required": true, + "flowType": { + "name": "sizes" + }, + "description": "" + }, + "indexed": { + "required": true, + "flowType": { + "name": "string", + "raw": "Shape['left']" + }, + "description": "" + }, + "missingIndex": { + "required": true, + "flowType": { + "name": "unknown" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/flow/types/comprehensive-props/index.js b/packages/integration-tests/cases/flow/types/comprehensive-props/index.js new file mode 100644 index 00000000000..57962999404 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/comprehensive-props/index.js @@ -0,0 +1,22 @@ +// @flow + +type Props = { + anything: any, + mixedValue: mixed, + text: string, + count: number, + enabled: boolean, + literal: 'small', + union: string | number, + maybe: ?string, + list: Array, + pair: [string, number], + callback: (value: string) => boolean, + nested: { value?: string }, + optional?: string, +}; + +/** Exercises Flow prop type extraction. */ +export function FlowTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/flow/types/comprehensive-props/output.json b/packages/integration-tests/cases/flow/types/comprehensive-props/output.json new file mode 100644 index 00000000000..2e6967075ef --- /dev/null +++ b/packages/integration-tests/cases/flow/types/comprehensive-props/output.json @@ -0,0 +1,154 @@ +[ + { + "description": "Exercises Flow prop type extraction.", + "displayName": "FlowTypes", + "methods": [], + "props": { + "anything": { + "required": true, + "flowType": { + "name": "any" + }, + "description": "" + }, + "mixedValue": { + "required": true, + "flowType": { + "name": "mixed" + }, + "description": "" + }, + "text": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + }, + "count": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "" + }, + "enabled": { + "required": true, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "literal": { + "required": true, + "flowType": { + "name": "literal", + "value": "'small'" + }, + "description": "" + }, + "union": { + "required": true, + "flowType": { + "name": "union", + "raw": "string | number", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "maybe": { + "required": true, + "flowType": { + "name": "string", + "nullable": true + }, + "description": "" + }, + "list": { + "required": true, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "Array" + }, + "description": "" + }, + "pair": { + "required": true, + "flowType": { + "name": "tuple", + "raw": "[string, number]", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "callback": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "(value: string) => boolean", + "signature": { + "arguments": [ + { + "name": "value", + "type": { + "name": "string" + } + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "nested": { + "required": true, + "flowType": { + "name": "signature", + "type": "object", + "raw": "{ value?: string }", + "signature": { + "properties": [ + { + "key": "value", + "value": { + "name": "string", + "required": false + } + } + ] + } + }, + "description": "" + }, + "optional": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_30.js b/packages/integration-tests/cases/flow/types/concrete-identity/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_30.js rename to packages/integration-tests/cases/flow/types/concrete-identity/index.js diff --git a/packages/integration-tests/cases/flow/types/concrete-identity/output.json b/packages/integration-tests/cases/flow/types/concrete-identity/output.json new file mode 100644 index 00000000000..b92b17a999f --- /dev/null +++ b/packages/integration-tests/cases/flow/types/concrete-identity/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "prop": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_29.js b/packages/integration-tests/cases/flow/types/generic-identity/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_29.js rename to packages/integration-tests/cases/flow/types/generic-identity/index.js diff --git a/packages/integration-tests/cases/flow/types/generic-identity/output.json b/packages/integration-tests/cases/flow/types/generic-identity/output.json new file mode 100644 index 00000000000..c7bcd68f975 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/generic-identity/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "prop": { + "required": true, + "flowType": { + "name": "T" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_26.js b/packages/integration-tests/cases/flow/types/generic-interface-extension/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_26.js rename to packages/integration-tests/cases/flow/types/generic-interface-extension/index.js diff --git a/packages/integration-tests/cases/flow/types/generic-interface-extension/output.json b/packages/integration-tests/cases/flow/types/generic-interface-extension/output.json new file mode 100644 index 00000000000..dc0f311c387 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/generic-interface-extension/output.json @@ -0,0 +1,36 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "FlowComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "flowType": { + "name": "Child" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "Child" + } + ], + "raw": "Array" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "Complex union prop" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_24.js b/packages/integration-tests/cases/flow/types/interface-composition/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_24.js rename to packages/integration-tests/cases/flow/types/interface-composition/index.js diff --git a/packages/integration-tests/cases/flow/types/interface-composition/output.json b/packages/integration-tests/cases/flow/types/interface-composition/output.json new file mode 100644 index 00000000000..efbabd70045 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/interface-composition/output.json @@ -0,0 +1,66 @@ +[ + { + "description": "This is a flow class component with an interface as props", + "displayName": "FlowComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "flowType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "Complex union prop" + } + }, + "composes": [ + "OtherProps" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_11.js b/packages/integration-tests/cases/flow/types/intersection-composition/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_11.js rename to packages/integration-tests/cases/flow/types/intersection-composition/index.js diff --git a/packages/integration-tests/cases/flow/types/intersection-composition/output.json b/packages/integration-tests/cases/flow/types/intersection-composition/output.json new file mode 100644 index 00000000000..97919102046 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/intersection-composition/output.json @@ -0,0 +1,33 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "fooProp": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "fooProp is spread in from a locally resolved type" + }, + "prop1": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "The first prop" + }, + "prop2": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "The second, covariant prop" + } + }, + "composes": [ + "OtherProps" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_31.js b/packages/integration-tests/cases/flow/types/nested-generic-identity/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_31.js rename to packages/integration-tests/cases/flow/types/nested-generic-identity/index.js diff --git a/packages/integration-tests/cases/flow/types/nested-generic-identity/output.json b/packages/integration-tests/cases/flow/types/nested-generic-identity/output.json new file mode 100644 index 00000000000..c7bcd68f975 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/nested-generic-identity/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "prop": { + "required": true, + "flowType": { + "name": "T" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_13.js b/packages/integration-tests/cases/flow/types/react-and-dom-types/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_13.js rename to packages/integration-tests/cases/flow/types/react-and-dom-types/index.js diff --git a/packages/integration-tests/cases/flow/types/react-and-dom-types/output.json b/packages/integration-tests/cases/flow/types/react-and-dom-types/output.json new file mode 100644 index 00000000000..6e0869ec511 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/react-and-dom-types/output.json @@ -0,0 +1,254 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "align": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"left\" | \"center\" | \"right\" | \"justify\"", + "elements": [ + { + "name": "literal", + "value": "\"left\"" + }, + { + "name": "literal", + "value": "\"center\"" + }, + { + "name": "literal", + "value": "\"right\"" + }, + { + "name": "literal", + "value": "\"justify\"" + } + ] + }, + "description": "" + }, + "left": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "center": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "right": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "justify": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "transform": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"lowercase\" | \"uppercase\" | \"capitalize\"", + "elements": [ + { + "name": "literal", + "value": "\"lowercase\"" + }, + { + "name": "literal", + "value": "\"uppercase\"" + }, + { + "name": "literal", + "value": "\"capitalize\"" + } + ] + }, + "description": "" + }, + "lowercase": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "uppercase": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "capitalize": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "tracking": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"tight\" | \"normal\" | \"wide\"", + "elements": [ + { + "name": "literal", + "value": "\"tight\"" + }, + { + "name": "literal", + "value": "\"normal\"" + }, + { + "name": "literal", + "value": "\"wide\"" + } + ] + }, + "description": "" + }, + "trackingTight": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "trackingNormal": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "trackingWide": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leading": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"none\" | \"tight\" | \"normal\" | \"loose\"", + "elements": [ + { + "name": "literal", + "value": "\"none\"" + }, + { + "name": "literal", + "value": "\"tight\"" + }, + { + "name": "literal", + "value": "\"normal\"" + }, + { + "name": "literal", + "value": "\"loose\"" + } + ] + }, + "description": "" + }, + "leadingNone": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leadingTight": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leadingNormal": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leadingLoose": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "children": { + "required": false, + "flowType": { + "name": "ReactNode", + "raw": "React.Node" + }, + "description": "" + }, + "className": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + }, + "RootComponent": { + "required": false, + "flowType": { + "name": "ReactElementType", + "raw": "React.ElementType" + }, + "description": "" + }, + "color": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + }, + "size": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + }, + "wrap": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "muted": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_15.js b/packages/integration-tests/cases/flow/types/spread-composition/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_15.js rename to packages/integration-tests/cases/flow/types/spread-composition/index.js diff --git a/packages/integration-tests/cases/flow/types/spread-composition/output.json b/packages/integration-tests/cases/flow/types/spread-composition/output.json new file mode 100644 index 00000000000..47f379e543d --- /dev/null +++ b/packages/integration-tests/cases/flow/types/spread-composition/output.json @@ -0,0 +1,62 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "other": { + "required": true, + "flowType": { + "name": "literal", + "value": "'a'" + }, + "description": "" + }, + "other2": { + "required": true, + "flowType": { + "name": "literal", + "value": "'b'" + }, + "description": "" + }, + "other3": { + "required": true, + "flowType": { + "name": "literal", + "value": "'c'" + }, + "description": "" + }, + "other4": { + "required": true, + "flowType": { + "name": "literal", + "value": "'g'" + }, + "description": "" + }, + "other5": { + "required": true, + "flowType": { + "name": "literal", + "value": "'f'" + }, + "description": "" + }, + "somePropOverride": { + "required": true, + "flowType": { + "name": "literal", + "value": "'baz'" + }, + "description": "" + } + }, + "composes": [ + "BarProps", + "BarProps2", + "BarProps3" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_20.js b/packages/integration-tests/cases/js/defaults/computed-property/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_20.js rename to packages/integration-tests/cases/js/defaults/computed-property/index.js diff --git a/packages/integration-tests/cases/js/defaults/computed-property/output.json b/packages/integration-tests/cases/js/defaults/computed-property/output.json new file mode 100644 index 00000000000..24a099af70c --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/computed-property/output.json @@ -0,0 +1,20 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "@computed#children": { + "type": { + "name": "string" + }, + "required": false, + "description": "This is a test", + "defaultValue": { + "value": "\"default\"", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/defaults/destructured-bindings/index.jsx b/packages/integration-tests/cases/js/defaults/destructured-bindings/index.jsx new file mode 100644 index 00000000000..1ddd851740c --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/destructured-bindings/index.jsx @@ -0,0 +1,24 @@ +import PropTypes from 'prop-types'; + +const source = { + label: 'from-variable-pattern', + count: 7, +}; +const { label } = source; +let count; + +({ count } = source); + +export default function DestructuredBindings() { + return
; +} + +DestructuredBindings.propTypes = { + label: PropTypes.string, + count: PropTypes.number, +}; + +DestructuredBindings.defaultProps = { + label, + count, +}; diff --git a/packages/integration-tests/cases/js/defaults/destructured-bindings/output.json b/packages/integration-tests/cases/js/defaults/destructured-bindings/output.json new file mode 100644 index 00000000000..1a825c14026 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/destructured-bindings/output.json @@ -0,0 +1,31 @@ +[ + { + "description": "", + "displayName": "DestructuredBindings", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "label", + "computed": false + } + }, + "count": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "count", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_16.js b/packages/integration-tests/cases/js/defaults/function-default-props/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_16.js rename to packages/integration-tests/cases/js/defaults/function-default-props/index.js diff --git a/packages/integration-tests/cases/js/defaults/function-default-props/output.json b/packages/integration-tests/cases/js/defaults/function-default-props/output.json new file mode 100644 index 00000000000..2d02536f9f5 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/function-default-props/output.json @@ -0,0 +1,21 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "bar": { + "type": { + "name": "custom", + "raw": "PropTypes.node" + }, + "required": false, + "description": "This does something.", + "defaultValue": { + "value": "null", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_42.js b/packages/integration-tests/cases/js/defaults/memo-forward-ref/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_42.js rename to packages/integration-tests/cases/js/defaults/memo-forward-ref/index.js diff --git a/packages/integration-tests/cases/js/defaults/memo-forward-ref/output.json b/packages/integration-tests/cases/js/defaults/memo-forward-ref/output.json new file mode 100644 index 00000000000..f38f6d016a3 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/memo-forward-ref/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "foo": { + "defaultValue": { + "value": "'bar'", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/integration-tests/cases/js/defaults/spreads-and-parameters/index.jsx b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/index.jsx new file mode 100644 index 00000000000..29494fb2cac --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/index.jsx @@ -0,0 +1,20 @@ +import PropTypes from 'prop-types'; + +const sharedDefaults = { + theme: 'light', +}; + +export function Button({ label = 'Fallback', size = 1 }) { + return ; +} + +Button.propTypes = { + label: PropTypes.string, + size: PropTypes.number, + theme: PropTypes.string, +}; + +Button.defaultProps = { + ...sharedDefaults, + label: 'Save', +}; diff --git a/packages/integration-tests/cases/js/defaults/spreads-and-parameters/output.json b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/output.json new file mode 100644 index 00000000000..01311d49c9c --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/output.json @@ -0,0 +1,42 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'Save'", + "computed": false + } + }, + "size": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "1", + "computed": false + } + }, + "theme": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'light'", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_40.js b/packages/integration-tests/cases/js/defaults/unresolved-enum/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_40.js rename to packages/integration-tests/cases/js/defaults/unresolved-enum/index.js diff --git a/packages/integration-tests/cases/js/defaults/unresolved-enum/output.json b/packages/integration-tests/cases/js/defaults/unresolved-enum/output.json new file mode 100644 index 00000000000..3500b1a1fa4 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/unresolved-enum/output.json @@ -0,0 +1,22 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "size": { + "type": { + "name": "enum", + "computed": true, + "value": "Object.values(Sizes)" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "Sizes.EXTRA_LARGE", + "computed": true + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/defaults/value-serialization/index.jsx b/packages/integration-tests/cases/js/defaults/value-serialization/index.jsx new file mode 100644 index 00000000000..c277442ebe7 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/value-serialization/index.jsx @@ -0,0 +1,37 @@ +import PropTypes from 'prop-types'; + +const shared = { + spreadValue: 'shared', +}; + +export default function ValueSerialization() { + return
; +} + +ValueSerialization.propTypes = { + text: PropTypes.string, + count: PropTypes.number, + disabled: PropTypes.bool, + empty: PropTypes.any, + pattern: PropTypes.instanceOf(RegExp), + big: PropTypes.any, + list: PropTypes.array, + object: PropTypes.object, + member: PropTypes.any, + called: PropTypes.any, + spreadValue: PropTypes.string, +}; + +ValueSerialization.defaultProps = { + text: 'value', + count: -2, + disabled: false, + empty: null, + pattern: /value/gi, + big: 2n, + list: ['one', 2, null], + object: { nested: true, method() {} }, + member: globalThis.location, + called: String(42), + ...shared, +}; diff --git a/packages/integration-tests/cases/js/defaults/value-serialization/output.json b/packages/integration-tests/cases/js/defaults/value-serialization/output.json new file mode 100644 index 00000000000..85c287c974e --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/value-serialization/output.json @@ -0,0 +1,131 @@ +[ + { + "description": "", + "displayName": "ValueSerialization", + "methods": [], + "props": { + "text": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'value'", + "computed": false + } + }, + "count": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "-2", + "computed": false + } + }, + "disabled": { + "type": { + "name": "bool" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "false", + "computed": false + } + }, + "empty": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "null", + "computed": false + } + }, + "pattern": { + "type": { + "name": "instanceOf", + "value": "RegExp" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "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/value/gi", + "computed": false + } + }, + "big": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "2n", + "computed": false + } + }, + "list": { + "type": { + "name": "array" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "['one', 2, null]", + "computed": false + } + }, + "object": { + "type": { + "name": "object" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "{ nested: true, method() {} }", + "computed": false + } + }, + "member": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "globalThis.location", + "computed": true + } + }, + "called": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "String(42)", + "computed": true + } + }, + "spreadValue": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'shared'", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/annotated-function/index.jsx b/packages/integration-tests/cases/js/definitions/annotated-function/index.jsx new file mode 100644 index 00000000000..a5c569972bf --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/annotated-function/index.jsx @@ -0,0 +1,4 @@ +// @component +const AnnotatedButton = ({ children }) => ; + +AnnotatedButton.displayName = 'AnnotatedButton'; diff --git a/packages/integration-tests/cases/js/definitions/annotated-function/output.json b/packages/integration-tests/cases/js/definitions/annotated-function/output.json new file mode 100644 index 00000000000..9542f41d02a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/annotated-function/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": "AnnotatedButton", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/index.jsx b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/index.jsx new file mode 100644 index 00000000000..192277f1dbe --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/index.jsx @@ -0,0 +1,17 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +let Assigned; + +Assigned = class extends React.Component { + render() { + return
; + } +}; + +Assigned.propTypes = { + value: PropTypes.number, +}; +Assigned.displayName = true; + +export default Assigned; diff --git a/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/output.json b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/output.json new file mode 100644 index 00000000000..d7f3431966a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "value": { + "type": { + "name": "number" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/index.jsx b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/index.jsx new file mode 100644 index 00000000000..f684e9497c8 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/index.jsx @@ -0,0 +1,17 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +const AssignedClass = class extends React.Component { + render() { + return
; + } +}; + +AssignedClass.propTypes = { + /** Visible text. */ + label: PropTypes.string.isRequired, +}; +AssignedClass.defaultProps = { label: 'default' }; +AssignedClass.displayName = 'AssignedClassDisplayName'; + +export default AssignedClass; diff --git a/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/output.json b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/output.json new file mode 100644 index 00000000000..b46eaf8f09e --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/output.json @@ -0,0 +1,20 @@ +[ + { + "description": "", + "displayName": "AssignedClassDisplayName", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "Visible text.", + "defaultValue": { + "value": "'default'", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/configured-nested-hoc/index.jsx b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/index.jsx new file mode 100644 index 00000000000..2a67226448a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/index.jsx @@ -0,0 +1,18 @@ +import PropTypes from 'prop-types'; + +const withOuterConfiguration = (..._arguments) => null; +const withInnerConfiguration = (..._arguments) => null; + +function NestedHocBase() { + return
; +} + +NestedHocBase.propTypes = { + /** Base value. */ + value: PropTypes.string.isRequired, +}; + +export default withOuterConfiguration( + { enabled: true }, + withInnerConfiguration('configured', NestedHocBase), +); diff --git a/packages/integration-tests/cases/js/definitions/configured-nested-hoc/output.json b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/output.json new file mode 100644 index 00000000000..0f8d9019219 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "NestedHocBase", + "methods": [], + "props": { + "value": { + "type": { + "name": "string" + }, + "required": true, + "description": "Base value." + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_9.js b/packages/integration-tests/cases/js/definitions/custom-base-class-render/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_9.js rename to packages/integration-tests/cases/js/definitions/custom-base-class-render/index.js diff --git a/packages/integration-tests/cases/js/definitions/custom-base-class-render/output.json b/packages/integration-tests/cases/js/definitions/custom-base-class-render/output.json new file mode 100644 index 00000000000..227412b3fae --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/custom-base-class-render/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "Should be recognized as component.", + "displayName": "ExampleComponent", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/definitions/display-name-resolution/index.jsx b/packages/integration-tests/cases/js/definitions/display-name-resolution/index.jsx new file mode 100644 index 00000000000..1c6b28ddebd --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/display-name-resolution/index.jsx @@ -0,0 +1,14 @@ +import React from 'react'; + +const resolvedName = 'ResolvedDisplayName'; + +/** Component with a resolved static display name. */ +export default class OriginalName extends React.Component { + static get displayName() { + return resolvedName; + } + + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/js/definitions/display-name-resolution/output.json b/packages/integration-tests/cases/js/definitions/display-name-resolution/output.json new file mode 100644 index 00000000000..414f765822a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/display-name-resolution/output.json @@ -0,0 +1,18 @@ +[ + { + "description": "Component with a resolved static display name.", + "displayName": "ResolvedDisplayName", + "methods": [ + { + "name": "displayName", + "docblock": null, + "modifiers": [ + "static", + "get" + ], + "params": [], + "returns": null + } + ] + } +] diff --git a/packages/integration-tests/cases/js/definitions/function-declaration/index.jsx b/packages/integration-tests/cases/js/definitions/function-declaration/index.jsx new file mode 100644 index 00000000000..c8b87d78986 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/function-declaration/index.jsx @@ -0,0 +1,4 @@ +/** Greets the user. */ +export function Greeting() { + return
; +} diff --git a/packages/integration-tests/cases/js/definitions/function-declaration/output.json b/packages/integration-tests/cases/js/definitions/function-declaration/output.json new file mode 100644 index 00000000000..6365c73cc66 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/function-declaration/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "Greets the user.", + "displayName": "Greeting", + "methods": [] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_3.js b/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_3.js rename to packages/integration-tests/cases/js/definitions/hoc-wrapped-component/index.js diff --git a/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/output.json b/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/output.json new file mode 100644 index 00000000000..b7f9bc461d2 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "Test", + "methods": [], + "props": { + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/numeric-display-name/index.jsx b/packages/integration-tests/cases/js/definitions/numeric-display-name/index.jsx new file mode 100644 index 00000000000..3ae9106da15 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/numeric-display-name/index.jsx @@ -0,0 +1,5 @@ +export default function NumericDisplayName() { + return
; +} + +NumericDisplayName.displayName = 42; diff --git a/packages/integration-tests/cases/js/definitions/numeric-display-name/output.json b/packages/integration-tests/cases/js/definitions/numeric-display-name/output.json new file mode 100644 index 00000000000..640ca210225 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/numeric-display-name/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": 42, + "methods": [] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_1.js b/packages/integration-tests/cases/js/definitions/react-create-class-assignment/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_1.js rename to packages/integration-tests/cases/js/definitions/react-create-class-assignment/index.js diff --git a/packages/integration-tests/cases/js/definitions/react-create-class-assignment/output.json b/packages/integration-tests/cases/js/definitions/react-create-class-assignment/output.json new file mode 100644 index 00000000000..353b2b3a8de --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/react-create-class-assignment/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "The is a component to test the document generation", + "displayName": "Component", + "methods": [] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_7.js b/packages/integration-tests/cases/js/definitions/react-create-class-variable/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_7.js rename to packages/integration-tests/cases/js/definitions/react-create-class-variable/index.js diff --git a/packages/integration-tests/cases/js/definitions/react-create-class-variable/output.json b/packages/integration-tests/cases/js/definitions/react-create-class-variable/output.json new file mode 100644 index 00000000000..353b2b3a8de --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/react-create-class-variable/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "The is a component to test the document generation", + "displayName": "Component", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/errors/missing-definition/error.json b/packages/integration-tests/cases/js/errors/missing-definition/error.json new file mode 100644 index 00000000000..ade7875a31f --- /dev/null +++ b/packages/integration-tests/cases/js/errors/missing-definition/error.json @@ -0,0 +1,3 @@ +{ + "code": "ERR_REACTDOCGEN_MISSING_DEFINITION" +} diff --git a/packages/integration-tests/cases/js/errors/missing-definition/index.jsx b/packages/integration-tests/cases/js/errors/missing-definition/index.jsx new file mode 100644 index 00000000000..64a32fd291e --- /dev/null +++ b/packages/integration-tests/cases/js/errors/missing-definition/index.jsx @@ -0,0 +1 @@ +export const answer = 42; diff --git a/packages/integration-tests/cases/js/errors/multiple-definitions/error.json b/packages/integration-tests/cases/js/errors/multiple-definitions/error.json new file mode 100644 index 00000000000..8a4d08b0f60 --- /dev/null +++ b/packages/integration-tests/cases/js/errors/multiple-definitions/error.json @@ -0,0 +1,3 @@ +{ + "code": "ERR_REACTDOCGEN_MULTIPLE_DEFINITIONS" +} diff --git a/packages/integration-tests/cases/js/errors/multiple-definitions/index.jsx b/packages/integration-tests/cases/js/errors/multiple-definitions/index.jsx new file mode 100644 index 00000000000..b7adebe5322 --- /dev/null +++ b/packages/integration-tests/cases/js/errors/multiple-definitions/index.jsx @@ -0,0 +1,7 @@ +export function First() { + return
; +} + +export function Second() { + return ; +} diff --git a/packages/integration-tests/cases/js/exports/commonjs-module/index.jsx b/packages/integration-tests/cases/js/exports/commonjs-module/index.jsx new file mode 100644 index 00000000000..5fc2fd63a87 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-module/index.jsx @@ -0,0 +1,11 @@ +const PropTypes = require('prop-types'); + +function CommonJsButton({ label }) { + return ; +} + +CommonJsButton.propTypes = { + label: PropTypes.string.isRequired, +}; + +module.exports = CommonJsButton; diff --git a/packages/integration-tests/cases/js/exports/commonjs-module/output.json b/packages/integration-tests/cases/js/exports/commonjs-module/output.json new file mode 100644 index 00000000000..324fe5f5c25 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-module/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "CommonJsButton", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/exports/commonjs-named/index.jsx b/packages/integration-tests/cases/js/exports/commonjs-named/index.jsx new file mode 100644 index 00000000000..3fcaf36dd31 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-named/index.jsx @@ -0,0 +1,9 @@ +const React = require('react'); + +class CommonJsClass extends React.Component { + render() { + return
; + } +} + +exports.CommonJsClass = CommonJsClass; diff --git a/packages/integration-tests/cases/js/exports/commonjs-named/output.json b/packages/integration-tests/cases/js/exports/commonjs-named/output.json new file mode 100644 index 00000000000..5a5f831830a --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-named/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": "CommonJsClass", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/exports/computed-commonjs/error.json b/packages/integration-tests/cases/js/exports/computed-commonjs/error.json new file mode 100644 index 00000000000..ade7875a31f --- /dev/null +++ b/packages/integration-tests/cases/js/exports/computed-commonjs/error.json @@ -0,0 +1,3 @@ +{ + "code": "ERR_REACTDOCGEN_MISSING_DEFINITION" +} diff --git a/packages/integration-tests/cases/js/exports/computed-commonjs/index.jsx b/packages/integration-tests/cases/js/exports/computed-commonjs/index.jsx new file mode 100644 index 00000000000..44a9e3ac7a0 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/computed-commonjs/index.jsx @@ -0,0 +1,7 @@ +const EXPORT_NAME = 'exports'; + +function ComputedCommonJs() { + return
; +} + +module[EXPORT_NAME] = ComputedCommonJs; diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_34.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_34.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_34.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_34.js diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_35.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_35.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_35.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_35.js diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_36.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_36.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_36.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_36.js diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_6.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_6.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_6.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_6.js diff --git a/packages/integration-tests/cases/js/imports/export-star-chain/index.js b/packages/integration-tests/cases/js/imports/export-star-chain/index.js new file mode 100644 index 00000000000..ae76d448c9f --- /dev/null +++ b/packages/integration-tests/cases/js/imports/export-star-chain/index.js @@ -0,0 +1,9 @@ +import {SuperCustomButton, sharedProps} from './component_35.js'; +import PropTypes from 'prop-types'; + +export function SuperDuperCustomButton({color, ...otherProps}) { + return ; +} + +SuperDuperCustomButton.propTypes = sharedProps; +export * from './component_35.js'; diff --git a/packages/integration-tests/cases/js/imports/export-star-chain/output.json b/packages/integration-tests/cases/js/imports/export-star-chain/output.json new file mode 100644 index 00000000000..0b23a1fefc7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/export-star-chain/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/index.jsx b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/index.jsx new file mode 100644 index 00000000000..543df50cc2b --- /dev/null +++ b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/index.jsx @@ -0,0 +1,17 @@ +import PropTypes from 'prop-types'; +import defaults, { choices } from './values.js'; + +export default function ImportedDefaultsAndEnums() { + return
; +} + +ImportedDefaultsAndEnums.propTypes = { + label: PropTypes.string, + count: PropTypes.number, + choice: PropTypes.oneOf(Object.values(choices)), +}; + +ImportedDefaultsAndEnums.defaultProps = { + ...defaults, + choice: choices.primary, +}; diff --git a/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/output.json b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/output.json new file mode 100644 index 00000000000..5a6986ee900 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/output.json @@ -0,0 +1,52 @@ +[ + { + "description": "", + "displayName": "ImportedDefaultsAndEnums", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'imported'", + "computed": false + } + }, + "count": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "3", + "computed": false + } + }, + "choice": { + "type": { + "name": "enum", + "value": [ + { + "value": "\"primary\"", + "computed": false + }, + { + "value": "\"secondary\"", + "computed": false + } + ] + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'primary'", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/values.js b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/values.js new file mode 100644 index 00000000000..08b93a8b088 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/values.js @@ -0,0 +1,9 @@ +export const choices = { + primary: 'primary', + secondary: 'secondary', +}; + +export default { + label: 'imported', + count: 3, +}; diff --git a/packages/integration-tests/cases/js/imports/member-proptypes/component_34.js b/packages/integration-tests/cases/js/imports/member-proptypes/component_34.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/member-proptypes/component_34.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_38.js b/packages/integration-tests/cases/js/imports/member-proptypes/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_38.js rename to packages/integration-tests/cases/js/imports/member-proptypes/index.js diff --git a/packages/integration-tests/cases/js/imports/member-proptypes/output.json b/packages/integration-tests/cases/js/imports/member-proptypes/output.json new file mode 100644 index 00000000000..0b23a1fefc7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/member-proptypes/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/namespace-reexport/component_34.js b/packages/integration-tests/cases/js/imports/namespace-reexport/component_34.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/namespace-reexport/component_34.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/imports/namespace-reexport/index.js b/packages/integration-tests/cases/js/imports/namespace-reexport/index.js new file mode 100644 index 00000000000..2c92127a749 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/namespace-reexport/index.js @@ -0,0 +1,9 @@ +import * as C36 from './component_36.js'; +import PropTypes from 'prop-types'; + +export function SuperDuperCustomButton({color, ...otherProps}) { + return ; +} + +SuperDuperCustomButton.propTypes = C36.sharedProps; +export {SuperCustomButton} from './component_36.js'; diff --git a/packages/integration-tests/cases/js/imports/namespace-reexport/output.json b/packages/integration-tests/cases/js/imports/namespace-reexport/output.json new file mode 100644 index 00000000000..0b23a1fefc7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/namespace-reexport/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/reexported-proptypes/component_34.js b/packages/integration-tests/cases/js/imports/reexported-proptypes/component_34.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/reexported-proptypes/component_34.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/imports/reexported-proptypes/index.js b/packages/integration-tests/cases/js/imports/reexported-proptypes/index.js new file mode 100644 index 00000000000..35aa85afaf7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/reexported-proptypes/index.js @@ -0,0 +1,10 @@ +import {CustomButton, sharedProps} from './component_34.js'; +import PropTypes from 'prop-types'; + +export function SuperCustomButton({color, ...otherProps}) { + return ; +} + +SuperCustomButton.propTypes = sharedProps; +export {sharedProps}; +export * from './component_36.js'; diff --git a/packages/integration-tests/cases/js/imports/reexported-proptypes/output.json b/packages/integration-tests/cases/js/imports/reexported-proptypes/output.json new file mode 100644 index 00000000000..f01edcd3b3e --- /dev/null +++ b/packages/integration-tests/cases/js/imports/reexported-proptypes/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/spread-proptypes/component_6.js b/packages/integration-tests/cases/js/imports/spread-proptypes/component_6.js new file mode 100644 index 00000000000..89355ab5f45 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/spread-proptypes/component_6.js @@ -0,0 +1,26 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +const Button = ({ children, onClick, style = {} }) => ( + +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/imports/spread-proptypes/index.js b/packages/integration-tests/cases/js/imports/spread-proptypes/index.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/spread-proptypes/index.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/props/package-proptypes-context/output.json b/packages/integration-tests/cases/js/props/package-proptypes-context/output.json new file mode 100644 index 00000000000..dc56f9d9334 --- /dev/null +++ b/packages/integration-tests/cases/js/props/package-proptypes-context/output.json @@ -0,0 +1,50 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "{}", + "computed": false + } + } + }, + "context": { + "config": { + "type": { + "name": "object" + }, + "required": false + } + }, + "childContext": { + "color": { + "type": { + "name": "string" + }, + "required": false + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_5.js b/packages/integration-tests/cases/js/props/react-proptypes-context/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_5.js rename to packages/integration-tests/cases/js/props/react-proptypes-context/index.js diff --git a/packages/integration-tests/cases/js/props/react-proptypes-context/output.json b/packages/integration-tests/cases/js/props/react-proptypes-context/output.json new file mode 100644 index 00000000000..dc56f9d9334 --- /dev/null +++ b/packages/integration-tests/cases/js/props/react-proptypes-context/output.json @@ -0,0 +1,50 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "{}", + "computed": false + } + } + }, + "context": { + "config": { + "type": { + "name": "object" + }, + "required": false + } + }, + "childContext": { + "color": { + "type": { + "name": "string" + }, + "required": false + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_17.js b/packages/integration-tests/cases/js/props/shape-exact-and-union/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_17.js rename to packages/integration-tests/cases/js/props/shape-exact-and-union/index.js diff --git a/packages/integration-tests/cases/js/props/shape-exact-and-union/output.json b/packages/integration-tests/cases/js/props/shape-exact-and-union/output.json new file mode 100644 index 00000000000..80a21cd55d5 --- /dev/null +++ b/packages/integration-tests/cases/js/props/shape-exact-and-union/output.json @@ -0,0 +1,61 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "shapeProp": { + "type": { + "name": "shape", + "value": { + "a": { + "name": "string", + "description": "Comment for property a", + "required": false + }, + "b": { + "name": "number", + "required": false + } + } + }, + "required": false, + "description": "" + }, + "exactProp": { + "type": { + "name": "exact", + "value": { + "c": { + "name": "string", + "description": "Comment for property c", + "required": false + }, + "d": { + "name": "number", + "required": false + } + } + }, + "required": false, + "description": "" + }, + "oneOfTypeProp": { + "type": { + "name": "union", + "value": [ + { + "name": "string", + "description": "Comment for type string" + }, + { + "name": "number" + } + ] + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_2.js b/packages/integration-tests/cases/js/regressions/class-static-getters/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_2.js rename to packages/integration-tests/cases/js/regressions/class-static-getters/index.js diff --git a/packages/integration-tests/cases/js/regressions/class-static-getters/output.json b/packages/integration-tests/cases/js/regressions/class-static-getters/output.json new file mode 100644 index 00000000000..2a033e80871 --- /dev/null +++ b/packages/integration-tests/cases/js/regressions/class-static-getters/output.json @@ -0,0 +1,37 @@ +[ + { + "description": "", + "displayName": "button", + "methods": [ + { + "name": "displayName", + "docblock": null, + "modifiers": [ + "static", + "get" + ], + "params": [], + "returns": null + }, + { + "name": "defaultProps", + "docblock": null, + "modifiers": [ + "static", + "get" + ], + "params": [], + "returns": null + } + ], + "props": { + "type": { + "defaultValue": { + "value": "\"primary\"", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_28.tsx b/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_28.tsx rename to packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/index.tsx diff --git a/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/output.json b/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/output.json new file mode 100644 index 00000000000..3f988b09614 --- /dev/null +++ b/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/output.json @@ -0,0 +1,20 @@ +[ + { + "description": "Example component description", + "displayName": "ABC", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "Example prop description", + "defaultValue": { + "value": "true", + "computed": false + } + } + } + } +] diff --git a/packages/typescript/src/__fixtures__/function-component.tsx b/packages/integration-tests/cases/typescript/defaults/function-default-parameters/index.tsx similarity index 100% rename from packages/typescript/src/__fixtures__/function-component.tsx rename to packages/integration-tests/cases/typescript/defaults/function-default-parameters/index.tsx diff --git a/packages/integration-tests/cases/typescript/defaults/function-default-parameters/output.json b/packages/integration-tests/cases/typescript/defaults/function-default-parameters/output.json new file mode 100644 index 00000000000..07f2a5e79be --- /dev/null +++ b/packages/integration-tests/cases/typescript/defaults/function-default-parameters/output.json @@ -0,0 +1,27 @@ +[ + { + "description": "Renders a button.", + "displayName": "Button", + "methods": [], + "props": { + "label": { + "description": "Text shown inside the button.", + "required": true, + "tsType": { + "name": "string" + } + }, + "disabled": { + "description": "Prevents interaction.", + "required": false, + "tsType": { + "name": "boolean" + }, + "defaultValue": { + "value": "false", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/class-without-id.tsx b/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/class-without-id.tsx rename to packages/integration-tests/cases/typescript/definitions/anonymous-default-class/index.tsx diff --git a/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/output.json b/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/output.json new file mode 100644 index 00000000000..f303d0fbc07 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/namespace-export.tsx b/packages/integration-tests/cases/typescript/exports/namespace-reexport/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/namespace-export.tsx rename to packages/integration-tests/cases/typescript/exports/namespace-reexport/index.tsx diff --git a/packages/integration-tests/cases/typescript/exports/namespace-reexport/output.json b/packages/integration-tests/cases/typescript/exports/namespace-reexport/output.json new file mode 100644 index 00000000000..f303d0fbc07 --- /dev/null +++ b/packages/integration-tests/cases/typescript/exports/namespace-reexport/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/support/other-exports.ts b/packages/integration-tests/cases/typescript/exports/namespace-reexport/support/other-exports.ts similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/support/other-exports.ts rename to packages/integration-tests/cases/typescript/exports/namespace-reexport/support/other-exports.ts diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_27.tsx b/packages/integration-tests/cases/typescript/imports/extended-props/component_27.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_27.tsx rename to packages/integration-tests/cases/typescript/imports/extended-props/component_27.tsx diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_39.tsx b/packages/integration-tests/cases/typescript/imports/extended-props/component_39.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_39.tsx rename to packages/integration-tests/cases/typescript/imports/extended-props/component_39.tsx diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_33.tsx b/packages/integration-tests/cases/typescript/imports/extended-props/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_33.tsx rename to packages/integration-tests/cases/typescript/imports/extended-props/index.tsx diff --git a/packages/integration-tests/cases/typescript/imports/extended-props/output.json b/packages/integration-tests/cases/typescript/imports/extended-props/output.json new file mode 100644 index 00000000000..085b2a81e74 --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/extended-props/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "This is a typescript component with imported prop types", + "displayName": "ImportedExtendedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + }, + "bar": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/imports/imported-props/component_27.tsx b/packages/integration-tests/cases/typescript/imports/imported-props/component_27.tsx new file mode 100644 index 00000000000..2b7ad0e8d30 --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/imported-props/component_27.tsx @@ -0,0 +1,35 @@ +import React, { Component } from 'react'; + +export interface Props { + foo: string +} + +/** + * This is a typescript class component + */ +export default class TSComponent extends Component { + render() { + return

Hello world

; + } + + /** + * This is a method + */ + foo(a: string): string { + return a; + } + + /** + * This is a public method + */ + public bar(a: string): string { + return a; + } + + /** + * This is a private method + */ + private baz(a: string): string { + return a; + } +} diff --git a/packages/integration-tests/cases/typescript/imports/imported-props/index.tsx b/packages/integration-tests/cases/typescript/imports/imported-props/index.tsx new file mode 100644 index 00000000000..32ca3239943 --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/imported-props/index.tsx @@ -0,0 +1,13 @@ +import React, { Component } from 'react'; +import { Props as ImportedProps } from './component_27.jsx'; + +export default interface ExtendedProps extends ImportedProps { + bar: number +} + +/** + * This is a typescript component with imported prop types + */ +export function ImportedComponent(props: ImportedProps) { + return

Hello world

; +} diff --git a/packages/integration-tests/cases/typescript/imports/imported-props/output.json b/packages/integration-tests/cases/typescript/imports/imported-props/output.json new file mode 100644 index 00000000000..5c8b99c401b --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/imported-props/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "This is a typescript component with imported prop types", + "displayName": "ImportedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/test-all-imports.tsx b/packages/integration-tests/cases/typescript/imports/reexported-default-values/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/test-all-imports.tsx rename to packages/integration-tests/cases/typescript/imports/reexported-default-values/index.tsx diff --git a/packages/integration-tests/cases/typescript/imports/reexported-default-values/output.json b/packages/integration-tests/cases/typescript/imports/reexported-default-values/output.json new file mode 100644 index 00000000000..76bdad981fe --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/reexported-default-values/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "This is a TS component with imported stuff", + "displayName": "ImportedExtendedComponent", + "methods": [], + "props": { + "x": { + "defaultValue": { + "value": "\"string\"", + "computed": false + }, + "required": false + }, + "y": { + "defaultValue": { + "value": "'otherstring'", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/other-exports.ts b/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/other-exports.ts new file mode 100644 index 00000000000..129c265f93d --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/other-exports.ts @@ -0,0 +1 @@ +export default 'otherstring' diff --git a/packages/react-docgen/tests/integration/__fixtures__/support/some-exports.ts b/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/some-exports.ts similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/support/some-exports.ts rename to packages/integration-tests/cases/typescript/imports/reexported-default-values/support/some-exports.ts diff --git a/packages/integration-tests/cases/typescript/methods/class-methods/index.tsx b/packages/integration-tests/cases/typescript/methods/class-methods/index.tsx new file mode 100644 index 00000000000..2b7ad0e8d30 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/class-methods/index.tsx @@ -0,0 +1,35 @@ +import React, { Component } from 'react'; + +export interface Props { + foo: string +} + +/** + * This is a typescript class component + */ +export default class TSComponent extends Component { + render() { + return

Hello world

; + } + + /** + * This is a method + */ + foo(a: string): string { + return a; + } + + /** + * This is a public method + */ + public bar(a: string): string { + return a; + } + + /** + * This is a private method + */ + private baz(a: string): string { + return a; + } +} diff --git a/packages/integration-tests/cases/typescript/methods/class-methods/output.json b/packages/integration-tests/cases/typescript/methods/class-methods/output.json new file mode 100644 index 00000000000..a96a47e1275 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/class-methods/output.json @@ -0,0 +1,57 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [ + { + "name": "foo", + "docblock": "This is a method", + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "This is a method" + }, + { + "name": "bar", + "docblock": "This is a public method", + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "This is a public method" + } + ], + "props": { + "foo": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/methods/modifiers-and-types/index.tsx b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/index.tsx new file mode 100644 index 00000000000..7e6e52fe5a0 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/index.tsx @@ -0,0 +1,34 @@ +import React from 'react'; + +interface Props { + value: string; +} + +export default class TypedMethods extends React.Component { + /** Static helper. */ + static utility(value: number): string { + return String(value); + } + + /** Loads one value. */ + async load(value: string): Promise { + return value; + } + + /** Produces values. */ + *items(count: number): Generator { + yield count; + } + + /** Computed method. */ + ['computed'](enabled?: boolean): boolean { + return enabled ?? false; + } + + /** Arrow property. */ + arrow = (value: number): string => String(value); + + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/methods/modifiers-and-types/output.json b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/output.json new file mode 100644 index 00000000000..bd71645edb3 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/output.json @@ -0,0 +1,135 @@ +[ + { + "description": "", + "displayName": "TypedMethods", + "methods": [ + { + "name": "utility", + "docblock": "Static helper.", + "modifiers": [ + "static" + ], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "number" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "Static helper." + }, + { + "name": "load", + "docblock": "Loads one value.", + "modifiers": [ + "async" + ], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "Promise", + "elements": [ + { + "name": "string" + } + ], + "raw": "Promise" + } + }, + "description": "Loads one value." + }, + { + "name": "items", + "docblock": "Produces values.", + "modifiers": [ + "generator" + ], + "params": [ + { + "name": "count", + "optional": false, + "type": { + "name": "number" + } + } + ], + "returns": { + "type": { + "name": "Generator", + "elements": [ + { + "name": "number" + } + ], + "raw": "Generator" + } + }, + "description": "Produces values." + }, + { + "name": "computed", + "docblock": "Computed method.", + "modifiers": [], + "params": [ + { + "name": "enabled", + "optional": true, + "type": { + "name": "boolean" + } + } + ], + "returns": { + "type": { + "name": "boolean" + } + }, + "description": "Computed method." + }, + { + "name": "arrow", + "docblock": "Arrow property.", + "modifiers": [], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "number" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "Arrow property." + } + ], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_43.tsx b/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_43.tsx rename to packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/index.tsx diff --git a/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/output.json b/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/output.json new file mode 100644 index 00000000000..0cc94b7fa1c --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/output.json @@ -0,0 +1,37 @@ +[ + { + "description": "", + "displayName": "MenuItem", + "methods": [], + "props": { + "children": { + "type": { + "name": "node" + }, + "required": false, + "description": "Menu item contents." + }, + "classes": { + "type": { + "name": "object" + }, + "required": false, + "description": "Override or extend the styles applied to the component. See CSS API below for more details." + }, + "component": { + "defaultValue": { + "value": "'li'", + "computed": false + }, + "required": false + }, + "disableGutters": { + "defaultValue": { + "value": "false", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/types/advanced-props/index.tsx b/packages/integration-tests/cases/typescript/types/advanced-props/index.tsx new file mode 100644 index 00000000000..b453a3bc5f6 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/advanced-props/index.tsx @@ -0,0 +1,41 @@ +import type * as React from 'react'; + +const values = { first: 'one', second: 'two' } as const; +type Values = typeof values; +type Action = { subAction?: Action }; + +interface IndexedInterface { + x: string; +} + +interface Callable { + (value: string): number; + [key: string]: unknown; + method(value: number): void; +} + +interface Props { + keys: keyof Values; + value: Values[keyof Values]; + mapped: { [Key in keyof Values]?: Values[Key] }; + children: React.ReactNode; + component: React.ComponentType<{ enabled: boolean }>; + callable: Callable; + rest: (...values: string[]) => void; + neverValue: never; + nullValue: null; + undefinedValue: undefined; + symbolValue: symbol; + objectValue: object; + action: Action; + interfaceIndex: IndexedInterface['x']; + qualifiedTypeof: typeof values.first; + inlineKeys: keyof { apple: string; banana: string }; + ref: React.Ref; + childrenArray: React.ChildrenArray; +} + +/** Exercises advanced TypeScript prop type extraction. */ +export function AdvancedTypeScriptTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/types/advanced-props/output.json b/packages/integration-tests/cases/typescript/types/advanced-props/output.json new file mode 100644 index 00000000000..2462c800c6b --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/advanced-props/output.json @@ -0,0 +1,231 @@ +[ + { + "description": "Exercises advanced TypeScript prop type extraction.", + "displayName": "AdvancedTypeScriptTypes", + "methods": [], + "props": { + "keys": { + "required": true, + "tsType": { + "name": "values" + }, + "description": "" + }, + "value": { + "required": true, + "tsType": { + "name": "values[values]", + "raw": "Values[keyof Values]" + }, + "description": "" + }, + "mapped": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{ [Key in keyof Values]?: Values[Key] }", + "signature": { + "properties": [ + { + "key": { + "name": "values", + "required": false + }, + "value": { + "name": "values[Key]", + "raw": "Values[Key]" + } + } + ] + } + }, + "description": "" + }, + "children": { + "required": true, + "tsType": { + "name": "ReactReactNode", + "raw": "React.ReactNode" + }, + "description": "" + }, + "component": { + "required": true, + "tsType": { + "name": "ReactComponentType", + "raw": "React.ComponentType<{ enabled: boolean }>", + "elements": [ + { + "name": "signature", + "type": "object", + "raw": "{ enabled: boolean }", + "signature": { + "properties": [ + { + "key": "enabled", + "value": { + "name": "boolean", + "required": true + } + } + ] + } + } + ] + }, + "description": "" + }, + "callable": { + "required": true, + "tsType": { + "name": "Callable" + }, + "description": "" + }, + "rest": { + "required": true, + "tsType": { + "name": "signature", + "type": "function", + "raw": "(...values: string[]) => void", + "signature": { + "arguments": [ + { + "type": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "string[]" + }, + "name": "values", + "rest": true + } + ], + "return": { + "name": "void" + } + } + }, + "description": "" + }, + "neverValue": { + "required": true, + "tsType": { + "name": "never" + }, + "description": "" + }, + "nullValue": { + "required": true, + "tsType": { + "name": "null" + }, + "description": "" + }, + "undefinedValue": { + "required": true, + "tsType": { + "name": "undefined" + }, + "description": "" + }, + "symbolValue": { + "required": true, + "tsType": { + "name": "symbol" + }, + "description": "" + }, + "objectValue": { + "required": true, + "tsType": { + "name": "object" + }, + "description": "" + }, + "action": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{ subAction?: Action }", + "signature": { + "properties": [ + { + "key": "subAction", + "value": { + "name": "Action", + "required": false + } + } + ] + } + }, + "description": "" + }, + "interfaceIndex": { + "required": true, + "tsType": { + "name": "IndexedInterface['x']", + "raw": "IndexedInterface['x']" + }, + "description": "" + }, + "qualifiedTypeof": { + "required": true, + "tsType": { + "name": "values.first" + }, + "description": "" + }, + "inlineKeys": { + "required": true, + "tsType": { + "name": "union", + "raw": "keyof { apple: string; banana: string }", + "elements": [ + { + "name": "literal", + "value": "apple" + }, + { + "name": "literal", + "value": "banana" + } + ] + }, + "description": "" + }, + "ref": { + "required": true, + "tsType": { + "name": "ReactRef", + "raw": "React.Ref", + "elements": [ + { + "name": "AdvancedTypeScriptTypes" + } + ] + }, + "description": "" + }, + "childrenArray": { + "required": true, + "tsType": { + "name": "ReactChildrenArray", + "raw": "React.ChildrenArray", + "elements": [ + { + "name": "string" + } + ] + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/types/comprehensive-props/index.tsx b/packages/integration-tests/cases/typescript/types/comprehensive-props/index.tsx new file mode 100644 index 00000000000..f9cbb26f272 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/comprehensive-props/index.tsx @@ -0,0 +1,27 @@ +const status = 'ready' as const; + +type Pair = [string, number]; + +interface Props { + anything: any; + unknownValue: unknown; + text: string; + count: number; + enabled: boolean; + literal: 'small'; + union: string | number; + intersection: { left: string } & { right: number }; + list: string[]; + readonlyList: ReadonlyArray; + pair: Pair; + callback: (value: string) => boolean; + nested: { value?: string }; + record: Record; + status: typeof status; + optional?: string; +} + +/** Exercises TypeScript prop type extraction. */ +export function TypeScriptTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/types/comprehensive-props/output.json b/packages/integration-tests/cases/typescript/types/comprehensive-props/output.json new file mode 100644 index 00000000000..6f3df955808 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/comprehensive-props/output.json @@ -0,0 +1,224 @@ +[ + { + "description": "Exercises TypeScript prop type extraction.", + "displayName": "TypeScriptTypes", + "methods": [], + "props": { + "anything": { + "required": true, + "tsType": { + "name": "any" + }, + "description": "" + }, + "unknownValue": { + "required": true, + "tsType": { + "name": "unknown" + }, + "description": "" + }, + "text": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + }, + "count": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + }, + "enabled": { + "required": true, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "literal": { + "required": true, + "tsType": { + "name": "literal", + "value": "'small'" + }, + "description": "" + }, + "union": { + "required": true, + "tsType": { + "name": "union", + "raw": "string | number", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "intersection": { + "required": true, + "tsType": { + "name": "intersection", + "raw": "{ left: string } & { right: number }", + "elements": [ + { + "name": "signature", + "type": "object", + "raw": "{ left: string }", + "signature": { + "properties": [ + { + "key": "left", + "value": { + "name": "string", + "required": true + } + } + ] + } + }, + { + "name": "signature", + "type": "object", + "raw": "{ right: number }", + "signature": { + "properties": [ + { + "key": "right", + "value": { + "name": "number", + "required": true + } + } + ] + } + } + ] + }, + "description": "" + }, + "list": { + "required": true, + "tsType": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "string[]" + }, + "description": "" + }, + "readonlyList": { + "required": true, + "tsType": { + "name": "ReadonlyArray", + "elements": [ + { + "name": "number" + } + ], + "raw": "ReadonlyArray" + }, + "description": "" + }, + "pair": { + "required": true, + "tsType": { + "name": "tuple", + "raw": "[string, number]", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "callback": { + "required": true, + "tsType": { + "name": "signature", + "type": "function", + "raw": "(value: string) => boolean", + "signature": { + "arguments": [ + { + "type": { + "name": "string" + }, + "name": "value" + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "nested": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{ value?: string }", + "signature": { + "properties": [ + { + "key": "value", + "value": { + "name": "string", + "required": false + } + } + ] + } + }, + "description": "" + }, + "record": { + "required": true, + "tsType": { + "name": "Record", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ], + "raw": "Record" + }, + "description": "" + }, + "status": { + "required": true, + "tsType": { + "name": "status" + }, + "description": "" + }, + "optional": { + "required": false, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_25.tsx b/packages/integration-tests/cases/typescript/types/generic-interface-extension/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_25.tsx rename to packages/integration-tests/cases/typescript/types/generic-interface-extension/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/generic-interface-extension/output.json b/packages/integration-tests/cases/typescript/types/generic-interface-extension/output.json new file mode 100644 index 00000000000..6ede61fa6e6 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/generic-interface-extension/output.json @@ -0,0 +1,36 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "Child" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "tsType": { + "name": "Array", + "elements": [ + { + "name": "Child" + } + ], + "raw": "Array" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "Complex union prop" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_41.tsx b/packages/integration-tests/cases/typescript/types/indexed-access-constant/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_41.tsx rename to packages/integration-tests/cases/typescript/types/indexed-access-constant/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/indexed-access-constant/output.json b/packages/integration-tests/cases/typescript/types/indexed-access-constant/output.json new file mode 100644 index 00000000000..7c633606c59 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/indexed-access-constant/output.json @@ -0,0 +1,17 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": false, + "tsType": { + "name": "STRING_VALS[number]", + "raw": "typeof STRING_VALS[number]" + }, + "description": "String value of a number" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_23.tsx b/packages/integration-tests/cases/typescript/types/interface-composition/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_23.tsx rename to packages/integration-tests/cases/typescript/types/interface-composition/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/interface-composition/output.json b/packages/integration-tests/cases/typescript/types/interface-composition/output.json new file mode 100644 index 00000000000..de43d447e5a --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/interface-composition/output.json @@ -0,0 +1,66 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "string" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "tsType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "Complex union prop" + } + }, + "composes": [ + "OtherProps" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_22.tsx b/packages/integration-tests/cases/typescript/types/nested-object-and-union/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_22.tsx rename to packages/integration-tests/cases/typescript/types/nested-object-and-union/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/nested-object-and-union/output.json b/packages/integration-tests/cases/typescript/types/nested-object-and-union/output.json new file mode 100644 index 00000000000..9761e87349a --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/nested-object-and-union/output.json @@ -0,0 +1,92 @@ +[ + { + "description": "This is a TypeScript function component", + "displayName": "TSFunctionComponent", + "methods": [], + "props": { + "align": { + "required": false, + "tsType": { + "name": "union", + "raw": "\"left\" | \"center\" | \"right\" | \"justify\"", + "elements": [ + { + "name": "literal", + "value": "\"left\"" + }, + { + "name": "literal", + "value": "\"center\"" + }, + { + "name": "literal", + "value": "\"right\"" + }, + { + "name": "literal", + "value": "\"justify\"" + } + ] + }, + "description": "" + }, + "left": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "center": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "right": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "justify": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "position": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{\n /**\n * x coordinate doc\n */\n x: number,\n /**\n * y coordinate doc\n */\n y: number\n}", + "signature": { + "properties": [ + { + "key": "x", + "value": { + "name": "number", + "required": true + }, + "description": "x coordinate doc" + }, + { + "key": "y", + "value": { + "name": "number", + "required": true + }, + "description": "y coordinate doc" + } + ] + } + }, + "description": "position doc" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/types/react-prop-wrappers/index.tsx b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/index.tsx new file mode 100644 index 00000000000..f5bbe978c28 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/index.tsx @@ -0,0 +1,15 @@ +import type * as React from 'react'; + +interface Props { + /** Required label. */ + label: string; +} + +/** Exercises nested built-in React prop wrappers. */ +export function WrappedPropsComponent( + _props: React.PropsWithChildren< + React.PropsWithRef> + >, +) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/types/react-prop-wrappers/output.json b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/output.json new file mode 100644 index 00000000000..a20710f8343 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "Exercises nested built-in React prop wrappers.", + "displayName": "WrappedPropsComponent", + "methods": [], + "props": { + "label": { + "description": "Required label.", + "required": true, + "tsType": { + "name": "string" + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_21.tsx b/packages/integration-tests/cases/typescript/types/type-alias-intersection/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_21.tsx rename to packages/integration-tests/cases/typescript/types/type-alias-intersection/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/type-alias-intersection/output.json b/packages/integration-tests/cases/typescript/types/type-alias-intersection/output.json new file mode 100644 index 00000000000..8bb04a69d22 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/type-alias-intersection/output.json @@ -0,0 +1,63 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "string" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "tsType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "Complex union prop" + } + } + } +] diff --git a/packages/integration-tests/package.json b/packages/integration-tests/package.json new file mode 100644 index 00000000000..a7fbe1e3de6 --- /dev/null +++ b/packages/integration-tests/package.json @@ -0,0 +1,23 @@ +{ + "name": "@react-docgen-internal/integration-tests", + "version": "0.0.0", + "private": true, + "description": "Shared integration fixtures for react-docgen parsers.", + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "cases", + "dist" + ], + "scripts": { + "build": "rimraf dist/ && tsc" + }, + "license": "MIT" +} diff --git a/packages/integration-tests/src/index.ts b/packages/integration-tests/src/index.ts new file mode 100644 index 00000000000..41773a94182 --- /dev/null +++ b/packages/integration-tests/src/index.ts @@ -0,0 +1,146 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const languages = ['flow', 'js', 'typescript'] as const; +const features = [ + 'defaults', + 'definitions', + 'documentation', + 'errors', + 'exports', + 'imports', + 'methods', + 'props', + 'regressions', + 'types', +] as const; +const entryPattern = /^index\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx)$/; + +export type IntegrationLanguage = (typeof languages)[number]; + +export interface IntegrationError { + code: string; +} + +export interface IntegrationCase { + directory: string; + error?: IntegrationError; + feature: string; + filename: string; + id: string; + language: IntegrationLanguage; + output?: unknown; + source: string; +} + +export interface LoadIntegrationCasesOptions { + ids?: readonly string[]; + languages?: readonly IntegrationLanguage[]; +} + +export const casesRoot = fileURLToPath(new URL('../cases', import.meta.url)); + +function directories(directory: string): string[] { + return fs + .readdirSync(directory, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort(); +} + +function readJson(filename: string): unknown { + return JSON.parse(fs.readFileSync(filename, 'utf8')) as unknown; +} + +function loadCase( + language: IntegrationLanguage, + feature: string, + name: string, +): IntegrationCase { + const directory = path.join(casesRoot, language, feature, name); + const files = fs.readdirSync(directory); + const entries = files.filter((file) => entryPattern.test(file)); + const outcomes = files.filter( + (file) => file === 'error.json' || file === 'output.json', + ); + + if (entries.length !== 1) { + throw new Error( + `Integration case "${language}/${feature}/${name}" must contain exactly one index source file.`, + ); + } + + if (outcomes.length !== 1) { + throw new Error( + `Integration case "${language}/${feature}/${name}" must contain exactly one output.json or error.json.`, + ); + } + + const [entry] = entries; + const [outcome] = outcomes; + + if (entry === undefined || outcome === undefined) { + throw new Error( + `Invalid integration case "${language}/${feature}/${name}".`, + ); + } + + const id = `${language}/${feature}/${name}`; + const filename = path.join(directory, entry); + + return { + directory, + feature, + filename, + id, + language, + source: fs.readFileSync(filename, 'utf8'), + ...(outcome === 'output.json' + ? { output: readJson(path.join(directory, outcome)) } + : { + error: readJson(path.join(directory, outcome)) as IntegrationError, + }), + }; +} + +export function loadIntegrationCases( + options: LoadIntegrationCasesOptions = {}, +): IntegrationCase[] { + const selectedLanguages = options.languages ?? languages; + const selectedIds = options.ids ? new Set(options.ids) : null; + const cases: IntegrationCase[] = []; + + for (const language of selectedLanguages) { + if (!(languages as readonly string[]).includes(language)) { + throw new Error(`Unknown integration language "${language}".`); + } + + for (const feature of directories(path.join(casesRoot, language))) { + if (!(features as readonly string[]).includes(feature)) { + throw new Error( + `Unknown integration feature "${language}/${feature}".`, + ); + } + + for (const name of directories(path.join(casesRoot, language, feature))) { + const integrationCase = loadCase(language, feature, name); + + if (!selectedIds || selectedIds.has(integrationCase.id)) { + cases.push(integrationCase); + } + } + } + } + + if (selectedIds) { + const foundIds = new Set(cases.map(({ id }) => id)); + const missingIds = [...selectedIds].filter((id) => !foundIds.has(id)); + + if (missingIds.length > 0) { + throw new Error(`Unknown integration cases: ${missingIds.join(', ')}.`); + } + } + + return cases; +} diff --git a/packages/integration-tests/tsconfig.json b/packages/integration-tests/tsconfig.json new file mode 100644 index 00000000000..4bf5c24a4f1 --- /dev/null +++ b/packages/integration-tests/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"] +} diff --git a/packages/react-docgen/package.json b/packages/react-docgen/package.json index 7fce579d521..8dc16cf259a 100644 --- a/packages/react-docgen/package.json +++ b/packages/react-docgen/package.json @@ -53,5 +53,8 @@ "doctrine": "^3.0.0", "resolve": "^1.22.1", "strip-indent": "^4.0.0" + }, + "devDependencies": { + "@react-docgen-internal/integration-tests": "workspace:*" } } diff --git a/packages/react-docgen/tests/integration/__snapshots__/integration-test.ts.snap b/packages/react-docgen/tests/integration/__snapshots__/integration-test.ts.snap deleted file mode 100644 index 9e4ece0c25a..00000000000 --- a/packages/react-docgen/tests/integration/__snapshots__/integration-test.ts.snap +++ /dev/null @@ -1,2165 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`integration > fixtures > processes component "class-without-id.tsx" without errors 1`] = ` -[ - { - "description": "", - "methods": [], - "props": { - "value": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_1.js" without errors 1`] = ` -[ - { - "description": "The is a component to test the document generation", - "displayName": "Component", - "methods": [], - }, -] -`; - -exports[`integration > fixtures > processes component "component_2.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "button", - "methods": [ - { - "docblock": null, - "modifiers": [ - "static", - "get", - ], - "name": "displayName", - "params": [], - "returns": null, - }, - { - "docblock": null, - "modifiers": [ - "static", - "get", - ], - "name": "defaultProps", - "params": [], - "returns": null, - }, - ], - "props": { - "type": { - "defaultValue": { - "computed": false, - "value": ""primary"", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_3.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Test", - "methods": [], - "props": { - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_4.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Parent", - "methods": [], - "props": { - "child": { - "description": "", - "required": true, - "type": { - "computed": true, - "name": "shape", - "value": "Child.propTypes", - }, - }, - "childExact": { - "description": "", - "required": true, - "type": { - "computed": true, - "name": "exact", - "value": "Child.propTypes", - }, - }, - "extendedChild": { - "description": "", - "required": true, - "type": { - "name": "shape", - "value": { - "adopted": { - "name": "bool", - "required": true, - }, - }, - }, - }, - "extendedChildExact": { - "description": "", - "required": true, - "type": { - "name": "exact", - "value": { - "adopted": { - "name": "bool", - "required": true, - }, - }, - }, - }, - "something": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_5.js" without errors 1`] = ` -[ - { - "childContext": { - "color": { - "required": false, - "type": { - "name": "string", - }, - }, - }, - "context": { - "config": { - "required": false, - "type": { - "name": "object", - }, - }, - }, - "description": "", - "displayName": "Button", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "defaultValue": { - "computed": false, - "value": "{}", - }, - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_6.js" without errors 1`] = ` -[ - { - "childContext": { - "color": { - "required": false, - "type": { - "name": "string", - }, - }, - }, - "context": { - "config": { - "required": false, - "type": { - "name": "object", - }, - }, - }, - "description": "", - "displayName": "Button", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "defaultValue": { - "computed": false, - "value": "{}", - }, - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_7.js" without errors 1`] = ` -[ - { - "description": "The is a component to test the document generation", - "displayName": "Component", - "methods": [], - }, -] -`; - -exports[`integration > fixtures > processes component "component_8.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Parent", - "methods": [ - { - "docblock": null, - "modifiers": [], - "name": "onChangeSlider", - "params": [ - { - "name": "[min, max]", - "optional": false, - "type": null, - }, - ], - "returns": null, - }, - ], - }, -] -`; - -exports[`integration > fixtures > processes component "component_9.js" without errors 1`] = ` -[ - { - "description": "Should be recognized as component.", - "displayName": "ExampleComponent", - "methods": [], - }, -] -`; - -exports[`integration > fixtures > processes component "component_10.js" without errors 1`] = ` -[ - { - "description": "React component that display current time at current location.", - "displayName": "Clock", - "methods": [ - { - "description": "Update clock state with new time", - "docblock": "Update clock state with new time", - "modifiers": [], - "name": "updateClock", - "params": [], - "returns": null, - }, - { - "description": "Parse current Date object", - "docblock": "Parse current Date object - -@returns {Object} currentTime - @returns {int} currentTime.hour - @returns {int} currentTime.minutes - @returns {string} currentTime.ampm "am" or "pm" - @returns {string} currentTime.dayOfWeek - @returns {string} currentTime.month - @returns {int} currentTime.date", - "modifiers": [], - "name": "getTime", - "params": [], - "returns": { - "description": "currentTime", - "type": { - "name": "Object", - }, - }, - }, - { - "description": "Update current clock for every 1 second", - "docblock": "Update current clock for every 1 second", - "modifiers": [], - "name": "setTimer", - "params": [], - "returns": null, - }, - ], - "props": { - "title": { - "description": "A text display current's user identity, - "Nobody" if no one is detected in the background, - "Hi, ..name" if an user is detected", - "required": false, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_11.js" without errors 1`] = ` -[ - { - "composes": [ - "OtherProps", - ], - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "fooProp": { - "description": "fooProp is spread in from a locally resolved type", - "flowType": { - "name": "string", - }, - "required": false, - }, - "prop1": { - "description": "The first prop", - "flowType": { - "name": "string", - }, - "required": true, - }, - "prop2": { - "description": "The second, covariant prop", - "flowType": { - "name": "number", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_12.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Paper", - "methods": [], - "props": { - "anchorOrigin": { - "defaultValue": { - "computed": false, - "value": "{ - vertical: 'top', - horizontal: 'left', -}", - }, - "description": "This is the point on the anchor where the popover's -\`anchorEl\` will attach to. This is not used when the -anchorReference is 'anchorPosition'. - -Options: -vertical: [top, center, bottom]; -horizontal: [left, center, right].", - "flowType": { - "name": "signature", - "raw": "{ - horizontal: 'left' | 'center' | 'right' | number, - vertical: 'top' | 'center' | 'bottom' | number, -}", - "signature": { - "properties": [ - { - "key": "horizontal", - "value": { - "elements": [ - { - "name": "literal", - "value": "'left'", - }, - { - "name": "literal", - "value": "'center'", - }, - { - "name": "literal", - "value": "'right'", - }, - { - "name": "number", - }, - ], - "name": "union", - "raw": "'left' | 'center' | 'right' | number", - "required": true, - }, - }, - { - "key": "vertical", - "value": { - "elements": [ - { - "name": "literal", - "value": "'top'", - }, - { - "name": "literal", - "value": "'center'", - }, - { - "name": "literal", - "value": "'bottom'", - }, - { - "name": "number", - }, - ], - "name": "union", - "raw": "'top' | 'center' | 'bottom' | number", - "required": true, - }, - }, - ], - }, - "type": "object", - }, - "required": false, - }, - "children": { - "description": "@ignore", - "flowType": { - "name": "Node", - }, - "required": false, - }, - "classes": { - "description": "Useful to extend the style applied to components.", - "flowType": { - "name": "Object", - }, - "required": false, - }, - "component": { - "defaultValue": { - "computed": false, - "value": "'div'", - }, - "description": "The component used for the root node. -This currently has to be flow cast in defaultProps as of flow 0.59.0", - "flowType": { - "name": "ElementType", - }, - "required": false, - }, - "elevation": { - "defaultValue": { - "computed": false, - "value": "2", - }, - "description": "Shadow depth, corresponds to \`dp\` in the spec. -It's accepting values between 0 and 24 inclusive.", - "flowType": { - "name": "number", - }, - "required": false, - }, - "labelRowsPerPage": { - "defaultValue": { - "computed": false, - "value": "'Rows per page:'", - }, - "description": "Useful to customize the rows per page label. Invoked with a \`{ from, to, count, page }\` -object.", - "flowType": { - "name": "Node", - }, - "required": false, - }, - "timeout": { - "defaultValue": { - "computed": false, - "value": "300", - }, - "description": "The duration for the transition, in milliseconds. -You may specify a single timeout for all transitions, or individually with an object. - -Set to 'auto' to automatically calculate transition time based on height.", - "flowType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - "required": false, - }, - "transition": { - "description": "Transition component.", - "flowType": { - "elements": [ - { - "name": "unknown", - }, - ], - "name": "ComponentType", - "raw": "ComponentType<*>", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_13.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "RootComponent": { - "description": "", - "flowType": { - "name": "ReactElementType", - "raw": "React.ElementType", - }, - "required": false, - }, - "align": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""left"", - }, - { - "name": "literal", - "value": ""center"", - }, - { - "name": "literal", - "value": ""right"", - }, - { - "name": "literal", - "value": ""justify"", - }, - ], - "name": "union", - "raw": ""left" | "center" | "right" | "justify"", - }, - "required": false, - }, - "capitalize": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "center": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "children": { - "description": "", - "flowType": { - "name": "ReactNode", - "raw": "React.Node", - }, - "required": false, - }, - "className": { - "description": "", - "flowType": { - "name": "string", - }, - "required": false, - }, - "color": { - "description": "", - "flowType": { - "name": "string", - }, - "required": false, - }, - "justify": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leading": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""none"", - }, - { - "name": "literal", - "value": ""tight"", - }, - { - "name": "literal", - "value": ""normal"", - }, - { - "name": "literal", - "value": ""loose"", - }, - ], - "name": "union", - "raw": ""none" | "tight" | "normal" | "loose"", - }, - "required": false, - }, - "leadingLoose": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leadingNone": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leadingNormal": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leadingTight": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "left": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "lowercase": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "muted": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "right": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "size": { - "description": "", - "flowType": { - "name": "string", - }, - "required": false, - }, - "tracking": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""tight"", - }, - { - "name": "literal", - "value": ""normal"", - }, - { - "name": "literal", - "value": ""wide"", - }, - ], - "name": "union", - "raw": ""tight" | "normal" | "wide"", - }, - "required": false, - }, - "trackingNormal": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "trackingTight": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "trackingWide": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "transform": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""lowercase"", - }, - { - "name": "literal", - "value": ""uppercase"", - }, - { - "name": "literal", - "value": ""capitalize"", - }, - ], - "name": "union", - "raw": ""lowercase" | "uppercase" | "capitalize"", - }, - "required": false, - }, - "uppercase": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "wrap": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_14.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "UncoloredView", - "methods": [], - "props": { - "color": { - "description": "", - "flowType": { - "name": "string", - "nullable": true, - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_15.js" without errors 1`] = ` -[ - { - "composes": [ - "BarProps", - "BarProps2", - "BarProps3", - ], - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "other": { - "description": "", - "flowType": { - "name": "literal", - "value": "'a'", - }, - "required": true, - }, - "other2": { - "description": "", - "flowType": { - "name": "literal", - "value": "'b'", - }, - "required": true, - }, - "other3": { - "description": "", - "flowType": { - "name": "literal", - "value": "'c'", - }, - "required": true, - }, - "other4": { - "description": "", - "flowType": { - "name": "literal", - "value": "'g'", - }, - "required": true, - }, - "other5": { - "description": "", - "flowType": { - "name": "literal", - "value": "'f'", - }, - "required": true, - }, - "somePropOverride": { - "description": "", - "flowType": { - "name": "literal", - "value": "'baz'", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_16.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "bar": { - "defaultValue": { - "computed": false, - "value": "null", - }, - "description": "This does something.", - "required": false, - "type": { - "name": "custom", - "raw": "PropTypes.node", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_17.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "exactProp": { - "description": "", - "required": false, - "type": { - "name": "exact", - "value": { - "c": { - "description": "Comment for property c", - "name": "string", - "required": false, - }, - "d": { - "name": "number", - "required": false, - }, - }, - }, - }, - "oneOfTypeProp": { - "description": "", - "required": false, - "type": { - "name": "union", - "value": [ - { - "description": "Comment for type string", - "name": "string", - }, - { - "name": "number", - }, - ], - }, - }, - "shapeProp": { - "description": "", - "required": false, - "type": { - "name": "shape", - "value": { - "a": { - "description": "Comment for property a", - "name": "string", - "required": false, - }, - "b": { - "name": "number", - "required": false, - }, - }, - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_18.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "UncoloredView", - "methods": [], - "props": { - "color": { - "description": "", - "flowType": { - "name": "string", - "nullable": true, - }, - "required": false, - "type": { - "name": "string", - }, - }, - "id": { - "defaultValue": { - "computed": false, - "value": "'test-forward-ref-default'", - }, - "description": "", - "required": false, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_19.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Component", - "methods": [], - "props": { - "data": { - "description": "", - "flowType": { - "elements": [ - { - "name": "mixed", - }, - ], - "name": "Array", - "raw": "Array", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_20.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Button", - "methods": [], - "props": { - "@computed#children": { - "defaultValue": { - "computed": false, - "value": ""default"", - }, - "description": "This is a test", - "required": false, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_21.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "required": true, - "tsType": { - "name": "number", - }, - }, - "baz": { - "description": "Complex union prop", - "required": true, - "tsType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - }, - "foo": { - "description": "Optional prop", - "required": false, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_22.tsx" without errors 1`] = ` -[ - { - "description": "This is a TypeScript function component", - "displayName": "TSFunctionComponent", - "methods": [], - "props": { - "align": { - "description": "", - "required": false, - "tsType": { - "elements": [ - { - "name": "literal", - "value": ""left"", - }, - { - "name": "literal", - "value": ""center"", - }, - { - "name": "literal", - "value": ""right"", - }, - { - "name": "literal", - "value": ""justify"", - }, - ], - "name": "union", - "raw": ""left" | "center" | "right" | "justify"", - }, - }, - "center": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - "justify": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - "left": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - "position": { - "description": "position doc", - "required": true, - "tsType": { - "name": "signature", - "raw": "{ - /** - * x coordinate doc - */ - x: number, - /** - * y coordinate doc - */ - y: number -}", - "signature": { - "properties": [ - { - "description": "x coordinate doc", - "key": "x", - "value": { - "name": "number", - "required": true, - }, - }, - { - "description": "y coordinate doc", - "key": "y", - "value": { - "name": "number", - "required": true, - }, - }, - ], - }, - "type": "object", - }, - }, - "right": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_23.tsx" without errors 1`] = ` -[ - { - "composes": [ - "OtherProps", - ], - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "required": true, - "tsType": { - "name": "number", - }, - }, - "baz": { - "description": "Complex union prop", - "required": true, - "tsType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - }, - "foo": { - "description": "Optional prop", - "required": false, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_24.js" without errors 1`] = ` -[ - { - "composes": [ - "OtherProps", - ], - "description": "This is a flow class component with an interface as props", - "displayName": "FlowComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "flowType": { - "name": "number", - }, - "required": true, - }, - "baz": { - "description": "Complex union prop", - "flowType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - "required": true, - }, - "foo": { - "description": "Optional prop", - "flowType": { - "name": "string", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_25.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "required": true, - "tsType": { - "elements": [ - { - "name": "Child", - }, - ], - "name": "Array", - "raw": "Array", - }, - }, - "baz": { - "description": "Complex union prop", - "required": true, - "tsType": { - "name": "number", - }, - }, - "foo": { - "description": "Optional prop", - "required": false, - "tsType": { - "name": "Child", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_26.js" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "FlowComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "flowType": { - "elements": [ - { - "name": "Child", - }, - ], - "name": "Array", - "raw": "Array", - }, - "required": true, - }, - "baz": { - "description": "Complex union prop", - "flowType": { - "name": "number", - }, - "required": true, - }, - "foo": { - "description": "Optional prop", - "flowType": { - "name": "Child", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_27.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [ - { - "description": "This is a method", - "docblock": "This is a method", - "modifiers": [], - "name": "foo", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - { - "description": "This is a public method", - "docblock": "This is a public method", - "modifiers": [], - "name": "bar", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - ], - "props": { - "foo": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_28.tsx" without errors 1`] = ` -[ - { - "description": "Example component description", - "displayName": "ABC", - "methods": [], - "props": { - "foo": { - "defaultValue": { - "computed": false, - "value": "true", - }, - "description": "Example prop description", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_29.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "prop": { - "description": "", - "flowType": { - "name": "T", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_30.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "prop": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_31.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "prop": { - "description": "", - "flowType": { - "name": "T", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_32.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Segments", - "methods": [ - { - "docblock": null, - "modifiers": [], - "name": "foo", - "params": [ - { - "name": "props", - "optional": false, - "type": { - "alias": "Props", - "name": "signature", - "raw": "{ - segments: Array, -}", - "signature": { - "properties": [ - { - "key": "segments", - "value": { - "elements": [ - { - "name": "T", - }, - ], - "name": "Array", - "raw": "Array", - "required": true, - }, - }, - ], - }, - "type": "object", - }, - }, - ], - "returns": null, - }, - ], - "props": { - "segments": { - "description": "", - "flowType": { - "elements": [ - { - "name": "T", - }, - ], - "name": "Array", - "raw": "Array", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_33.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript component with imported prop types", - "displayName": "ImportedExtendedComponent", - "methods": [], - "props": { - "bar": { - "description": "", - "required": true, - "tsType": { - "name": "number", - }, - }, - "foo": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_34.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "CustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "color": { - "description": "", - "required": false, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_35.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_36.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_37.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_38.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_39.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript component with imported prop types", - "displayName": "ImportedComponent", - "methods": [], - "props": { - "foo": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_40.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "size": { - "defaultValue": { - "computed": true, - "value": "Sizes.EXTRA_LARGE", - }, - "description": "", - "required": false, - "type": { - "computed": true, - "name": "enum", - "value": "Object.values(Sizes)", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_41.tsx" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "value": { - "description": "String value of a number", - "required": false, - "tsType": { - "name": "STRING_VALS[number]", - "raw": "typeof STRING_VALS[number]", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_42.js" without errors 1`] = ` -[ - { - "description": "", - "methods": [], - "props": { - "foo": { - "defaultValue": { - "computed": false, - "value": "'bar'", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_43.tsx" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MenuItem", - "methods": [], - "props": { - "children": { - "description": "Menu item contents.", - "required": false, - "type": { - "name": "node", - }, - }, - "classes": { - "description": "Override or extend the styles applied to the component. See CSS API below for more details.", - "required": false, - "type": { - "name": "object", - }, - }, - "component": { - "defaultValue": { - "computed": false, - "value": "'li'", - }, - "required": false, - }, - "disableGutters": { - "defaultValue": { - "computed": false, - "value": "false", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "flow-export-type.js" without errors 1`] = ` -[ - { - "description": "This is a Flow class component", - "displayName": "FlowComponent", - "methods": [ - { - "docblock": null, - "modifiers": [], - "name": "foo", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - { - "docblock": null, - "modifiers": [], - "name": "bar", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - ], - "props": { - "foo": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "flow-import-type.js" without errors 1`] = ` -[ - { - "description": "This is a Flow component with imported prop types", - "displayName": "ImportedComponent", - "methods": [], - "props": { - "foo": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "flow-spread-import-type.js" without errors 1`] = ` -[ - { - "description": "This is a Flow component with imported prop types", - "displayName": "ImportedExtendedComponent", - "methods": [], - "props": { - "bar": { - "description": "", - "flowType": { - "name": "number", - }, - "required": true, - }, - "foo": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "namespace-export.tsx" without errors 1`] = ` -[ - { - "description": "", - "methods": [], - "props": { - "value": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "test-all-imports.tsx" without errors 1`] = ` -[ - { - "description": "This is a TS component with imported stuff", - "displayName": "ImportedExtendedComponent", - "methods": [], - "props": { - "x": { - "defaultValue": { - "computed": false, - "value": ""string"", - }, - "required": false, - }, - "y": { - "defaultValue": { - "computed": false, - "value": "'otherstring'", - }, - "required": false, - }, - }, - }, -] -`; diff --git a/packages/react-docgen/tests/integration/fixtureCapabilities.ts b/packages/react-docgen/tests/integration/fixtureCapabilities.ts deleted file mode 100644 index 5712e86f90d..00000000000 --- a/packages/react-docgen/tests/integration/fixtureCapabilities.ts +++ /dev/null @@ -1,60 +0,0 @@ -export type FixtureCapability = - 'babel-specific' | 'common' | 'flow' | 'typescript'; - -export const fixtureCapabilities: Record = { - 'class-without-id.tsx': 'typescript', - 'component_1.js': 'common', - 'component_2.js': 'common', - 'component_3.js': 'common', - 'component_4.js': 'common', - 'component_5.js': 'common', - 'component_6.js': 'common', - 'component_7.js': 'common', - 'component_8.js': 'common', - 'component_9.js': 'common', - 'component_10.js': 'common', - 'component_11.js': 'flow', - 'component_12.js': 'flow', - 'component_13.js': 'flow', - 'component_14.js': 'flow', - 'component_15.js': 'flow', - 'component_16.js': 'common', - 'component_17.js': 'common', - 'component_18.js': 'flow', - 'component_19.js': 'flow', - 'component_20.js': 'common', - 'component_21.tsx': 'typescript', - 'component_22.tsx': 'typescript', - 'component_23.tsx': 'typescript', - 'component_24.js': 'flow', - 'component_25.tsx': 'typescript', - 'component_26.js': 'flow', - 'component_27.tsx': 'typescript', - 'component_28.tsx': 'typescript', - 'component_29.js': 'flow', - 'component_30.js': 'flow', - 'component_31.js': 'flow', - 'component_32.js': 'flow', - 'component_33.tsx': 'typescript', - 'component_34.js': 'common', - 'component_35.js': 'common', - 'component_36.js': 'common', - 'component_37.js': 'common', - 'component_38.js': 'common', - 'component_39.tsx': 'typescript', - 'component_40.js': 'common', - 'component_41.tsx': 'typescript', - 'component_42.js': 'common', - 'component_43.tsx': 'typescript', - 'flow-export-type.js': 'flow', - 'flow-import-type.js': 'flow', - 'flow-spread-import-type.js': 'flow', - 'namespace-export.tsx': 'typescript', - 'test-all-imports.tsx': 'typescript', -}; - -export function assertFixtureIsClassified(filename: string): void { - if (!(filename in fixtureCapabilities)) { - throw new Error(`Integration fixture "${filename}" has no capability.`); - } -} diff --git a/packages/react-docgen/tests/integration/integration-test.ts b/packages/react-docgen/tests/integration/integration-test.ts index ab9c7e5eb76..22321fd7256 100644 --- a/packages/react-docgen/tests/integration/integration-test.ts +++ b/packages/react-docgen/tests/integration/integration-test.ts @@ -1,43 +1,26 @@ -import fs from 'fs'; -import { dirname, join } from 'path'; import { describe, expect, test } from 'vitest'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; import { parse, makeFsImporter } from '../../src/main'; -import { fileURLToPath } from 'url'; -import { assertFixtureIsClassified } from './fixtureCapabilities'; describe('integration', () => { - describe('fixtures', () => { - const fixturePath = join( - dirname(fileURLToPath(import.meta.url)), - '__fixtures__', - ); - const fileNames = fs.readdirSync(fixturePath, { withFileTypes: true }); + for (const integrationCase of loadIntegrationCases()) { + test(integrationCase.id, () => { + const run = () => + parse(integrationCase.source, { + importer: makeFsImporter(), + babelOptions: { + filename: integrationCase.filename, + babelrc: false, + }, + }); - for (const entry of fileNames) { - if (entry.isDirectory()) { - continue; + if (integrationCase.error) { + expect(run).toThrow( + expect.objectContaining({ code: integrationCase.error.code }), + ); + } else { + expect(run()).toEqual(integrationCase.output); } - const name = entry.name; - - assertFixtureIsClassified(name); - - const filePath = join(fixturePath, name); - const fileContent = fs.readFileSync(filePath, 'utf8'); - - test(`processes component "${name}" without errors`, () => { - let result; - - expect(() => { - result = parse(fileContent, { - importer: makeFsImporter(), - babelOptions: { - filename: filePath, - babelrc: false, - }, - }); - }).not.toThrow(); - expect(result).toMatchSnapshot(); - }); - } - }); + }); + } }); diff --git a/packages/react-docgen/vitest.config.ts b/packages/react-docgen/vitest.config.ts index 477c4ebbf79..03499cbb3db 100644 --- a/packages/react-docgen/vitest.config.ts +++ b/packages/react-docgen/vitest.config.ts @@ -10,9 +10,20 @@ export default defineConfig({ }, coverage: { include: ['src/**'], - exclude: ['**/__mocks__/**', '**/__tests__/**'], + exclude: [ + '**/__mocks__/**', + '**/__snapshots__/**', + '**/__tests__/**', + '**/*-test.ts', + ], provider: 'v8', reporter: ['text', 'lcov'], + thresholds: { + statements: 84, + branches: 74, + functions: 94, + lines: 84, + }, }, }, }); diff --git a/packages/typescript/package.json b/packages/typescript/package.json index 0bf216a7f95..089c5ef393d 100644 --- a/packages/typescript/package.json +++ b/packages/typescript/package.json @@ -29,5 +29,8 @@ "@typescript-eslint/typescript-estree": "8.67.0", "@typescript-eslint/visitor-keys": "8.67.0" }, + "devDependencies": { + "@react-docgen-internal/integration-tests": "workspace:*" + }, "license": "MIT" } diff --git a/packages/typescript/src/__tests__/parse-test.ts b/packages/typescript/src/__tests__/parse-test.ts index 5527603d81e..76b574860a8 100644 --- a/packages/typescript/src/__tests__/parse-test.ts +++ b/packages/typescript/src/__tests__/parse-test.ts @@ -1,5 +1,3 @@ -import fs from 'fs'; -import { fileURLToPath } from 'url'; import { describe, expect, test } from 'vitest'; import { isIdentifier, @@ -7,12 +5,7 @@ import { traverse, type AstNode, } from '@react-docgen/core'; -import { parse, parser } from '../index.js'; - -const filename = fileURLToPath( - new URL('../__fixtures__/function-component.tsx', import.meta.url), -); -const source = fs.readFileSync(filename, 'utf8'); +import { parser } from '../index.js'; describe('@react-docgen/typescript', () => { test.each([ @@ -63,45 +56,4 @@ describe('@react-docgen/typescript', () => { expect(isIdentifier(identifier, { name: 'answer' })).toBe(true); }); - - test('extracts an exported function component', () => { - expect(parse(source, { filename })).toEqual([ - { - description: 'Renders a button.', - displayName: 'Button', - methods: [], - props: { - disabled: { - defaultValue: { - computed: false, - value: 'false', - }, - description: 'Prevents interaction.', - required: false, - tsType: { name: 'boolean' }, - }, - label: { - description: 'Text shown inside the button.', - required: true, - tsType: { name: 'string' }, - }, - }, - }, - ]); - }); - - test('extracts a JavaScript function component', () => { - expect( - parse( - '/** Greets the user. */ export function Greeting() { return
; }', - { filename: 'component.jsx' }, - ), - ).toEqual([ - { - description: 'Greets the user.', - displayName: 'Greeting', - methods: [], - }, - ]); - }); }); diff --git a/packages/typescript/tests/integration/integration-test.ts b/packages/typescript/tests/integration/integration-test.ts new file mode 100644 index 00000000000..b5304560aaa --- /dev/null +++ b/packages/typescript/tests/integration/integration-test.ts @@ -0,0 +1,22 @@ +import { describe, expect, test } from 'vitest'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { parse } from '../../src/index.js'; + +const supportedCases = [ + 'js/definitions/function-declaration', + 'typescript/defaults/function-default-parameters', +]; + +describe('integration', () => { + for (const integrationCase of loadIntegrationCases({ + ids: supportedCases, + })) { + test(integrationCase.id, () => { + expect( + parse(integrationCase.source, { + filename: integrationCase.filename, + }), + ).toEqual(integrationCase.output); + }); + } +}); diff --git a/packages/typescript/vitest.config.ts b/packages/typescript/vitest.config.ts index 9bdaf160de2..aca73767e86 100644 --- a/packages/typescript/vitest.config.ts +++ b/packages/typescript/vitest.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { name: 'typescript', - include: ['**/__tests__/**/*-test.ts'], + include: ['**/__tests__/**/*-test.ts', '**/tests/integration/**/*-test.ts'], coverage: { include: ['src/**'], provider: 'v8', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2865e771be3..9159b671426 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -233,7 +233,7 @@ importers: specifier: 5.0.5 version: 5.0.5(@types/node@22.20.5)(@vitest/coverage-v8@5.0.5)(vite@8.3.5(@types/node@22.20.5)(jiti@2.7.0)(yaml@2.9.1)) - benchmark: + packages/benchmark: dependencies: benchmark: specifier: 2.1.4 @@ -256,6 +256,8 @@ importers: packages/core: {} + packages/integration-tests: {} + packages/react-docgen: dependencies: '@babel/core': @@ -288,6 +290,10 @@ importers: strip-indent: specifier: ^4.0.0 version: 4.1.1 + devDependencies: + '@react-docgen-internal/integration-tests': + specifier: workspace:* + version: link:../integration-tests packages/react-docgen-cli: dependencies: @@ -319,6 +325,10 @@ importers: '@typescript-eslint/visitor-keys': specifier: 8.67.0 version: 8.67.0 + devDependencies: + '@react-docgen-internal/integration-tests': + specifier: workspace:* + version: link:../integration-tests packages/website: dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index edc8b393647..045a6ea6109 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,4 @@ packages: - - 'benchmark' - 'packages/*' allowBuilds: esbuild: false diff --git a/renovate.json b/renovate.json index 59957c3f131..29e5ff8d319 100644 --- a/renovate.json +++ b/renovate.json @@ -20,7 +20,7 @@ "packageRules": [ { "matchFileNames": [ - "benchmark/package.json", + "packages/benchmark/package.json", "packages/website/package.json", "packages/react-docgen-cli/package.json" ], @@ -46,7 +46,7 @@ }, { "matchFileNames": [ - "benchmark/package.json", + "packages/benchmark/package.json", "packages/website/package.json" ], "matchUpdateTypes": ["minor", "patch"], @@ -59,7 +59,7 @@ }, { "matchFileNames": [ - "benchmark/package.json", + "packages/benchmark/package.json", "packages/website/package.json" ], "semanticCommitType": "chore" From a9ca684fe04a136f5cf51d888e2839beac47fed5 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Mon, 21 Sep 2026 01:26:35 +0200 Subject: [PATCH 05/22] new package structure --- PLAN.md | 74 +++- packages/babel/package.json | 38 ++ packages/babel/src/__tests__/parser-test.ts | 56 +++ packages/babel/src/index.ts | 54 +++ packages/babel/src/normalize.ts | 97 ++++ packages/babel/tsconfig.json | 10 + packages/babel/vitest.config.ts | 8 + .../core/src/__tests__/extension-api-test.ts | 34 ++ packages/core/src/createDocgen.ts | 46 ++ packages/core/src/extract.ts | 12 +- packages/core/src/guards.ts | 66 +++ .../core/src/handlers/componentHandler.ts | 47 ++ packages/core/src/handlers/contextHandler.ts | 65 +++ .../core/src/handlers/defaultPropsHandler.ts | 104 +++++ packages/core/src/handlers/methodHandler.ts | 158 +++++++ .../core/src/handlers/propTypesHandler.ts | 111 +++++ packages/core/src/index.ts | 34 ++ packages/core/src/internal.ts | 11 + packages/core/src/nodes.ts | 137 ++++++ packages/core/src/reactHandlers.ts | 15 + .../src/resolver/findExportedDefinitions.ts | 129 ++++++ .../resolver/resolveComponentDefinitions.ts | 24 + .../src/utils/findImperativeHandleMethods.ts | 46 ++ .../core/src/utils/findTopLevelDefinition.ts | 76 ++++ packages/core/src/utils/getBody.ts | 7 + .../core/src/utils/getClassStaticValue.ts | 49 ++ .../core/src/utils/getComponentDescription.ts | 29 ++ packages/core/src/utils/getComponentName.ts | 43 ++ packages/core/src/utils/getDefaultValue.ts | 41 ++ packages/core/src/utils/getDescription.ts | 30 ++ .../core/src/utils/getExplicitDisplayName.ts | 41 ++ packages/core/src/utils/getMemberName.ts | 17 + .../core/src/utils/getObjectProperties.ts | 27 ++ .../core/src/utils/getParameterDefaults.ts | 25 ++ packages/core/src/utils/getPropType.ts | 165 +++++++ packages/core/src/utils/getPropertyName.ts | 13 + .../core/src/utils/getResolvedEnumValues.ts | 64 +++ .../core/src/utils/hasComponentAnnotation.ts | 17 + .../core/src/utils/parseMethodDocblock.ts | 79 ++++ .../src/utils/resolveComponentDefinition.ts | 83 ++++ packages/core/src/utils/resolveValue.ts | 419 ++++++++++++++++++ packages/core/src/utils/unwrapExpression.ts | 28 ++ .../circular-interface-inheritance/index.tsx | 11 + .../output.json | 23 + .../circular-type-aliases/index.tsx | 6 + .../circular-type-aliases/output.json | 7 + packages/typescript/package.json | 1 + .../typescript/src/__tests__/testUtils.ts | 23 + .../src/extractFunctionComponent.ts | 194 -------- .../src/handlers/typescriptPropsHandler.ts | 75 ++++ packages/typescript/src/index.ts | 39 +- .../__tests__/findExportedDefinitions-test.ts | 21 + .../findImperativeHandleMethods-test.ts | 20 + .../__tests__/findTopLevelDefinition-test.ts | 15 + .../src/utils/__tests__/getBody-test.ts | 12 + .../__tests__/getClassStaticValue-test.ts | 19 + .../__tests__/getComponentDescription-test.ts | 19 + .../utils/__tests__/getComponentName-test.ts | 10 + .../__tests__/getComposedTypeNames-test.ts | 24 + .../utils/__tests__/getDescription-test.ts | 18 + .../__tests__/getExplicitDisplayName-test.ts | 13 + .../src/utils/__tests__/getMemberName-test.ts | 28 ++ .../__tests__/getObjectProperties-test.ts | 24 + .../__tests__/getParameterDefaults-test.ts | 32 ++ .../src/utils/__tests__/getPropType-test.ts | 35 ++ .../utils/__tests__/getPropertyName-test.ts | 30 ++ .../utils/__tests__/getPropsMembers-test.ts | 59 +++ .../__tests__/getResolvedEnumValues-test.ts | 33 ++ .../src/utils/__tests__/getTSType-test.ts | 29 ++ .../src/utils/__tests__/getTypeName-test.ts | 28 ++ .../__tests__/hasComponentAnnotation-test.ts | 12 + .../__tests__/parseMethodDocblock-test.ts | 20 + .../resolveComponentDefinition-test.ts | 18 + .../src/utils/__tests__/resolveValue-test.ts | 26 ++ .../utils/__tests__/unwrapExpression-test.ts | 18 + .../src/utils/getComposedTypeNames.ts | 75 ++++ .../typescript/src/utils/getPropsMembers.ts | 213 +++++++++ packages/typescript/src/utils/getTSType.ts | 358 +++++++++++++++ packages/typescript/src/utils/getTypeName.ts | 22 + .../integration/babel-differential-test.ts | 37 ++ .../tests/integration/integration-test.ts | 90 +++- pnpm-lock.yaml | 366 +++++++++------ 82 files changed, 4373 insertions(+), 359 deletions(-) create mode 100644 packages/babel/package.json create mode 100644 packages/babel/src/__tests__/parser-test.ts create mode 100644 packages/babel/src/index.ts create mode 100644 packages/babel/src/normalize.ts create mode 100644 packages/babel/tsconfig.json create mode 100644 packages/babel/vitest.config.ts create mode 100644 packages/core/src/__tests__/extension-api-test.ts create mode 100644 packages/core/src/createDocgen.ts create mode 100644 packages/core/src/handlers/componentHandler.ts create mode 100644 packages/core/src/handlers/contextHandler.ts create mode 100644 packages/core/src/handlers/defaultPropsHandler.ts create mode 100644 packages/core/src/handlers/methodHandler.ts create mode 100644 packages/core/src/handlers/propTypesHandler.ts create mode 100644 packages/core/src/internal.ts create mode 100644 packages/core/src/reactHandlers.ts create mode 100644 packages/core/src/resolver/findExportedDefinitions.ts create mode 100644 packages/core/src/resolver/resolveComponentDefinitions.ts create mode 100644 packages/core/src/utils/findImperativeHandleMethods.ts create mode 100644 packages/core/src/utils/findTopLevelDefinition.ts create mode 100644 packages/core/src/utils/getBody.ts create mode 100644 packages/core/src/utils/getClassStaticValue.ts create mode 100644 packages/core/src/utils/getComponentDescription.ts create mode 100644 packages/core/src/utils/getComponentName.ts create mode 100644 packages/core/src/utils/getDefaultValue.ts create mode 100644 packages/core/src/utils/getDescription.ts create mode 100644 packages/core/src/utils/getExplicitDisplayName.ts create mode 100644 packages/core/src/utils/getMemberName.ts create mode 100644 packages/core/src/utils/getObjectProperties.ts create mode 100644 packages/core/src/utils/getParameterDefaults.ts create mode 100644 packages/core/src/utils/getPropType.ts create mode 100644 packages/core/src/utils/getPropertyName.ts create mode 100644 packages/core/src/utils/getResolvedEnumValues.ts create mode 100644 packages/core/src/utils/hasComponentAnnotation.ts create mode 100644 packages/core/src/utils/parseMethodDocblock.ts create mode 100644 packages/core/src/utils/resolveComponentDefinition.ts create mode 100644 packages/core/src/utils/resolveValue.ts create mode 100644 packages/core/src/utils/unwrapExpression.ts create mode 100644 packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/index.tsx create mode 100644 packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/output.json create mode 100644 packages/integration-tests/cases/typescript/regressions/circular-type-aliases/index.tsx create mode 100644 packages/integration-tests/cases/typescript/regressions/circular-type-aliases/output.json create mode 100644 packages/typescript/src/__tests__/testUtils.ts delete mode 100644 packages/typescript/src/extractFunctionComponent.ts create mode 100644 packages/typescript/src/handlers/typescriptPropsHandler.ts create mode 100644 packages/typescript/src/resolver/__tests__/findExportedDefinitions-test.ts create mode 100644 packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts create mode 100644 packages/typescript/src/utils/__tests__/findTopLevelDefinition-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getBody-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getClassStaticValue-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getComponentDescription-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getComponentName-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getComposedTypeNames-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getDescription-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getExplicitDisplayName-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getMemberName-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getObjectProperties-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getParameterDefaults-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getPropType-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getPropertyName-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getPropsMembers-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getResolvedEnumValues-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getTSType-test.ts create mode 100644 packages/typescript/src/utils/__tests__/getTypeName-test.ts create mode 100644 packages/typescript/src/utils/__tests__/hasComponentAnnotation-test.ts create mode 100644 packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts create mode 100644 packages/typescript/src/utils/__tests__/resolveComponentDefinition-test.ts create mode 100644 packages/typescript/src/utils/__tests__/resolveValue-test.ts create mode 100644 packages/typescript/src/utils/__tests__/unwrapExpression-test.ts create mode 100644 packages/typescript/src/utils/getComposedTypeNames.ts create mode 100644 packages/typescript/src/utils/getPropsMembers.ts create mode 100644 packages/typescript/src/utils/getTSType.ts create mode 100644 packages/typescript/src/utils/getTypeName.ts create mode 100644 packages/typescript/tests/integration/babel-differential-test.ts diff --git a/PLAN.md b/PLAN.md index ccbe9869599..c26dadc1014 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2,8 +2,8 @@ ## Status -- Current milestone: 3 — JavaScript and TypeScript parity -- Overall status: in progress +- Current milestone: 4 — Hermes and Flow +- Overall status: Milestone 3.1 complete; Milestone 4 not started - Last updated: 2026-08-16 ## Decisions @@ -79,10 +79,10 @@ ready for an explicitly requested release. ## Milestone 3 — JavaScript and TypeScript parity -- [ ] Port resolvers, imports, value resolution, PropTypes, defaults, classes, +- [x] Port resolvers, imports, value resolution, PropTypes, defaults, classes, methods, docblocks, and TypeScript type extraction. -- [ ] Add normalized Babel adapter for differential testing. -- [ ] Define public neutral extension APIs and compile-test custom handlers, +- [x] Add normalized Babel adapter for differential testing. +- [x] Define public neutral extension APIs and compile-test custom handlers, resolvers, and importers. Exit criteria: all applicable `common` and `typescript` fixtures match legacy @@ -114,6 +114,22 @@ cannot silently regress. Exit criteria: common JS/JSX output agrees across adapters and Flow output matches the legacy implementation. +## Milestone 3.1 — Shared React extraction + +- [x] Move parser-neutral resolvers, handlers, and value/documentation helpers + from `@react-docgen/typescript` into `@react-docgen/core`. +- [x] Split shared component metadata extraction from TypeScript prop/type + extraction. +- [x] Keep TypeScript-only type helpers and handler composition in + `@react-docgen/typescript`. +- [x] Expose preconfigured `parse()` from `@react-docgen/babel` using only + Babel plus shared core extraction. +- [x] Keep focused utility tests and JavaScript differential fixtures green. + +Exit criteria: Babel and TypeScript adapters share React extraction without +depending on each other; only TypeScript semantics remain in the TypeScript +package; all applicable JavaScript output remains identical. + ## Milestone 5 — Mixed-parser projects - [ ] Add ordered `createParserRouter()` rules using filename, glob, or a custom @@ -174,6 +190,30 @@ import { parse } from '@react-docgen/typescript'; Record every material plan change here before or with implementation. +### 2026-08-16 — Added shared React extraction milestone + +- Inserted Milestone 3.1 before Hermes work and temporarily made it current. +- Moved parser-neutral React behavior toward `@react-docgen/core`; parser + packages will compose that behavior with parser/language-specific handlers. +- Reason: Milestone 3 proved Babel could reuse normalized ASTs, but its + differential runner depended on TypeScript-owned handlers. That dependency + direction would duplicate behavior for Babel and Hermes. + +### 2026-08-16 — Completed shared React extraction milestone + +- Moved shared React handlers, exported-definition resolution, and + value/documentation helpers into `@react-docgen/core` while preserving their + one-purpose-file layout. +- Split TypeScript prop extraction into `typescriptPropsHandler`; kept only + composed-type, props-member, TypeScript-type, and TypeScript-name helpers in + `@react-docgen/typescript`. +- Made method extraction accept an optional type resolver, allowing core and + Babel to handle JavaScript/JSDoc while TypeScript supplies `getTSType`. +- Added Babel's preconfigured `parse()` and changed differential tests to use + public Babel and TypeScript APIs, removing their implementation dependency. +- Reason: parser adapters now select syntax while core owns shared observable + React behavior; new adapters need only contribute language-specific logic. + ### 2026-08-16 — Initial roadmap - Added parser-neutral package architecture and six delivery milestones. @@ -267,3 +307,27 @@ Record every material plan change here before or with implementation. - Reason: unit tests additionally cover Babel-specific internals, public helper APIs, custom resolvers, and synthetic AST states that parser adapters should not need to reproduce through integration fixtures. + +### 2026-08-16 — Completed JavaScript and TypeScript parity milestone + +- Expanded `@react-docgen/typescript` from the vertical slice to the complete + applicable JavaScript and TypeScript corpus: exports, stable resolver errors, + local/imported values and types, PropTypes, contexts, defaults, classes, + methods, docblocks, HOCs, imperative handles, and TypeScript type shapes. +- Kept extraction utilities in one-purpose files and added focused tests for + new resolution, type, docblock, class, enum, expression, and method helpers. +- Added parser-neutral `createDocgen()` composition to `@react-docgen/core` and + compile/runtime-tested custom `Parser`, `Resolver`, `Handler`, and `Importer` + contracts without Babel types. +- Added `@react-docgen/babel`, which normalizes Babel 7/8 AST node names into + the shared representation and declares both Babel majors as peer ranges. + Differential tests now require all 40 portable JavaScript golden outputs to + agree between normalized Babel and TypeScript ESTree. +- Excluded only `typescript/imports/reexported-default-values` from the + TypeScript adapter. Its support file uses Babel's nonstandard + `export defaultFrom` proposal, which TypeScript ESTree rejects before an + importer can expose its values; the same observable import/value behavior is + covered by standard-syntax import fixtures. +- Reason: Milestone 3's contract is observable output parity for syntax a + selected parser supports, plus explicit parser boundaries—not emulation of + another parser's proposal syntax. diff --git a/packages/babel/package.json b/packages/babel/package.json new file mode 100644 index 00000000000..c7c9cbba449 --- /dev/null +++ b/packages/babel/package.json @@ -0,0 +1,38 @@ +{ + "name": "@react-docgen/babel", + "version": "0.0.0", + "description": "Normalized Babel parser adapter for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/babel" + }, + "type": "module", + "files": ["dist"], + "engines": { + "node": "^22.13.0 || >=24" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + }, + "dependencies": { + "@react-docgen/core": "workspace:*" + }, + "peerDependencies": { + "@babel/core": "^7.28.0 || ^8.0.0", + "@babel/types": "^7.28.2 || ^8.0.0" + }, + "devDependencies": { + "@babel/core": "7.29.7", + "@babel/types": "7.29.8", + "@types/babel__core": "7.20.5" + }, + "license": "MIT" +} diff --git a/packages/babel/src/__tests__/parser-test.ts b/packages/babel/src/__tests__/parser-test.ts new file mode 100644 index 00000000000..59773ce28e7 --- /dev/null +++ b/packages/babel/src/__tests__/parser-test.ts @@ -0,0 +1,56 @@ +import { expect, test } from 'vitest'; +import parser, { parse } from '../index.js'; + +test('normalizes Babel-specific node names', () => { + const ast = parser.parse({ + code: 'class Button { static propTypes = { label: "text" }; }', + filename: 'button.jsx', + }); + + expect(ast).toMatchObject({ + type: 'Program', + body: [ + { + type: 'ClassDeclaration', + body: { + body: [ + { + type: 'PropertyDefinition', + value: { + type: 'ObjectExpression', + properties: [{ type: 'Property', value: { type: 'Literal' } }], + }, + }, + ], + }, + }, + ], + }); +}); + +test('extracts React documentation with shared handlers', () => { + expect( + parse(` + import PropTypes from 'prop-types'; + + /** Button description. */ + export function Button() {} + Button.propTypes = { label: PropTypes.string.isRequired }; + Button.defaultProps = { label: 'Save' }; + `), + ).toEqual([ + { + description: 'Button description.', + displayName: 'Button', + methods: [], + props: { + label: { + defaultValue: { computed: false, value: "'Save'" }, + description: '', + required: false, + type: { name: 'string' }, + }, + }, + }, + ]); +}); diff --git a/packages/babel/src/index.ts b/packages/babel/src/index.ts new file mode 100644 index 00000000000..e6d481779ee --- /dev/null +++ b/packages/babel/src/index.ts @@ -0,0 +1,54 @@ +import { parseSync } from '@babel/core'; +import { VISITOR_KEYS } from '@babel/types'; +import { + createDocgen, + reactHandlers, + resolveComponentDefinitions, + type ComponentDocumentation, + type DocgenParseOptions, + type Parser, + type VisitorKeys, +} from '@react-docgen/core'; +import normalize from './normalize.js'; + +export const visitorKeys: VisitorKeys = { + ...VISITOR_KEYS, + Literal: [], + MethodDefinition: ['key', 'value', 'decorators'], + Property: ['key', 'value', 'decorators'], + PropertyDefinition: ['key', 'value', 'decorators'], +}; + +const parser: Parser = { + parse(source) { + const ast = parseSync(source.code, { + ast: true, + code: false, + filename: source.filename, + parserOpts: { + plugins: ['jsx', 'typescript'], + }, + }); + + if (!ast) throw new TypeError('Babel did not return an AST.'); + + return normalize(ast); + }, + visitorKeys, +}; + +export default parser; +export { parser }; + +const docgen = createDocgen({ + handlers: reactHandlers, + parser, + resolver: resolveComponentDefinitions, +}); + +export function parse( + code: string, + options?: DocgenParseOptions, +): ComponentDocumentation[] { + return docgen(code, options); +} diff --git a/packages/babel/src/normalize.ts b/packages/babel/src/normalize.ts new file mode 100644 index 00000000000..d8dfce4dad2 --- /dev/null +++ b/packages/babel/src/normalize.ts @@ -0,0 +1,97 @@ +import { isAstNode, type AstNode } from '@react-docgen/core'; + +const typeNames: Record = { + BigIntLiteral: 'Literal', + BooleanLiteral: 'Literal', + ClassMethod: 'MethodDefinition', + ClassPrivateMethod: 'MethodDefinition', + ClassPrivateProperty: 'PropertyDefinition', + ClassProperty: 'PropertyDefinition', + CommentBlock: 'Block', + CommentLine: 'Line', + DecimalLiteral: 'Literal', + NullLiteral: 'Literal', + NumericLiteral: 'Literal', + ObjectMethod: 'Property', + ObjectProperty: 'Property', + RegExpLiteral: 'Literal', + StringLiteral: 'Literal', +}; + +function normalizeValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(normalizeValue); + if (!value || typeof value !== 'object') return value; + + const input = value as Record; + + if (input.type === 'File') { + const program = normalizeValue(input.program); + + if (program && typeof program === 'object') { + (program as Record).comments = normalizeValue( + input.comments, + ); + } + + return program; + } + + const output: Record = {}; + + for (const [key, child] of Object.entries(input)) { + output[key] = normalizeValue(child); + } + + const originalType = typeof input.type === 'string' ? input.type : ''; + + output.type = typeNames[originalType] ?? originalType; + if (typeof input.start === 'number' && typeof input.end === 'number') { + output.range = [input.start, input.end]; + } + + if (output.type === 'Literal') { + output.raw = + input.extra && typeof input.extra === 'object' && 'raw' in input.extra + ? (input.extra as { raw: unknown }).raw + : originalType === 'NullLiteral' + ? 'null' + : input.value; + if (originalType === 'NullLiteral') output.value = null; + } + + if (originalType === 'ObjectMethod') { + output.value = { + type: 'FunctionExpression', + range: output.range, + params: output.params, + body: output.body, + async: output.async, + generator: output.generator, + returnType: output.returnType, + }; + } + + if (originalType === 'ClassMethod' || originalType === 'ClassPrivateMethod') { + output.value = { + type: 'FunctionExpression', + range: output.range, + params: output.params, + body: output.body, + async: output.async, + generator: output.generator, + returnType: output.returnType, + }; + } + + return output; +} + +export default function normalize(node: unknown): AstNode { + const normalized = normalizeValue(node); + + if (!isAstNode(normalized)) { + throw new TypeError('Babel did not return an AST node.'); + } + + return normalized; +} diff --git a/packages/babel/tsconfig.json b/packages/babel/tsconfig.json new file mode 100644 index 00000000000..a1f3d920bb4 --- /dev/null +++ b/packages/babel/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "exclude": ["**/__tests__/**/*"], + "include": ["src/**/*"] +} diff --git a/packages/babel/vitest.config.ts b/packages/babel/vitest.config.ts new file mode 100644 index 00000000000..427827c013a --- /dev/null +++ b/packages/babel/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'babel-adapter', + include: ['**/__tests__/**/*-test.ts'], + }, +}); diff --git a/packages/core/src/__tests__/extension-api-test.ts b/packages/core/src/__tests__/extension-api-test.ts new file mode 100644 index 00000000000..715b275ac9a --- /dev/null +++ b/packages/core/src/__tests__/extension-api-test.ts @@ -0,0 +1,34 @@ +import { expect, test } from 'vitest'; +import { + createDocgen, + type Handler, + type Importer, + type Parser, + type Resolver, +} from '../index.js'; + +test('composes neutral parser, resolver, handler, and importer APIs', () => { + const parser: Parser = { + visitorKeys: { Program: ['body'] }, + parse: ({ code }) => ({ type: 'Program', body: [], code }), + }; + const resolver: Resolver = (file) => [file.path]; + const handler: Handler = (documentation, _path, file) => { + documentation.description = file.import('./description').source.code; + }; + const importer: Importer = (specifier) => ({ + code: specifier === './description' ? 'Portable description.' : '', + filename: 'description.js', + }); + + const parse = createDocgen({ + handlers: [handler], + importer, + parser, + resolver, + }); + + expect(parse('')).toEqual([ + { description: 'Portable description.', methods: [] }, + ]); +}); diff --git a/packages/core/src/createDocgen.ts b/packages/core/src/createDocgen.ts new file mode 100644 index 00000000000..5e822b8b59a --- /dev/null +++ b/packages/core/src/createDocgen.ts @@ -0,0 +1,46 @@ +import extract, { + type ComponentDocumentation, + type Handler, + type Resolver, +} from './extract.js'; +import ProjectContext, { + type Importer, + type Parser, +} from './ProjectContext.js'; + +export interface CreateDocgenOptions { + handlers: readonly Handler[]; + importer?: Importer; + parser: Parser; + resolver: Resolver; +} + +export interface DocgenParseOptions { + filename?: string; + importer?: Importer; +} + +export default function createDocgen({ + handlers, + importer: defaultImporter, + parser, + resolver, +}: CreateDocgenOptions): ( + code: string, + options?: DocgenParseOptions, +) => ComponentDocumentation[] { + return (code, { filename = 'component.js', importer } = {}) => { + const project = new ProjectContext({ + importer: + importer ?? + defaultImporter ?? + (() => { + throw new Error('An importer is required to resolve imported files.'); + }), + selectParser: () => parser, + }); + const file = project.parse({ code, filename }); + + return extract(file, resolver, handlers); + }; +} diff --git a/packages/core/src/extract.ts b/packages/core/src/extract.ts index af44b4cdeec..5dde3b2a434 100644 --- a/packages/core/src/extract.ts +++ b/packages/core/src/extract.ts @@ -3,6 +3,7 @@ import type { FileState } from './ProjectContext.js'; export interface TypeDescriptor { readonly name: string; + readonly [key: string]: unknown; } export interface DefaultValueDescriptor { @@ -12,14 +13,18 @@ export interface DefaultValueDescriptor { export interface PropDescriptor { defaultValue?: DefaultValueDescriptor; - description: string; + description?: string; required: boolean; - tsType: TypeDescriptor; + tsType?: TypeDescriptor; + type?: TypeDescriptor; } export interface ComponentDocumentation { + composes?: string[]; + childContext?: Record>; + context?: Record>; description: string; - displayName: string; + displayName?: number | string; methods: unknown[]; props?: Record; } @@ -39,7 +44,6 @@ export default function extract( return resolver(file).map((path) => { const documentation: ComponentDocumentation = { description: '', - displayName: '', methods: [], }; diff --git a/packages/core/src/guards.ts b/packages/core/src/guards.ts index acc5e93fca6..0a119ea8451 100644 --- a/packages/core/src/guards.ts +++ b/packages/core/src/guards.ts @@ -1,20 +1,39 @@ import type { AstNode } from './AstNode.js'; import type { AssignmentPattern, + AssignmentExpression, + BlockStatement, + ArrayExpression, + ArrowFunctionExpression, + CallExpression, + ClassDeclaration, + ClassExpression, ExportNamedDeclaration, + ExportDefaultDeclaration, + ExpressionStatement, FunctionDeclaration, + FunctionExpression, Identifier, Literal, + MemberExpression, + MethodDefinition, ObjectPattern, + ObjectExpression, Program, Property, + PropertyDefinition, + ReturnStatement, + SpreadElement, TSBooleanKeyword, + TSInterfaceDeclaration, TSPropertySignature, TSStringKeyword, TSTypeAliasDeclaration, TSTypeAnnotation, TSTypeLiteral, TSTypeReference, + VariableDeclaration, + VariableDeclarator, } from './nodes.js'; function isType(node: AstNode, type: T['type']): node is T { @@ -23,12 +42,37 @@ function isType(node: AstNode, type: T['type']): node is T { export const isAssignmentPattern = (node: AstNode): node is AssignmentPattern => isType(node, 'AssignmentPattern'); +export const isAssignmentExpression = ( + node: AstNode, +): node is AssignmentExpression => isType(node, 'AssignmentExpression'); +export const isArrayExpression = (node: AstNode): node is ArrayExpression => + isType(node, 'ArrayExpression'); +export const isBlockStatement = (node: AstNode): node is BlockStatement => + isType(node, 'BlockStatement'); +export const isArrowFunctionExpression = ( + node: AstNode, +): node is ArrowFunctionExpression => isType(node, 'ArrowFunctionExpression'); +export const isCallExpression = (node: AstNode): node is CallExpression => + isType(node, 'CallExpression'); +export const isClassDeclaration = (node: AstNode): node is ClassDeclaration => + isType(node, 'ClassDeclaration'); +export const isClassExpression = (node: AstNode): node is ClassExpression => + isType(node, 'ClassExpression'); +export const isExportDefaultDeclaration = ( + node: AstNode, +): node is ExportDefaultDeclaration => isType(node, 'ExportDefaultDeclaration'); export const isExportNamedDeclaration = ( node: AstNode, ): node is ExportNamedDeclaration => isType(node, 'ExportNamedDeclaration'); +export const isExpressionStatement = ( + node: AstNode, +): node is ExpressionStatement => isType(node, 'ExpressionStatement'); export const isFunctionDeclaration = ( node: AstNode, ): node is FunctionDeclaration => isType(node, 'FunctionDeclaration'); +export const isFunctionExpression = ( + node: AstNode, +): node is FunctionExpression => isType(node, 'FunctionExpression'); export const isIdentifier = ( node: AstNode, options?: { name?: string }, @@ -37,14 +81,30 @@ export const isIdentifier = ( (options?.name === undefined || node.name === options.name); export const isLiteral = (node: AstNode): node is Literal => isType(node, 'Literal'); +export const isMemberExpression = (node: AstNode): node is MemberExpression => + isType(node, 'MemberExpression'); +export const isMethodDefinition = (node: AstNode): node is MethodDefinition => + isType(node, 'MethodDefinition'); export const isObjectPattern = (node: AstNode): node is ObjectPattern => isType(node, 'ObjectPattern'); +export const isObjectExpression = (node: AstNode): node is ObjectExpression => + isType(node, 'ObjectExpression'); export const isProgram = (node: AstNode): node is Program => isType(node, 'Program'); export const isProperty = (node: AstNode): node is Property => isType(node, 'Property'); +export const isPropertyDefinition = ( + node: AstNode, +): node is PropertyDefinition => isType(node, 'PropertyDefinition'); +export const isReturnStatement = (node: AstNode): node is ReturnStatement => + isType(node, 'ReturnStatement'); +export const isSpreadElement = (node: AstNode): node is SpreadElement => + isType(node, 'SpreadElement'); export const isTSBooleanKeyword = (node: AstNode): node is TSBooleanKeyword => isType(node, 'TSBooleanKeyword'); +export const isTSInterfaceDeclaration = ( + node: AstNode, +): node is TSInterfaceDeclaration => isType(node, 'TSInterfaceDeclaration'); export const isTSPropertySignature = ( node: AstNode, ): node is TSPropertySignature => isType(node, 'TSPropertySignature'); @@ -59,3 +119,9 @@ export const isTSTypeLiteral = (node: AstNode): node is TSTypeLiteral => isType(node, 'TSTypeLiteral'); export const isTSTypeReference = (node: AstNode): node is TSTypeReference => isType(node, 'TSTypeReference'); +export const isVariableDeclaration = ( + node: AstNode, +): node is VariableDeclaration => isType(node, 'VariableDeclaration'); +export const isVariableDeclarator = ( + node: AstNode, +): node is VariableDeclarator => isType(node, 'VariableDeclarator'); diff --git a/packages/core/src/handlers/componentHandler.ts b/packages/core/src/handlers/componentHandler.ts new file mode 100644 index 00000000000..c610f324ab5 --- /dev/null +++ b/packages/core/src/handlers/componentHandler.ts @@ -0,0 +1,47 @@ +import { + isClassDeclaration, + isClassExpression, + isCallExpression, + isArrowFunctionExpression, + isFunctionDeclaration, + isFunctionExpression, + isLiteral, + type Handler, +} from '../internal.js'; +import getComponentDescription from '../utils/getComponentDescription.js'; +import getComponentName from '../utils/getComponentName.js'; +import getExplicitDisplayName from '../utils/getExplicitDisplayName.js'; +import getClassStaticValue from '../utils/getClassStaticValue.js'; + +const componentHandler: Handler = (documentation, path, file) => { + if ( + !isFunctionDeclaration(path.node) && + !isClassDeclaration(path.node) && + !isClassExpression(path.node) && + !isFunctionExpression(path.node) && + !isArrowFunctionExpression(path.node) && + !isCallExpression(path.node) + ) { + return; + } + + const componentName = getComponentName(path); + + if (componentName) { + const staticDisplayName = getClassStaticValue(file, path, 'displayName'); + const explicitDisplayName = + staticDisplayName && + isLiteral(staticDisplayName) && + (typeof staticDisplayName.value === 'string' || + typeof staticDisplayName.value === 'number') + ? staticDisplayName.value + : getExplicitDisplayName(file, componentName); + + if (explicitDisplayName !== null) { + documentation.displayName = explicitDisplayName ?? componentName; + } + } + documentation.description = getComponentDescription(file, path); +}; + +export default componentHandler; diff --git a/packages/core/src/handlers/contextHandler.ts b/packages/core/src/handlers/contextHandler.ts new file mode 100644 index 00000000000..745f9d3d95d --- /dev/null +++ b/packages/core/src/handlers/contextHandler.ts @@ -0,0 +1,65 @@ +import { + isAssignmentExpression, + isExpressionStatement, + isIdentifier, + isMemberExpression, + isObjectExpression, + isProperty, + type Handler, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import getComponentName from '../utils/getComponentName.js'; +import getPropType from '../utils/getPropType.js'; + +const contextHandler: Handler = (documentation, path, file) => { + const componentName = getComponentName(path); + + if (!componentName) { + return; + } + + for (const statement of getBody(file)) { + if (!isExpressionStatement(statement.node)) { + continue; + } + + const assignment = statement.node.expression; + + if ( + !isAssignmentExpression(assignment) || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(assignment.left.object, { name: componentName }) || + !isIdentifier(assignment.left.property) || + !isObjectExpression(assignment.right) + ) { + continue; + } + + const target = + assignment.left.property.name === 'contextTypes' + ? 'context' + : assignment.left.property.name === 'childContextTypes' + ? 'childContext' + : null; + + if (!target) { + continue; + } + + for (const property of assignment.right.properties) { + if (!isProperty(property) || !isIdentifier(property.key)) { + continue; + } + + const propType = getPropType(property.value); + + if (propType) { + documentation[target] ??= {}; + documentation[target][property.key.name] = propType; + } + } + } +}; + +export default contextHandler; diff --git a/packages/core/src/handlers/defaultPropsHandler.ts b/packages/core/src/handlers/defaultPropsHandler.ts new file mode 100644 index 00000000000..242ca77e405 --- /dev/null +++ b/packages/core/src/handlers/defaultPropsHandler.ts @@ -0,0 +1,104 @@ +import { + isArrowFunctionExpression, + isAssignmentExpression, + isExpressionStatement, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isMemberExpression, + isObjectPattern, + type Handler, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import getComponentName from '../utils/getComponentName.js'; +import getDefaultValue from '../utils/getDefaultValue.js'; +import getParameterDefaults from '../utils/getParameterDefaults.js'; +import getObjectProperties from '../utils/getObjectProperties.js'; +import getPropertyName from '../utils/getPropertyName.js'; +import getClassStaticValue from '../utils/getClassStaticValue.js'; +import unwrapExpression from '../utils/unwrapExpression.js'; + +const defaultPropsHandler: Handler = (documentation, path, file) => { + const componentName = getComponentName(path); + + if ( + isFunctionDeclaration(path.node) || + isFunctionExpression(path.node) || + isArrowFunctionExpression(path.node) + ) { + const [parameter] = path.node.params; + + if (parameter && isObjectPattern(parameter)) { + for (const [name, value] of getParameterDefaults(parameter)) { + const prop = documentation.props?.[name]; + + if (prop) { + prop.defaultValue = getDefaultValue(file, value); + prop.required = false; + } else { + documentation.props ??= {}; + documentation.props[name] = { + defaultValue: getDefaultValue(file, value), + required: false, + }; + } + } + } + } + + if (!componentName) { + return; + } + + const staticDefaults = getClassStaticValue(file, path, 'defaultProps'); + const defaultObjects = staticDefaults ? [staticDefaults] : []; + + for (const statement of getBody(file)) { + if (!isExpressionStatement(statement.node)) { + continue; + } + + const assignment = statement.node.expression; + + if ( + !isAssignmentExpression(assignment) || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(unwrapExpression(assignment.left.object), { + name: componentName, + }) || + !isIdentifier(assignment.left.property, { name: 'defaultProps' }) + ) { + continue; + } + + defaultObjects.push(assignment.right); + } + + for (const defaultsObject of defaultObjects) { + for (const property of getObjectProperties(file, defaultsObject)) { + const keyName = getPropertyName(property.key); + const propertyName = + keyName && property.computed && isIdentifier(property.key) + ? `@computed#${keyName}` + : keyName; + + if (!propertyName) continue; + + const prop = documentation.props?.[propertyName]; + + if (prop) { + prop.defaultValue = getDefaultValue(file, property.value); + prop.required = false; + } else { + documentation.props ??= {}; + documentation.props[propertyName] = { + defaultValue: getDefaultValue(file, property.value), + required: false, + }; + } + } + } +}; + +export default defaultPropsHandler; diff --git a/packages/core/src/handlers/methodHandler.ts b/packages/core/src/handlers/methodHandler.ts new file mode 100644 index 00000000000..6991fe9b15d --- /dev/null +++ b/packages/core/src/handlers/methodHandler.ts @@ -0,0 +1,158 @@ +import { + isArrowFunctionExpression, + isClassDeclaration, + isClassExpression, + isIdentifier, + isFunctionDeclaration, + isFunctionExpression, + isMethodDefinition, + isPropertyDefinition, + type AstNode, + type Handler, + type FileState, + type TypeDescriptor, +} from '../internal.js'; +import getDescription from '../utils/getDescription.js'; +import getPropertyName from '../utils/getPropertyName.js'; +import parseMethodDocblock from '../utils/parseMethodDocblock.js'; +import findImperativeHandleMethods from '../utils/findImperativeHandleMethods.js'; + +function addImperativeMethods( + documentation: Parameters[0], + path: Parameters[1], + file: Parameters[2], +): void { + if ( + !isFunctionDeclaration(path.node) && + !isFunctionExpression(path.node) && + !isArrowFunctionExpression(path.node) + ) + return; + for (const property of findImperativeHandleMethods(path.node)) { + const name = getPropertyName(property.key); + + if (!name) continue; + const description = getDescription(file, property); + + documentation.methods.push({ + name, + docblock: description || null, + modifiers: [], + params: [], + returns: null, + ...(description ? { description } : {}), + }); + } +} + +export type TypeResolver = ( + file: FileState, + annotation: AstNode, +) => TypeDescriptor | null; + +export default function createMethodHandler(getType?: TypeResolver): Handler { + return (documentation, path, file) => { + addImperativeMethods(documentation, path, file); + if (!isClassDeclaration(path.node) && !isClassExpression(path.node)) return; + + for (const member of path.node.body.body) { + if (member.accessibility === 'private') continue; + let name: string | null = null; + let fn: AstNode | null = null; + const modifiers: string[] = []; + + if (isMethodDefinition(member)) { + name = getPropertyName(member.key); + fn = member.value; + if (member.static) modifiers.push('static'); + if (member.kind === 'get' || member.kind === 'set') { + modifiers.push(member.kind); + } + if (member.value.async) modifiers.push('async'); + if (member.value.generator) modifiers.push('generator'); + } else if ( + isPropertyDefinition(member) && + member.value && + isArrowFunctionExpression(member.value) + ) { + name = getPropertyName(member.key); + fn = member.value; + if (member.static) modifiers.push('static'); + if (member.value.async) modifiers.push('async'); + } + + if ( + !name || + !fn || + name === 'constructor' || + name === 'render' || + name === 'componentDidMount' || + name === 'componentWillUnmount' + ) + continue; + + const params = Array.isArray(fn.params) ? (fn.params as AstNode[]) : []; + const returnType = + fn.returnType && + typeof fn.returnType === 'object' && + 'type' in fn.returnType + ? (fn.returnType as AstNode) + : null; + const description = getDescription(file, member); + const parsedDocblock = parseMethodDocblock(description); + + documentation.methods.push({ + name, + docblock: description || null, + modifiers, + params: params.map((parameter) => { + const annotation = + parameter.typeAnnotation && + typeof parameter.typeAnnotation === 'object' && + 'type' in parameter.typeAnnotation + ? (parameter.typeAnnotation as AstNode) + : null; + const rawName = Array.isArray(parameter.range) + ? file.source.code + .slice(parameter.range[0], parameter.range[1]) + .replace(/\??:\s*[\s\S]*$/, '') + : isIdentifier(parameter) + ? parameter.name + : ''; + const normalizedName = rawName + .replace(/^\.\.\./, '') + .replace(/\s*=.*$/, ''); + const documented = + parameter.type === 'Identifier' || + parameter.type === 'AssignmentPattern' + ? parsedDocblock.params.get(normalizedName) + : undefined; + const type = + documented?.type ?? + (annotation && getType ? getType(file, annotation) : null); + + return { + name: rawName.replace(/\s*=.*$/, ''), + optional: Boolean( + documented?.optional || + parameter.optional || + parameter.type === 'AssignmentPattern', + ), + ...(!description || documented || parameter.type === 'Identifier' + ? { type } + : {}), + ...(documented?.description + ? { description: documented.description } + : {}), + }; + }), + returns: + parsedDocblock.returns ?? + (returnType && getType ? { type: getType(file, returnType) } : null), + ...(parsedDocblock.description + ? { description: parsedDocblock.description } + : {}), + }); + } + }; +} diff --git a/packages/core/src/handlers/propTypesHandler.ts b/packages/core/src/handlers/propTypesHandler.ts new file mode 100644 index 00000000000..1b7443d2702 --- /dev/null +++ b/packages/core/src/handlers/propTypesHandler.ts @@ -0,0 +1,111 @@ +import { + isAssignmentExpression, + isExpressionStatement, + isIdentifier, + isMemberExpression, + type Handler, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import getComponentName from '../utils/getComponentName.js'; +import getDescription from '../utils/getDescription.js'; +import getPropType from '../utils/getPropType.js'; +import getObjectProperties from '../utils/getObjectProperties.js'; +import getMemberName from '../utils/getMemberName.js'; +import getPropertyName from '../utils/getPropertyName.js'; +import resolveValue from '../utils/resolveValue.js'; +import getClassStaticValue from '../utils/getClassStaticValue.js'; +import getResolvedEnumValues from '../utils/getResolvedEnumValues.js'; +import unwrapExpression from '../utils/unwrapExpression.js'; + +const propTypesHandler: Handler = (documentation, path, file) => { + const componentName = getComponentName(path); + + if (!componentName) { + return; + } + + const staticPropTypes = getClassStaticValue(file, path, 'propTypes'); + const propTypesObjects = staticPropTypes ? [staticPropTypes] : []; + + for (const statement of getBody(file)) { + if (!isExpressionStatement(statement.node)) { + continue; + } + + const assignment = statement.node.expression; + + if ( + !isAssignmentExpression(assignment) || + assignment.operator !== '=' || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(unwrapExpression(assignment.left.object), { + name: componentName, + }) || + !isIdentifier(assignment.left.property, { name: 'propTypes' }) + ) { + continue; + } + + propTypesObjects.push(assignment.right); + } + + for (const propTypesObject of propTypesObjects) { + for (const property of getObjectProperties(file, propTypesObject)) { + const keyName = getPropertyName(property.key); + const propertyName = + keyName && property.computed && isIdentifier(property.key) + ? `@computed#${keyName}` + : keyName; + + if (!propertyName) continue; + + const propType = getPropType( + property.value, + (node) => getDescription(file, node), + (node) => + Array.isArray(node.range) + ? file.source.code.slice(node.range[0], node.range[1]) + : '', + ); + + const resolvedValue = resolveValue(file, property.value); + const raw = Array.isArray(resolvedValue.range) + ? file.source.code.slice(resolvedValue.range[0], resolvedValue.range[1]) + : ''; + + if (!propType) { + documentation.props ??= {}; + documentation.props[propertyName] = { + description: getDescription(file, property), + required: false, + type: { name: 'custom', raw }, + }; + continue; + } + + documentation.props ??= {}; + const memberName = getMemberName(property.value); + const enumValues = getResolvedEnumValues(file, property.value); + const type = enumValues + ? { name: 'enum', value: enumValues } + : memberName?.startsWith('PropTypes.') && + !/(?:\bfrom\s+['"]prop-types['"]|require\(['"]prop-types['"]\)|import\s+[^;]*\bPropTypes\b[^;]*\bfrom\s+['"]react['"])/.test( + file.source.code, + ) + ? { + name: 'custom', + raw, + } + : propType.type; + + documentation.props[propertyName] = { + description: getDescription(file, property), + required: propType.required, + type, + }; + } + } +}; + +export default propTypesHandler; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 303c982254e..3364202e029 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,10 +1,39 @@ export { default as AstPath } from './AstPath.js'; +export { default as createDocgen } from './createDocgen.js'; export { isAstNode } from './AstNode.js'; export { default as extract } from './extract.js'; export * from './guards.js'; export { FileState, default as ProjectContext } from './ProjectContext.js'; export { default as Scope } from './Scope.js'; export { default as traverse } from './traverse.js'; +export { default as componentHandler } from './handlers/componentHandler.js'; +export { default as contextHandler } from './handlers/contextHandler.js'; +export { default as defaultPropsHandler } from './handlers/defaultPropsHandler.js'; +export { default as createMethodHandler } from './handlers/methodHandler.js'; +export { default as propTypesHandler } from './handlers/propTypesHandler.js'; +export { default as reactHandlers } from './reactHandlers.js'; +export { default as findExportedDefinitions } from './resolver/findExportedDefinitions.js'; +export { default as resolveComponentDefinitions } from './resolver/resolveComponentDefinitions.js'; +export { default as findImperativeHandleMethods } from './utils/findImperativeHandleMethods.js'; +export { default as findTopLevelDefinition } from './utils/findTopLevelDefinition.js'; +export { default as getBody } from './utils/getBody.js'; +export { default as getClassStaticValue } from './utils/getClassStaticValue.js'; +export { default as getComponentDescription } from './utils/getComponentDescription.js'; +export { default as getComponentName } from './utils/getComponentName.js'; +export { default as getDefaultValue } from './utils/getDefaultValue.js'; +export { default as getDescription } from './utils/getDescription.js'; +export { default as getExplicitDisplayName } from './utils/getExplicitDisplayName.js'; +export { default as getMemberName } from './utils/getMemberName.js'; +export { default as getObjectProperties } from './utils/getObjectProperties.js'; +export { default as getParameterDefaults } from './utils/getParameterDefaults.js'; +export { default as getPropType } from './utils/getPropType.js'; +export { default as getPropertyName } from './utils/getPropertyName.js'; +export { default as getResolvedEnumValues } from './utils/getResolvedEnumValues.js'; +export { default as hasComponentAnnotation } from './utils/hasComponentAnnotation.js'; +export { default as parseMethodDocblock } from './utils/parseMethodDocblock.js'; +export { default as resolveComponentDefinition } from './utils/resolveComponentDefinition.js'; +export { default as resolveValue, getValueFile } from './utils/resolveValue.js'; +export { default as unwrapExpression } from './utils/unwrapExpression.js'; export type { AstNode, VisitorKeys } from './AstNode.js'; export type { @@ -22,7 +51,12 @@ export type { ParserSelector, SourceFile, } from './ProjectContext.js'; +export type { + CreateDocgenOptions, + DocgenParseOptions, +} from './createDocgen.js'; export type { Binding, BindingKind } from './Scope.js'; +export type { TypeResolver } from './handlers/methodHandler.js'; export type { Visit, Visitor, diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts new file mode 100644 index 00000000000..1b889568be8 --- /dev/null +++ b/packages/core/src/internal.ts @@ -0,0 +1,11 @@ +export * from './guards.js'; +export type { AstNode } from './AstNode.js'; +export type { default as AstPath } from './AstPath.js'; +export type { + DefaultValueDescriptor, + Handler, + Resolver, + TypeDescriptor, +} from './extract.js'; +export type { FileState } from './ProjectContext.js'; +export type * from './nodes.js'; diff --git a/packages/core/src/nodes.ts b/packages/core/src/nodes.ts index a76f0bdaea4..c3895edac5b 100644 --- a/packages/core/src/nodes.ts +++ b/packages/core/src/nodes.ts @@ -26,12 +26,122 @@ export interface ExportNamedDeclaration extends RangedNode { readonly declaration: AstNode | null; } +export interface ExportDefaultDeclaration extends RangedNode { + readonly type: 'ExportDefaultDeclaration'; + readonly declaration: AstNode; +} + +export interface ExpressionStatement extends RangedNode { + readonly type: 'ExpressionStatement'; + readonly expression: AstNode; +} + +export interface AssignmentExpression extends RangedNode { + readonly type: 'AssignmentExpression'; + readonly left: AstNode; + readonly operator: string; + readonly right: AstNode; +} + +export interface CallExpression extends RangedNode { + readonly type: 'CallExpression'; + readonly arguments: AstNode[]; + readonly callee: AstNode; +} + +export interface ArrayExpression extends RangedNode { + readonly type: 'ArrayExpression'; + readonly elements: Array; +} + +export interface MemberExpression extends RangedNode { + readonly type: 'MemberExpression'; + readonly computed: boolean; + readonly object: AstNode; + readonly property: AstNode; +} + export interface FunctionDeclaration extends RangedNode { readonly type: 'FunctionDeclaration'; readonly id: Identifier | null; readonly params: AstNode[]; } +export interface FunctionExpression extends RangedNode { + readonly type: 'FunctionExpression'; + readonly id: Identifier | null; + readonly params: AstNode[]; + readonly body: AstNode; + readonly async?: boolean; + readonly generator?: boolean; + readonly returnType?: TSTypeAnnotation; +} + +export interface ArrowFunctionExpression extends RangedNode { + readonly type: 'ArrowFunctionExpression'; + readonly params: AstNode[]; + readonly body: AstNode; + readonly async?: boolean; + readonly returnType?: TSTypeAnnotation; +} + +export interface VariableDeclaration extends RangedNode { + readonly type: 'VariableDeclaration'; + readonly declarations: AstNode[]; +} + +export interface VariableDeclarator extends RangedNode { + readonly type: 'VariableDeclarator'; + readonly id: AstNode; + readonly init: AstNode | null; +} + +export interface ClassDeclaration extends RangedNode { + readonly type: 'ClassDeclaration'; + readonly body: ClassBody; + readonly id: Identifier | null; + readonly superTypeArguments?: TSTypeParameterInstantiation; +} + +export interface ClassExpression extends RangedNode { + readonly type: 'ClassExpression'; + readonly body: ClassBody; + readonly id: Identifier | null; + readonly superTypeArguments?: TSTypeParameterInstantiation; +} + +export interface ClassBody extends RangedNode { + readonly type: 'ClassBody'; + readonly body: AstNode[]; +} + +export interface PropertyDefinition extends RangedNode { + readonly type: 'PropertyDefinition'; + readonly computed: boolean; + readonly key: AstNode; + readonly static: boolean; + readonly value: AstNode | null; +} + +export interface MethodDefinition extends RangedNode { + readonly type: 'MethodDefinition'; + readonly computed: boolean; + readonly key: AstNode; + readonly kind: 'constructor' | 'get' | 'method' | 'set'; + readonly static: boolean; + readonly value: FunctionExpression; +} + +export interface BlockStatement extends RangedNode { + readonly type: 'BlockStatement'; + readonly body: AstNode[]; +} + +export interface ReturnStatement extends RangedNode { + readonly type: 'ReturnStatement'; + readonly argument: AstNode | null; +} + export interface ObjectPattern extends RangedNode { readonly type: 'ObjectPattern'; readonly properties: AstNode[]; @@ -40,10 +150,21 @@ export interface ObjectPattern extends RangedNode { export interface Property extends RangedNode { readonly type: 'Property'; + readonly computed?: boolean; readonly key: AstNode; readonly value: AstNode; } +export interface ObjectExpression extends RangedNode { + readonly type: 'ObjectExpression'; + readonly properties: AstNode[]; +} + +export interface SpreadElement extends RangedNode { + readonly type: 'SpreadElement'; + readonly argument: AstNode; +} + export interface AssignmentPattern extends RangedNode { readonly type: 'AssignmentPattern'; readonly left: AstNode; @@ -62,6 +183,22 @@ export interface TSTypeAliasDeclaration extends RangedNode { readonly typeAnnotation: AstNode; } +export interface TSInterfaceBody extends RangedNode { + readonly type: 'TSInterfaceBody'; + readonly body: AstNode[]; +} + +export interface TSInterfaceDeclaration extends RangedNode { + readonly type: 'TSInterfaceDeclaration'; + readonly body: TSInterfaceBody; + readonly id: Identifier; +} + +export interface TSTypeParameterInstantiation extends RangedNode { + readonly type: 'TSTypeParameterInstantiation'; + readonly params: AstNode[]; +} + export interface TSTypeAnnotation extends RangedNode { readonly type: 'TSTypeAnnotation'; readonly typeAnnotation: AstNode; diff --git a/packages/core/src/reactHandlers.ts b/packages/core/src/reactHandlers.ts new file mode 100644 index 00000000000..1cbf789f5db --- /dev/null +++ b/packages/core/src/reactHandlers.ts @@ -0,0 +1,15 @@ +import componentHandler from './handlers/componentHandler.js'; +import contextHandler from './handlers/contextHandler.js'; +import defaultPropsHandler from './handlers/defaultPropsHandler.js'; +import createMethodHandler from './handlers/methodHandler.js'; +import propTypesHandler from './handlers/propTypesHandler.js'; + +const reactHandlers = [ + componentHandler, + propTypesHandler, + defaultPropsHandler, + contextHandler, + createMethodHandler(), +]; + +export default reactHandlers; diff --git a/packages/core/src/resolver/findExportedDefinitions.ts b/packages/core/src/resolver/findExportedDefinitions.ts new file mode 100644 index 00000000000..4538ac2974a --- /dev/null +++ b/packages/core/src/resolver/findExportedDefinitions.ts @@ -0,0 +1,129 @@ +import { + isAssignmentExpression, + isClassDeclaration, + isExportDefaultDeclaration, + isExportNamedDeclaration, + isFunctionDeclaration, + isExpressionStatement, + isIdentifier, + isMemberExpression, + isVariableDeclaration, + isVariableDeclarator, + type AstPath, + type Resolver, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import findTopLevelDefinition from '../utils/findTopLevelDefinition.js'; +import resolveComponentDefinition from '../utils/resolveComponentDefinition.js'; +import hasComponentAnnotation from '../utils/hasComponentAnnotation.js'; + +const findExportedDefinitions: Resolver = (file) => { + const definitions = new Set(); + + for (const path of getBody(file)) { + if ( + isVariableDeclaration(path.node) && + hasComponentAnnotation(file, path.node) + ) { + const declarations = path.get('declarations'); + + if (Array.isArray(declarations)) { + for (const declaration of declarations) { + if (!isVariableDeclarator(declaration.node)) continue; + const init = declaration.get('init'); + + if (!init || Array.isArray(init)) continue; + const definition = resolveComponentDefinition(file, init); + + if (definition) definitions.add(definition); + } + } + } + + if ( + (isExportNamedDeclaration(path.node) || + isExportDefaultDeclaration(path.node)) && + path.node.declaration + ) { + const declaration = path.get('declaration'); + + if ( + declaration && + !Array.isArray(declaration) && + (isFunctionDeclaration(declaration.node) || + isClassDeclaration(declaration.node)) + ) { + if ( + !isFunctionDeclaration(declaration.node) || + !declaration.node.id || + /^[A-Z]/.test(declaration.node.id.name) + ) { + definitions.add(declaration); + } + } else if ( + declaration && + !Array.isArray(declaration) && + isVariableDeclaration(declaration.node) + ) { + const variables = declaration.get('declarations'); + + if (Array.isArray(variables)) { + for (const variable of variables) { + if (!isVariableDeclarator(variable.node)) continue; + const init = variable.get('init'); + + if (!init || Array.isArray(init)) continue; + const definition = resolveComponentDefinition(file, init); + + if (definition) definitions.add(definition); + } + } + } else if (declaration && !Array.isArray(declaration)) { + const definition = resolveComponentDefinition(file, declaration); + + if (definition) { + definitions.add(definition); + } + } + + continue; + } + + if (!isExpressionStatement(path.node)) { + continue; + } + + const assignment = path.node.expression; + + if ( + !isAssignmentExpression(assignment) || + assignment.operator !== '=' || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(assignment.right) + ) { + continue; + } + + const object = assignment.left.object; + const property = assignment.left.property; + const isModuleExport = + isIdentifier(object, { name: 'module' }) && + isIdentifier(property, { name: 'exports' }); + const isNamedExport = isIdentifier(object, { name: 'exports' }); + + if (!isModuleExport && !isNamedExport) { + continue; + } + + const definition = findTopLevelDefinition(file, assignment.right.name); + + if (definition) { + definitions.add(definition); + } + } + + return [...definitions]; +}; + +export default findExportedDefinitions; diff --git a/packages/core/src/resolver/resolveComponentDefinitions.ts b/packages/core/src/resolver/resolveComponentDefinitions.ts new file mode 100644 index 00000000000..b7c7d82761b --- /dev/null +++ b/packages/core/src/resolver/resolveComponentDefinitions.ts @@ -0,0 +1,24 @@ +import type { Resolver } from '../extract.js'; +import findExportedDefinitions from './findExportedDefinitions.js'; + +const resolveComponentDefinitions: Resolver = (file) => { + const definitions = findExportedDefinitions(file); + + if (definitions.length === 1) return definitions; + + throw Object.assign( + new Error( + definitions.length === 0 + ? 'No component definition found.' + : 'Multiple component definitions found.', + ), + { + code: + definitions.length === 0 + ? 'ERR_REACTDOCGEN_MISSING_DEFINITION' + : 'ERR_REACTDOCGEN_MULTIPLE_DEFINITIONS', + }, + ); +}; + +export default resolveComponentDefinitions; diff --git a/packages/core/src/utils/findImperativeHandleMethods.ts b/packages/core/src/utils/findImperativeHandleMethods.ts new file mode 100644 index 00000000000..60f15d4c98d --- /dev/null +++ b/packages/core/src/utils/findImperativeHandleMethods.ts @@ -0,0 +1,46 @@ +import { + isArrowFunctionExpression, + isCallExpression, + isObjectExpression, + isProperty, + type AstNode, + type Property, +} from '../internal.js'; +import getMemberName from './getMemberName.js'; + +export default function findImperativeHandleMethods(node: AstNode): Property[] { + const methods: Property[] = []; + + function visit(current: AstNode): void { + if ( + isCallExpression(current) && + getMemberName(current.callee)?.split('.').at(-1) === 'useImperativeHandle' + ) { + const factory = current.arguments[1]; + + if ( + factory && + isArrowFunctionExpression(factory) && + isObjectExpression(factory.body) + ) { + methods.push(...factory.body.properties.filter(isProperty)); + } + } + + for (const value of Object.values(current)) { + if (Array.isArray(value)) { + for (const child of value) { + if (child && typeof child === 'object' && 'type' in child) { + visit(child as AstNode); + } + } + } else if (value && typeof value === 'object' && 'type' in value) { + visit(value as AstNode); + } + } + } + + visit(node); + + return methods; +} diff --git a/packages/core/src/utils/findTopLevelDefinition.ts b/packages/core/src/utils/findTopLevelDefinition.ts new file mode 100644 index 00000000000..232a89673db --- /dev/null +++ b/packages/core/src/utils/findTopLevelDefinition.ts @@ -0,0 +1,76 @@ +import { + isAssignmentExpression, + isClassDeclaration, + isFunctionDeclaration, + isExpressionStatement, + isIdentifier, + isVariableDeclaration, + isVariableDeclarator, + type AstPath, + type FileState, +} from '../internal.js'; +import getBody from './getBody.js'; + +export default function findTopLevelDefinition( + file: FileState, + name: string, +): AstPath | null { + for (const path of getBody(file)) { + if ( + (isFunctionDeclaration(path.node) || isClassDeclaration(path.node)) && + path.node.id?.name === name + ) { + return path; + } + + if (!isVariableDeclaration(path.node)) { + if (!isExpressionStatement(path.node)) { + continue; + } + + const expression = path.node.expression; + + if ( + !isAssignmentExpression(expression) || + !isIdentifier(expression.left, { name }) + ) { + continue; + } + + const expressionPath = path.get('expression'); + const rightPath = + expressionPath && !Array.isArray(expressionPath) + ? expressionPath.get('right') + : null; + + if (rightPath && !Array.isArray(rightPath)) { + return rightPath; + } + + continue; + } + + const declarations = path.get('declarations'); + + if (!Array.isArray(declarations)) { + continue; + } + + for (const declaration of declarations) { + if ( + !isVariableDeclarator(declaration.node) || + !isIdentifier(declaration.node.id, { name }) + ) { + continue; + } + + const init = declaration.get('init'); + + if (init && !Array.isArray(init)) { + return init; + } + } + } + + return null; +} diff --git a/packages/core/src/utils/getBody.ts b/packages/core/src/utils/getBody.ts new file mode 100644 index 00000000000..f903de6d9dd --- /dev/null +++ b/packages/core/src/utils/getBody.ts @@ -0,0 +1,7 @@ +import type { AstPath, FileState } from '../internal.js'; + +export default function getBody(file: FileState): AstPath[] { + const body = file.path.get('body'); + + return Array.isArray(body) ? body : []; +} diff --git a/packages/core/src/utils/getClassStaticValue.ts b/packages/core/src/utils/getClassStaticValue.ts new file mode 100644 index 00000000000..e49c0f4cc8e --- /dev/null +++ b/packages/core/src/utils/getClassStaticValue.ts @@ -0,0 +1,49 @@ +import { + isClassDeclaration, + isClassExpression, + isIdentifier, + isBlockStatement, + isMethodDefinition, + isPropertyDefinition, + isReturnStatement, + type AstNode, + type AstPath, + type FileState, +} from '../internal.js'; +import resolveValue from './resolveValue.js'; + +export default function getClassStaticValue( + file: FileState, + path: AstPath, + name: string, +): AstNode | null { + if (!isClassDeclaration(path.node) && !isClassExpression(path.node)) { + return null; + } + + for (const member of path.node.body.body) { + if ( + isPropertyDefinition(member) && + member.static && + !member.computed && + isIdentifier(member.key, { name }) + ) { + return member.value; + } + + if ( + isMethodDefinition(member) && + member.static && + member.kind === 'get' && + !member.computed && + isIdentifier(member.key, { name }) && + isBlockStatement(member.value.body) + ) { + const returned = member.value.body.body.find(isReturnStatement)?.argument; + + return returned ? resolveValue(file, returned) : null; + } + } + + return null; +} diff --git a/packages/core/src/utils/getComponentDescription.ts b/packages/core/src/utils/getComponentDescription.ts new file mode 100644 index 00000000000..a31021371e0 --- /dev/null +++ b/packages/core/src/utils/getComponentDescription.ts @@ -0,0 +1,29 @@ +import { + isProgram, + isVariableDeclaration, + type AstPath, + type FileState, +} from '../internal.js'; +import getDescription from './getDescription.js'; + +export default function getComponentDescription( + file: FileState, + path: AstPath, +): string { + for ( + let current: AstPath | null = path; + current; + current = current.parentPath + ) { + if (isVariableDeclaration(current.node)) { + return getDescription(file, current.node); + } + } + + return getDescription( + file, + path.parentPath && !isProgram(path.parentPath.node) + ? path.parentPath.node + : path.node, + ); +} diff --git a/packages/core/src/utils/getComponentName.ts b/packages/core/src/utils/getComponentName.ts new file mode 100644 index 00000000000..9359c727994 --- /dev/null +++ b/packages/core/src/utils/getComponentName.ts @@ -0,0 +1,43 @@ +import { + isAssignmentExpression, + isClassDeclaration, + isClassExpression, + isCallExpression, + isArrowFunctionExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isVariableDeclarator, + type AstPath, +} from '../internal.js'; + +export default function getComponentName(path: AstPath): string | null { + if ( + (isFunctionDeclaration(path.node) || isClassDeclaration(path.node)) && + path.node.id + ) { + return path.node.id.name; + } + + if ( + isArrowFunctionExpression(path.node) || + isFunctionExpression(path.node) || + isClassExpression(path.node) || + isCallExpression(path.node) + ) { + for (let parent = path.parentPath; parent; parent = parent.parentPath) { + if (isVariableDeclarator(parent.node) && isIdentifier(parent.node.id)) { + return parent.node.id.name; + } + + if ( + isAssignmentExpression(parent.node) && + isIdentifier(parent.node.left) + ) { + return parent.node.left.name; + } + } + } + + return null; +} diff --git a/packages/core/src/utils/getDefaultValue.ts b/packages/core/src/utils/getDefaultValue.ts new file mode 100644 index 00000000000..a8bff73f8a2 --- /dev/null +++ b/packages/core/src/utils/getDefaultValue.ts @@ -0,0 +1,41 @@ +import type { + AstNode, + DefaultValueDescriptor, + FileState, +} from '../internal.js'; +import { isIdentifier, isMemberExpression } from '../internal.js'; +import resolveValue, { getValueFile } from './resolveValue.js'; + +export default function getDefaultValue( + file: FileState, + node: AstNode, +): DefaultValueDescriptor { + if (isIdentifier(node) || isMemberExpression(node)) { + const original = node; + const resolved = resolveValue(file, node); + const resolvedFile = getValueFile(file, resolved); + + if (resolvedFile.source.filename !== file.source.filename) { + node = resolved; + file = resolvedFile; + } else { + node = original; + } + } + file = getValueFile(file, node); + const range = node.range; + + if ( + !Array.isArray(range) || + typeof range[0] !== 'number' || + typeof range[1] !== 'number' + ) { + return { computed: true, value: '' }; + } + + return { + computed: + node.type === 'CallExpression' || node.type === 'MemberExpression', + value: file.source.code.slice(range[0], range[1]), + }; +} diff --git a/packages/core/src/utils/getDescription.ts b/packages/core/src/utils/getDescription.ts new file mode 100644 index 00000000000..0e16440d5b9 --- /dev/null +++ b/packages/core/src/utils/getDescription.ts @@ -0,0 +1,30 @@ +import { + isProgram, + type AstNode, + type Comment, + type FileState, +} from '../internal.js'; + +export default function getDescription(file: FileState, node: AstNode): string { + if (!isProgram(file.ast) || !('range' in node)) { + return ''; + } + + const start = (node.range as readonly [number, number])[0]; + const comments = (file.ast.comments ?? []).filter( + (comment): comment is Comment => + comment.type === 'Block' && + comment.value.startsWith('*') && + comment.range[1] <= start && + /^[\s,;]*$/.test(file.source.code.slice(comment.range[1], start)), + ); + const comment = comments.at(-1); + + return comment + ? comment.value + .split('\n') + .map((line) => line.replace(/^\s*\* ?/, '')) + .join('\n') + .trim() + : ''; +} diff --git a/packages/core/src/utils/getExplicitDisplayName.ts b/packages/core/src/utils/getExplicitDisplayName.ts new file mode 100644 index 00000000000..ef0e5853cec --- /dev/null +++ b/packages/core/src/utils/getExplicitDisplayName.ts @@ -0,0 +1,41 @@ +import { + isAssignmentExpression, + isExpressionStatement, + isIdentifier, + isLiteral, + isMemberExpression, + type FileState, +} from '../internal.js'; +import getBody from './getBody.js'; + +export default function getExplicitDisplayName( + file: FileState, + componentName: string, +): number | string | null | undefined { + for (const path of getBody(file)) { + if (!isExpressionStatement(path.node)) { + continue; + } + + const assignment = path.node.expression; + + if ( + !isAssignmentExpression(assignment) || + assignment.operator !== '=' || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(assignment.left.object, { name: componentName }) || + !isIdentifier(assignment.left.property, { name: 'displayName' }) + ) { + continue; + } + + return isLiteral(assignment.right) && + (typeof assignment.right.value === 'string' || + typeof assignment.right.value === 'number') + ? assignment.right.value + : null; + } + + return undefined; +} diff --git a/packages/core/src/utils/getMemberName.ts b/packages/core/src/utils/getMemberName.ts new file mode 100644 index 00000000000..0a71b31d4a5 --- /dev/null +++ b/packages/core/src/utils/getMemberName.ts @@ -0,0 +1,17 @@ +import { isIdentifier, isMemberExpression, type AstNode } from '../internal.js'; + +export default function getMemberName(node: AstNode): string | null { + if (isIdentifier(node)) return node.name; + + if (!isMemberExpression(node) || node.computed) { + return null; + } + + const objectName = isIdentifier(node.object) + ? node.object.name + : getMemberName(node.object); + + return objectName && isIdentifier(node.property) + ? `${objectName}.${node.property.name}` + : null; +} diff --git a/packages/core/src/utils/getObjectProperties.ts b/packages/core/src/utils/getObjectProperties.ts new file mode 100644 index 00000000000..ff985242ae0 --- /dev/null +++ b/packages/core/src/utils/getObjectProperties.ts @@ -0,0 +1,27 @@ +import { + isObjectExpression, + isProperty, + isSpreadElement, + type FileState, + type AstNode, + type Property, +} from '../internal.js'; +import resolveValue from './resolveValue.js'; + +export default function getObjectProperties( + file: FileState, + node: AstNode, +): Property[] { + const object = resolveValue(file, node); + + if (!object || !isObjectExpression(object)) return []; + + return object.properties.flatMap((property) => { + if (isProperty(property)) return [property]; + if (isSpreadElement(property)) { + return getObjectProperties(file, property.argument); + } + + return []; + }); +} diff --git a/packages/core/src/utils/getParameterDefaults.ts b/packages/core/src/utils/getParameterDefaults.ts new file mode 100644 index 00000000000..c556bc50ed7 --- /dev/null +++ b/packages/core/src/utils/getParameterDefaults.ts @@ -0,0 +1,25 @@ +import { + isAssignmentPattern, + isIdentifier, + isProperty, + type AstNode, + type ObjectPattern, +} from '../internal.js'; + +export default function getParameterDefaults( + pattern: ObjectPattern | null, +): Map { + const defaults = new Map(); + + for (const property of pattern?.properties ?? []) { + if ( + isProperty(property) && + isIdentifier(property.key) && + isAssignmentPattern(property.value) + ) { + defaults.set(property.key.name, property.value.right); + } + } + + return defaults; +} diff --git a/packages/core/src/utils/getPropType.ts b/packages/core/src/utils/getPropType.ts new file mode 100644 index 00000000000..62d22f251f0 --- /dev/null +++ b/packages/core/src/utils/getPropType.ts @@ -0,0 +1,165 @@ +import { + isArrayExpression, + isCallExpression, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isProperty, + type AstNode, + type TypeDescriptor, +} from '../internal.js'; +import getMemberName from './getMemberName.js'; + +export interface PropTypeResult { + required: boolean; + type: TypeDescriptor; +} + +type GetDescription = (node: AstNode) => string; +type GetSource = (node: AstNode) => string; + +function getCalledPropType( + node: AstNode, + getDescription?: GetDescription, + getSource?: GetSource, +): TypeDescriptor | null { + if (!isCallExpression(node)) { + return null; + } + + const calleeName = getMemberName(node.callee); + const [argument] = node.arguments; + + if (!calleeName || !argument) { + return null; + } + + const name = calleeName.split('.').at(-1); + + if (name === 'arrayOf' || name === 'objectOf') { + const result = getPropType(argument, getDescription, getSource); + + return result ? { name, value: result.type } : null; + } + + if (name === 'instanceOf') { + return isIdentifier(argument) ? { name, value: argument.name } : null; + } + + if (name === 'oneOf' && isArrayExpression(argument)) { + return { + name: 'enum', + value: argument.elements.flatMap((element) => + element && isLiteral(element) + ? [ + { + computed: false, + value: element.raw ?? JSON.stringify(element.value), + }, + ] + : [], + ), + }; + } + + if (name === 'oneOf') { + return { + name: 'enum', + computed: true, + value: getSource?.(argument) ?? '', + }; + } + + if (name === 'oneOfType' && isArrayExpression(argument)) { + return { + name: 'union', + value: argument.elements.flatMap((element) => { + const result = element + ? getPropType(element, getDescription, getSource) + : null; + + if (!result || !element) { + return []; + } + + const description = getDescription?.(element); + + return [ + { + ...result.type, + ...(description ? { description } : {}), + }, + ]; + }), + }; + } + + if ((name === 'shape' || name === 'exact') && isObjectExpression(argument)) { + const value: Record = {}; + + for (const property of argument.properties) { + if (!isProperty(property) || !isIdentifier(property.key)) { + continue; + } + + const result = getPropType(property.value, getDescription, getSource); + + if (result) { + const description = getDescription?.(property); + + value[property.key.name] = { + ...result.type, + ...(description ? { description } : {}), + required: result.required, + }; + } + } + + return { name, value }; + } + + if (name === 'shape' || name === 'exact') { + return { + name, + computed: true, + value: getSource?.(argument) ?? '', + }; + } + + return null; +} + +export default function getPropType( + node: AstNode, + getDescription?: GetDescription, + getSource?: GetSource, +): PropTypeResult | null { + let required = false; + + if ( + isMemberExpression(node) && + !node.computed && + isIdentifier(node.property, { name: 'isRequired' }) + ) { + required = true; + node = node.object; + } + + const calledType = getCalledPropType(node, getDescription, getSource); + + if (calledType) { + return { required, type: calledType }; + } + + const name = getMemberName(node); + + if (!name?.includes('.')) { + return null; + } + + return { + required, + type: { name: name.split('.').at(-1) ?? name }, + }; +} diff --git a/packages/core/src/utils/getPropertyName.ts b/packages/core/src/utils/getPropertyName.ts new file mode 100644 index 00000000000..ec356b2bd8f --- /dev/null +++ b/packages/core/src/utils/getPropertyName.ts @@ -0,0 +1,13 @@ +import { isIdentifier, isLiteral, type AstNode } from '../internal.js'; + +export default function getPropertyName(node: AstNode): string | null { + if (isIdentifier(node)) return node.name; + if ( + isLiteral(node) && + (typeof node.value === 'string' || typeof node.value === 'number') + ) { + return String(node.value); + } + + return null; +} diff --git a/packages/core/src/utils/getResolvedEnumValues.ts b/packages/core/src/utils/getResolvedEnumValues.ts new file mode 100644 index 00000000000..657eac58f04 --- /dev/null +++ b/packages/core/src/utils/getResolvedEnumValues.ts @@ -0,0 +1,64 @@ +import { + isCallExpression, + isIdentifier, + isLiteral, + isMemberExpression, + type AstNode, + type FileState, +} from '../internal.js'; +import getMemberName from './getMemberName.js'; +import getObjectProperties from './getObjectProperties.js'; +import getPropertyName from './getPropertyName.js'; + +export default function getResolvedEnumValues( + file: FileState, + node: AstNode, +): Array<{ computed: false; value: string }> | null { + if ( + isMemberExpression(node) && + !node.computed && + isIdentifier(node.property, { name: 'isRequired' }) + ) { + return getResolvedEnumValues(file, node.object); + } + if ( + !isCallExpression(node) || + getMemberName(node.callee)?.endsWith('.oneOf') !== true + ) { + return null; + } + const [argument] = node.arguments; + + if (!argument || !isCallExpression(argument)) return null; + const operation = getMemberName(argument.callee); + const [object] = argument.arguments; + + if ( + !object || + (operation !== 'Object.keys' && operation !== 'Object.values') + ) { + return null; + } + const properties = getObjectProperties(file, object); + + if (properties.length === 0) return null; + if (operation === 'Object.keys') { + return properties.flatMap((property) => { + const name = getPropertyName(property.key); + + return name + ? [{ computed: false as const, value: JSON.stringify(name) }] + : []; + }); + } + + return properties.map((property) => ({ + computed: false, + value: + isLiteral(property.value) && + (typeof property.value.value === 'string' || + typeof property.value.value === 'number') + ? JSON.stringify(property.value.value) + : 'null', + })); +} diff --git a/packages/core/src/utils/hasComponentAnnotation.ts b/packages/core/src/utils/hasComponentAnnotation.ts new file mode 100644 index 00000000000..75525eef8f6 --- /dev/null +++ b/packages/core/src/utils/hasComponentAnnotation.ts @@ -0,0 +1,17 @@ +import { isProgram, type AstNode, type FileState } from '../internal.js'; + +export default function hasComponentAnnotation( + file: FileState, + node: AstNode, +): boolean { + if (!isProgram(file.ast) || !Array.isArray(node.range)) return false; + + const start = node.range[0]; + + return (file.ast.comments ?? []).some( + (comment) => + /(?:^|\s)@component(?:\s|$)/.test(comment.value) && + comment.range[1] <= start && + /^\s*$/.test(file.source.code.slice(comment.range[1], start)), + ); +} diff --git a/packages/core/src/utils/parseMethodDocblock.ts b/packages/core/src/utils/parseMethodDocblock.ts new file mode 100644 index 00000000000..698b86b09e3 --- /dev/null +++ b/packages/core/src/utils/parseMethodDocblock.ts @@ -0,0 +1,79 @@ +import type { TypeDescriptor } from '../internal.js'; + +export interface DocblockParam { + description?: string; + name: string; + optional: boolean; + type?: TypeDescriptor; +} + +export interface ParsedMethodDocblock { + description: string; + params: Map; + returns: { description?: string; type?: TypeDescriptor } | null; +} + +function parseType(raw: string): TypeDescriptor { + const value = raw.replace(/=$/, ''); + + if (value === '*') return { name: 'mixed' }; + if (value.startsWith('[') && value.endsWith(']')) { + return { + name: 'tuple', + elements: value + .slice(1, -1) + .split(',') + .map((part) => parseType(part.trim())), + }; + } + if (value.includes('|')) { + return { name: 'union', elements: value.split('|').map(parseType) }; + } + if (value.endsWith('[]')) { + return { name: 'Array', elements: [parseType(value.slice(0, -2))] }; + } + + return { name: value }; +} + +export default function parseMethodDocblock( + docblock: string, +): ParsedMethodDocblock { + const params = new Map(); + let returns: ParsedMethodDocblock['returns'] = null; + const description: string[] = []; + + for (const line of docblock.split('\n')) { + const trimmed = line.trim(); + const param = /^@param\s+\{([^}]+)\}\s+(\S+)(?:\s+(.*))?$/.exec(trimmed); + + if (param) { + const [, rawType = '', rawName = '', text] = param; + const name = rawName.replace(/^\.\.\./, '').replace(/^\[|\]$/g, ''); + + params.set(name, { + name, + optional: rawType.endsWith('=') || /^\[/.test(rawName), + type: parseType(rawType), + ...(text ? { description: text } : {}), + }); + continue; + } + const returned = /^@returns?\s*(?:\{([^}]+)\})?\s*(.*)$/.exec(trimmed); + + if (returned && !returns) { + const [, rawType, text] = returned; + + returns = { + ...(rawType ? { type: parseType(rawType) } : {}), + ...(text ? { description: text } : {}), + }; + continue; + } + if (!trimmed.startsWith('@') && (description.length > 0 || trimmed)) { + description.push(trimmed); + } + } + + return { description: description.join('\n').trim(), params, returns }; +} diff --git a/packages/core/src/utils/resolveComponentDefinition.ts b/packages/core/src/utils/resolveComponentDefinition.ts new file mode 100644 index 00000000000..ad7bec567f8 --- /dev/null +++ b/packages/core/src/utils/resolveComponentDefinition.ts @@ -0,0 +1,83 @@ +import { + isArrayExpression, + isArrowFunctionExpression, + isCallExpression, + isClassDeclaration, + isClassExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isObjectExpression, + type AstPath, + type FileState, +} from '../internal.js'; +import findTopLevelDefinition from './findTopLevelDefinition.js'; +import getMemberName from './getMemberName.js'; + +export default function resolveComponentDefinition( + file: FileState, + path: AstPath, +): AstPath | null { + if ( + path.node.type === 'ChainExpression' || + path.node.type === 'TSAsExpression' || + path.node.type === 'TSNonNullExpression' || + path.node.type === 'TSSatisfiesExpression' || + path.node.type === 'TSTypeAssertion' + ) { + const expression = path.get('expression'); + + return expression && !Array.isArray(expression) + ? resolveComponentDefinition(file, expression) + : null; + } + if (isIdentifier(path.node)) { + const definition = findTopLevelDefinition(file, path.node.name); + + return definition ? resolveComponentDefinition(file, definition) : null; + } + + if ( + isFunctionDeclaration(path.node) || + isFunctionExpression(path.node) || + isArrowFunctionExpression(path.node) || + isClassDeclaration(path.node) || + isClassExpression(path.node) + ) { + return path; + } + + if (!isCallExpression(path.node)) { + return null; + } + + if ( + getMemberName(path.node.callee) === 'React.createClass' || + getMemberName(path.node.callee) === 'createReactClass' + ) { + return path; + } + + const argumentsPaths = path.get('arguments'); + + if (!Array.isArray(argumentsPaths) || argumentsPaths.length === 0) { + return null; + } + + const [first] = argumentsPaths; + + if (!first) { + return null; + } + + const useLast = + argumentsPaths.length > 1 && + (isLiteral(first.node) || + isObjectExpression(first.node) || + isArrayExpression(first.node) || + first.node.type === 'SpreadElement'); + const candidate = useLast ? argumentsPaths.at(-1) : first; + + return candidate ? resolveComponentDefinition(file, candidate) : null; +} diff --git a/packages/core/src/utils/resolveValue.ts b/packages/core/src/utils/resolveValue.ts new file mode 100644 index 00000000000..283611771a1 --- /dev/null +++ b/packages/core/src/utils/resolveValue.ts @@ -0,0 +1,419 @@ +import { + isAssignmentExpression, + isExportDefaultDeclaration, + isExportNamedDeclaration, + isExpressionStatement, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isProperty, + isVariableDeclaration, + isVariableDeclarator, + type AstNode, + type FileState, +} from '../internal.js'; +import getBody from './getBody.js'; +import getPropertyName from './getPropertyName.js'; + +const valueFiles = new WeakMap(); + +function markTree(file: FileState, node: AstNode): void { + valueFiles.set(node, file); + for (const value of Object.values(node)) { + if (Array.isArray(value)) { + for (const child of value) { + if (child && typeof child === 'object' && 'type' in child) { + markTree(file, child as AstNode); + } + } + } else if (value && typeof value === 'object' && 'type' in value) { + markTree(file, value as AstNode); + } + } +} + +function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function importSource(node: AstNode): string | null { + const source = node.source; + + return source && + typeof source === 'object' && + 'type' in source && + isLiteral(source as AstNode) && + typeof (source as AstNode & { value: unknown }).value === 'string' + ? String((source as AstNode & { value: unknown }).value) + : null; +} + +function importedBinding( + file: FileState, + localName: string, +): { file: FileState; importedName: string } | null { + for (const path of getBody(file)) { + if (path.node.type !== 'ImportDeclaration') continue; + const source = importSource(path.node); + + if (!source || (!source.startsWith('.') && !source.startsWith('/'))) + continue; + for (const specifier of nodes(path.node, 'specifiers')) { + const local = specifier.local; + + if ( + !local || + typeof local !== 'object' || + !('type' in local) || + !isIdentifier(local as AstNode, { name: localName }) + ) + continue; + const imported = specifier.imported; + const importedName = + specifier.type === 'ImportDefaultSpecifier' + ? 'default' + : specifier.type === 'ImportNamespaceSpecifier' + ? '*' + : imported && + typeof imported === 'object' && + 'type' in imported && + isIdentifier(imported as AstNode) + ? (imported as AstNode & { name: string }).name + : localName; + + try { + return { file: file.import(source), importedName }; + } catch { + return null; + } + } + } + + return null; +} + +function localValue(file: FileState, name: string): AstNode | null { + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + + if (isVariableDeclaration(declaration)) { + for (const variable of declaration.declarations) { + if ( + isVariableDeclarator(variable) && + isIdentifier(variable.id, { name }) && + variable.init + ) + return variable.init; + if ( + isVariableDeclarator(variable) && + variable.id.type === 'ObjectPattern' && + variable.init + ) { + for (const property of nodes(variable.id, 'properties')) { + if ( + !isProperty(property) || + !isIdentifier(property.value, { name }) + ) + continue; + const object = resolveValue(file, variable.init); + + if (!isObjectExpression(object)) continue; + const value = object.properties.find( + (item) => + isProperty(item) && + getPropertyName(item.key) === getPropertyName(property.key), + ); + + if (value && isProperty(value)) return value.value; + } + } + } + } + if ( + (declaration.type === 'FunctionDeclaration' || + declaration.type === 'ClassDeclaration') && + declaration.id && + typeof declaration.id === 'object' && + 'type' in declaration.id && + isIdentifier(declaration.id as AstNode, { name }) + ) + return declaration; + if ( + !isExpressionStatement(path.node) || + !isAssignmentExpression(path.node.expression) + ) + continue; + if (isIdentifier(path.node.expression.left, { name })) + return path.node.expression.right; + } + + return null; +} + +function memberValue( + file: FileState, + objectName: string, + name: string, +): AstNode | null { + for (const path of getBody(file)) { + if ( + !isExpressionStatement(path.node) || + !isAssignmentExpression(path.node.expression) + ) + continue; + const left = path.node.expression.left; + + if ( + isMemberExpression(left) && + isIdentifier(left.object, { name: objectName }) && + getPropertyName(left.property) === name + ) + return path.node.expression.right; + } + + return null; +} + +function exportedValue( + file: FileState, + name: string, + seen: Set, +): AstNode | null { + const key = `${file.source.filename}:${name}`; + + if (seen.has(key)) return null; + seen.add(key); + + for (const path of getBody(file)) { + if (isExportDefaultDeclaration(path.node) && name === 'default') { + return resolve(file, path.node.declaration, seen); + } + if (path.node.type === 'ExportAllDeclaration') { + const source = importSource(path.node); + + if (source) { + const value = exportedValue(file.import(source), name, seen); + + if (value) return value; + } + } + if (!isExportNamedDeclaration(path.node)) continue; + if (path.node.declaration) { + const declaration = path.node.declaration; + + if (isVariableDeclaration(declaration)) { + for (const variable of declaration.declarations) { + if ( + isVariableDeclarator(variable) && + isIdentifier(variable.id, { name }) && + variable.init + ) { + return resolve(file, variable.init, seen); + } + if ( + isVariableDeclarator(variable) && + variable.id.type === 'ObjectPattern' + ) { + const value = localValue(file, name); + + if (value) return resolve(file, value, seen); + } + } + } + if ( + declaration.id && + typeof declaration.id === 'object' && + 'type' in declaration.id && + isIdentifier(declaration.id as AstNode, { name }) + ) { + return declaration; + } + } + for (const specifier of nodes(path.node, 'specifiers')) { + const exported = specifier.exported; + + if ( + !exported || + typeof exported !== 'object' || + !('type' in exported) || + !isIdentifier(exported as AstNode, { name }) + ) + continue; + const local = specifier.local; + const localName = + local && + typeof local === 'object' && + 'type' in local && + isIdentifier(local as AstNode) + ? (local as AstNode & { name: string }).name + : name; + const source = importSource(path.node); + + return source + ? exportedValue(file.import(source), localName, seen) + : resolve( + file, + { type: 'Identifier', name: localName } as AstNode, + seen, + ); + } + } + + return null; +} + +function exportedMember( + file: FileState, + exportName: string, + memberName: string, + seen: Set, +): AstNode | null { + const key = `${file.source.filename}:${exportName}.${memberName}`; + + if (seen.has(key)) return null; + seen.add(key); + for (const path of getBody(file)) { + if (path.node.type === 'ExportAllDeclaration') { + const source = importSource(path.node); + + if (source) { + const value = exportedMember( + file.import(source), + exportName, + memberName, + seen, + ); + + if (value) return value; + } + } + if (!isExportNamedDeclaration(path.node)) continue; + for (const specifier of nodes(path.node, 'specifiers')) { + const exported = specifier.exported; + + if ( + !exported || + typeof exported !== 'object' || + !('type' in exported) || + !isIdentifier(exported as AstNode, { name: exportName }) + ) + continue; + const local = specifier.local; + const localName = + local && + typeof local === 'object' && + 'type' in local && + isIdentifier(local as AstNode) + ? (local as AstNode & { name: string }).name + : exportName; + const source = importSource(path.node); + + if (source) + return exportedMember(file.import(source), localName, memberName, seen); + const value = memberValue(file, localName, memberName); + + if (value) return resolve(file, value, seen); + } + } + const value = memberValue(file, exportName, memberName); + + if (value) return resolve(file, value, seen); + const exported = exportedValue(file, exportName, seen); + + if (exported && isObjectExpression(exported)) { + const property = exported.properties.find( + (item) => isProperty(item) && getPropertyName(item.key) === memberName, + ); + + if (property && isProperty(property)) + return resolve(file, property.value, seen); + } + + return null; +} + +function resolve(file: FileState, node: AstNode, seen: Set): AstNode { + markTree(file, node); + if (isIdentifier(node)) { + const imported = importedBinding(file, node.name); + + if (imported) + return exportedValue(imported.file, imported.importedName, seen) ?? node; + const value = localValue(file, node.name); + + return value ? resolve(file, value, seen) : node; + } + if ( + isMemberExpression(node) && + !node.computed && + isIdentifier(node.property) + ) { + if (isIdentifier(node.object)) { + const imported = importedBinding(file, node.object.name); + + if (imported) { + if (imported.importedName === '*') { + return exportedValue(imported.file, node.property.name, seen) ?? node; + } + const localName = + imported.importedName === 'default' + ? (() => { + for (const path of getBody(imported.file)) { + if ( + isExportDefaultDeclaration(path.node) && + isIdentifier(path.node.declaration) + ) + return path.node.declaration.name; + } + + return imported.importedName; + })() + : imported.importedName; + const value = exportedMember( + imported.file, + imported.importedName === 'default' + ? localName + : imported.importedName, + node.property.name, + seen, + ); + + return value ? resolve(imported.file, value, seen) : node; + } + const value = memberValue(file, node.object.name, node.property.name); + + if (value) return resolve(file, value, seen); + } + const object = resolve(file, node.object, seen); + + if (isObjectExpression(object)) { + const property = object.properties.find( + (item) => + isProperty(item) && getPropertyName(item.key) === node.property.name, + ); + + if (property && isProperty(property)) + return resolve(file, property.value, seen); + } + } + + return node; +} + +export default function resolveValue(file: FileState, node: AstNode): AstNode { + return resolve(file, node, new Set()); +} + +export function getValueFile(fallback: FileState, node: AstNode): FileState { + return valueFiles.get(node) ?? fallback; +} diff --git a/packages/core/src/utils/unwrapExpression.ts b/packages/core/src/utils/unwrapExpression.ts new file mode 100644 index 00000000000..326b335b94c --- /dev/null +++ b/packages/core/src/utils/unwrapExpression.ts @@ -0,0 +1,28 @@ +import type { AstNode } from '../internal.js'; + +const wrappers = new Set([ + 'ChainExpression', + 'TSAsExpression', + 'TSNonNullExpression', + 'TSSatisfiesExpression', + 'TSTypeAssertion', +]); + +export default function unwrapExpression(node: AstNode): AstNode { + let current = node; + + while (wrappers.has(current.type)) { + const expression = current.expression; + + if ( + !expression || + typeof expression !== 'object' || + !('type' in expression) + ) { + break; + } + current = expression as AstNode; + } + + return current; +} diff --git a/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/index.tsx b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/index.tsx new file mode 100644 index 00000000000..bf4c5bfd061 --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/index.tsx @@ -0,0 +1,11 @@ +interface A extends B { + a: number; +} + +interface B extends A { + b: number; +} + +export function Component(props: A) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/output.json b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/output.json new file mode 100644 index 00000000000..b4cd621ecc7 --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "", + "displayName": "Component", + "methods": [], + "props": { + "b": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + }, + "a": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/index.tsx b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/index.tsx new file mode 100644 index 00000000000..8480b5fb3f3 --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/index.tsx @@ -0,0 +1,6 @@ +type Foo = Bar; +type Bar = Foo; + +export function Component(props: Foo) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/output.json b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/output.json new file mode 100644 index 00000000000..dde063f6a2d --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": "Component", + "methods": [] + } +] diff --git a/packages/typescript/package.json b/packages/typescript/package.json index 089c5ef393d..a374dd14756 100644 --- a/packages/typescript/package.json +++ b/packages/typescript/package.json @@ -30,6 +30,7 @@ "@typescript-eslint/visitor-keys": "8.67.0" }, "devDependencies": { + "@react-docgen/babel": "workspace:*", "@react-docgen-internal/integration-tests": "workspace:*" }, "license": "MIT" diff --git a/packages/typescript/src/__tests__/testUtils.ts b/packages/typescript/src/__tests__/testUtils.ts new file mode 100644 index 00000000000..59cc26526be --- /dev/null +++ b/packages/typescript/src/__tests__/testUtils.ts @@ -0,0 +1,23 @@ +import { + ProjectContext, + type FileState, + type Importer, +} from '@react-docgen/core'; +import parser from '../parser.js'; + +export default function parseFile( + code: string, + filename = 'component.tsx', + importer?: Importer, +): FileState { + const project = new ProjectContext({ + importer: + importer ?? + (() => { + throw new Error('Unexpected import.'); + }), + selectParser: () => parser, + }); + + return project.parse({ code, filename }); +} diff --git a/packages/typescript/src/extractFunctionComponent.ts b/packages/typescript/src/extractFunctionComponent.ts deleted file mode 100644 index d03ac0e384e..00000000000 --- a/packages/typescript/src/extractFunctionComponent.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { - isAssignmentPattern, - isExportNamedDeclaration, - isFunctionDeclaration, - isIdentifier, - isLiteral, - isObjectPattern, - isProgram, - isProperty, - isTSBooleanKeyword, - isTSPropertySignature, - isTSStringKeyword, - isTSTypeAliasDeclaration, - isTSTypeAnnotation, - isTSTypeLiteral, - isTSTypeReference, - type AstNode, - type AstPath, - type Comment, - type FileState, - type Handler, - type ObjectPattern, - type Resolver, - type TSTypeLiteral, -} from '@react-docgen/core'; - -function getBody(file: FileState): AstPath[] { - const body = file.path.get('body'); - - return Array.isArray(body) ? body : []; -} - -export const resolver: Resolver = (file) => - getBody(file).flatMap((path) => { - if (!isExportNamedDeclaration(path.node) || !path.node.declaration) { - return []; - } - - const declaration = path.get('declaration'); - - return declaration && - !Array.isArray(declaration) && - isFunctionDeclaration(declaration.node) - ? [declaration] - : []; - }); - -function getDescription(file: FileState, node: AstNode): string { - if (!isProgram(file.ast) || !('range' in node)) { - return ''; - } - - const start = (node.range as readonly [number, number])[0]; - const comments = (file.ast.comments ?? []).filter( - (comment): comment is Comment => - comment.type === 'Block' && - comment.value.startsWith('*') && - comment.range[1] <= start && - /^[\s,;]*$/.test(file.source.code.slice(comment.range[1], start)), - ); - const comment = comments.at(-1); - - return comment - ? comment.value - .split('\n') - .map((line) => line.replace(/^\s*\* ?/, '')) - .join('\n') - .trim() - : ''; -} - -function getPropsType( - file: FileState, - parameter: AstNode, -): TSTypeLiteral | null { - const annotation = - (isIdentifier(parameter) || isObjectPattern(parameter)) && - parameter.typeAnnotation && - isTSTypeAnnotation(parameter.typeAnnotation) - ? parameter.typeAnnotation.typeAnnotation - : null; - - if (!annotation) { - return null; - } - - if (isTSTypeLiteral(annotation)) { - return annotation; - } - - if (!isTSTypeReference(annotation) || !isIdentifier(annotation.typeName)) { - return null; - } - - for (const path of getBody(file)) { - if ( - isTSTypeAliasDeclaration(path.node) && - path.node.id.name === annotation.typeName.name && - isTSTypeLiteral(path.node.typeAnnotation) - ) { - return path.node.typeAnnotation; - } - } - - return null; -} - -function getDefaults(pattern: ObjectPattern | null): Map { - const defaults = new Map(); - - for (const property of pattern?.properties ?? []) { - if ( - isProperty(property) && - isIdentifier(property.key) && - isAssignmentPattern(property.value) - ) { - defaults.set(property.key.name, property.value.right); - } - } - - return defaults; -} - -function getTypeName(node: AstNode | undefined): string | null { - if (!node || !isTSTypeAnnotation(node)) { - return null; - } - - if (isTSStringKeyword(node.typeAnnotation)) { - return 'string'; - } - - if (isTSBooleanKeyword(node.typeAnnotation)) { - return 'boolean'; - } - - return null; -} - -export const handler: Handler = (documentation, path, file) => { - if (!isFunctionDeclaration(path.node) || !path.node.id) { - return; - } - - const parameter = path.node.params[0]; - const propsType = parameter ? getPropsType(file, parameter) : null; - const pattern = parameter && isObjectPattern(parameter) ? parameter : null; - const defaults = getDefaults(pattern); - - documentation.displayName = path.node.id.name; - documentation.description = getDescription( - file, - path.parentPath?.node ?? path.node, - ); - - if (!propsType) { - return; - } - - documentation.props = {}; - - for (const member of propsType.members) { - if (!isTSPropertySignature(member) || !isIdentifier(member.key)) { - continue; - } - - const typeName = getTypeName(member.typeAnnotation); - - if (!typeName) { - continue; - } - - const defaultNode = defaults.get(member.key.name); - - documentation.props[member.key.name] = { - description: getDescription(file, member), - required: !member.optional, - tsType: { name: typeName }, - ...(defaultNode && isLiteral(defaultNode) - ? { - defaultValue: { - computed: false, - value: - defaultNode.raw ?? - file.source.code.slice( - defaultNode.range[0], - defaultNode.range[1], - ), - }, - } - : {}), - }; - } -}; diff --git a/packages/typescript/src/handlers/typescriptPropsHandler.ts b/packages/typescript/src/handlers/typescriptPropsHandler.ts new file mode 100644 index 00000000000..3d1cef4627f --- /dev/null +++ b/packages/typescript/src/handlers/typescriptPropsHandler.ts @@ -0,0 +1,75 @@ +import { + getDescription, + getParameterDefaults, + isArrowFunctionExpression, + isClassDeclaration, + isClassExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isObjectPattern, + isTSPropertySignature, + isTSTypeAnnotation, + type Handler, +} from '@react-docgen/core'; +import getComposedTypeNames from '../utils/getComposedTypeNames.js'; +import getPropsMembers from '../utils/getPropsMembers.js'; +import getTSType from '../utils/getTSType.js'; + +const typescriptPropsHandler: Handler = (documentation, path, file) => { + const parameter = + isFunctionDeclaration(path.node) || + isFunctionExpression(path.node) || + isArrowFunctionExpression(path.node) + ? path.node.params[0] + : undefined; + const annotation = parameter + ? (isIdentifier(parameter) || isObjectPattern(parameter)) && + parameter.typeAnnotation && + isTSTypeAnnotation(parameter.typeAnnotation) + ? parameter.typeAnnotation.typeAnnotation + : null + : isClassDeclaration(path.node) || isClassExpression(path.node) + ? (path.node.superTypeArguments?.params[0] ?? null) + : null; + const propsMembers = getPropsMembers(file, annotation); + const composes = getComposedTypeNames(file, annotation); + const defaults = getParameterDefaults( + parameter && isObjectPattern(parameter) ? parameter : null, + ); + + if (composes.length > 0) documentation.composes = composes; + if (propsMembers.length === 0) return; + + documentation.props = {}; + + for (const member of propsMembers) { + if (!isTSPropertySignature(member) || !isIdentifier(member.key)) continue; + const tsType = getTSType(file, member.typeAnnotation); + + if (!tsType) continue; + const defaultNode = defaults.get(member.key.name); + + documentation.props[member.key.name] = { + description: getDescription(file, member), + required: !member.optional, + tsType, + ...(defaultNode && isLiteral(defaultNode) + ? { + defaultValue: { + computed: false, + value: + defaultNode.raw ?? + file.source.code.slice( + defaultNode.range[0], + defaultNode.range[1], + ), + }, + } + : {}), + }; + } +}; + +export default typescriptPropsHandler; diff --git a/packages/typescript/src/index.ts b/packages/typescript/src/index.ts index ab41d1a0e60..3edfc133df6 100644 --- a/packages/typescript/src/index.ts +++ b/packages/typescript/src/index.ts @@ -1,28 +1,41 @@ import { - extract, - ProjectContext, + componentHandler, + contextHandler, + createDocgen, + createMethodHandler, + defaultPropsHandler, + propTypesHandler, + resolveComponentDefinitions, type ComponentDocumentation, + type Importer, } from '@react-docgen/core'; -import { handler, resolver } from './extractFunctionComponent.js'; +import typescriptPropsHandler from './handlers/typescriptPropsHandler.js'; import parser from './parser.js'; +import getTSType from './utils/getTSType.js'; export { default as parser, visitorKeys } from './parser.js'; export interface ParseOptions { filename?: string; + importer?: Importer; } +const docgen = createDocgen({ + handlers: [ + componentHandler, + typescriptPropsHandler, + propTypesHandler, + defaultPropsHandler, + contextHandler, + createMethodHandler(getTSType), + ], + parser, + resolver: resolveComponentDefinitions, +}); + export function parse( code: string, - { filename = 'component.tsx' }: ParseOptions = {}, + { filename = 'component.tsx', importer }: ParseOptions = {}, ): ComponentDocumentation[] { - const project = new ProjectContext({ - importer() { - throw new Error('Imports are not supported by this vertical slice.'); - }, - selectParser: () => parser, - }); - const file = project.parse({ code, filename }); - - return extract(file, resolver, [handler]); + return docgen(code, { filename, importer }); } diff --git a/packages/typescript/src/resolver/__tests__/findExportedDefinitions-test.ts b/packages/typescript/src/resolver/__tests__/findExportedDefinitions-test.ts new file mode 100644 index 00000000000..b385cde7c40 --- /dev/null +++ b/packages/typescript/src/resolver/__tests__/findExportedDefinitions-test.ts @@ -0,0 +1,21 @@ +import { findExportedDefinitions } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns supported named and default declarations only', () => { + const definitions = findExportedDefinitions( + parseFile(` + function Internal() {} + export function Named() {} + export default class Default {} + class CommonJs {} + exports.CommonJs = CommonJs; + `), + ); + + expect(definitions.map(({ node }) => node.type)).toEqual([ + 'FunctionDeclaration', + 'ClassDeclaration', + 'ClassDeclaration', + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts b/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts new file mode 100644 index 00000000000..6abb60a4d07 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts @@ -0,0 +1,20 @@ +import { + findExportedDefinitions, + findImperativeHandleMethods, +} from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds methods exposed through useImperativeHandle', () => { + const file = parseFile(` + export const Input = forwardRef(function Input(props, ref) { + useImperativeHandle(ref, () => ({ focus() {}, reset() {} })); + }); + `); + const [definition] = findExportedDefinitions(file); + + expect(definition?.node.type).toBe('FunctionExpression'); + expect( + definition && findImperativeHandleMethods(definition.node), + ).toHaveLength(2); +}); diff --git a/packages/typescript/src/utils/__tests__/findTopLevelDefinition-test.ts b/packages/typescript/src/utils/__tests__/findTopLevelDefinition-test.ts new file mode 100644 index 00000000000..53b49cf0d23 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/findTopLevelDefinition-test.ts @@ -0,0 +1,15 @@ +import { findTopLevelDefinition } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds named top-level functions and classes', () => { + const file = parseFile('function View() {} class Panel {}'); + + expect(findTopLevelDefinition(file, 'View')?.node.type).toBe( + 'FunctionDeclaration', + ); + expect(findTopLevelDefinition(file, 'Panel')?.node.type).toBe( + 'ClassDeclaration', + ); + expect(findTopLevelDefinition(file, 'Missing')).toBeNull(); +}); diff --git a/packages/typescript/src/utils/__tests__/getBody-test.ts b/packages/typescript/src/utils/__tests__/getBody-test.ts new file mode 100644 index 00000000000..34ca50471e6 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getBody-test.ts @@ -0,0 +1,12 @@ +import { getBody } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns program body paths', () => { + const body = getBody(parseFile('const first = 1; const second = 2;')); + + expect(body.map(({ node }) => node.type)).toEqual([ + 'VariableDeclaration', + 'VariableDeclaration', + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/getClassStaticValue-test.ts b/packages/typescript/src/utils/__tests__/getClassStaticValue-test.ts new file mode 100644 index 00000000000..3ade6718adf --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getClassStaticValue-test.ts @@ -0,0 +1,19 @@ +import { expect, test } from 'vitest'; +import { + findExportedDefinitions, + getClassStaticValue, + isLiteral, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('resolves a static getter return value', () => { + const file = parseFile( + 'const name = "Button"; export default class View { static get displayName() { return name; } }', + ); + const [definition] = findExportedDefinitions(file); + const value = definition + ? getClassStaticValue(file, definition, 'displayName') + : null; + + expect(value && isLiteral(value) ? value.value : null).toBe('Button'); +}); diff --git a/packages/typescript/src/utils/__tests__/getComponentDescription-test.ts b/packages/typescript/src/utils/__tests__/getComponentDescription-test.ts new file mode 100644 index 00000000000..0caad98cb30 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getComponentDescription-test.ts @@ -0,0 +1,19 @@ +import { + findExportedDefinitions, + getComponentDescription, +} from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('reads the docblock above a wrapped variable component', () => { + const file = parseFile(` + /** Wrapped component. */ + const Component = memo(forwardRef(() => null)); + export default Component; + `); + const [definition] = findExportedDefinitions(file); + + expect(definition && getComponentDescription(file, definition)).toBe( + 'Wrapped component.', + ); +}); diff --git a/packages/typescript/src/utils/__tests__/getComponentName-test.ts b/packages/typescript/src/utils/__tests__/getComponentName-test.ts new file mode 100644 index 00000000000..808c43de237 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getComponentName-test.ts @@ -0,0 +1,10 @@ +import { findTopLevelDefinition, getComponentName } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns declaration names', () => { + const file = parseFile('function View() {}'); + const definition = findTopLevelDefinition(file, 'View'); + + expect(definition && getComponentName(definition)).toBe('View'); +}); diff --git a/packages/typescript/src/utils/__tests__/getComposedTypeNames-test.ts b/packages/typescript/src/utils/__tests__/getComposedTypeNames-test.ts new file mode 100644 index 00000000000..4dd3c8e78ea --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getComposedTypeNames-test.ts @@ -0,0 +1,24 @@ +import { expect, test } from 'vitest'; +import { isTSTypeReference, type AstNode } from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; +import getComposedTypeNames from '../getComposedTypeNames.js'; + +test('reports only unresolved interface compositions', () => { + const file = parseFile( + 'interface Local {} interface Props extends Local, External {} function View(props: Props) {}', + ); + const fn = file.ast.body[2]; + const annotation = + fn?.params && Array.isArray(fn.params) + ? fn.params[0]?.typeAnnotation?.typeAnnotation + : null; + + expect( + annotation && + typeof annotation === 'object' && + 'type' in annotation && + isTSTypeReference(annotation as AstNode) + ? getComposedTypeNames(file, annotation as AstNode) + : [], + ).toEqual(['External']); +}); diff --git a/packages/typescript/src/utils/__tests__/getDescription-test.ts b/packages/typescript/src/utils/__tests__/getDescription-test.ts new file mode 100644 index 00000000000..7aac91d5265 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getDescription-test.ts @@ -0,0 +1,18 @@ +import { getBody, getDescription } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns only adjacent JSDoc descriptions', () => { + const file = parseFile( + '/** Component description. */\nexport function View() {}', + ); + const [declaration] = getBody(file); + + expect(declaration).toBeDefined(); + + if (declaration) { + expect(getDescription(file, declaration.node)).toBe( + 'Component description.', + ); + } +}); diff --git a/packages/typescript/src/utils/__tests__/getExplicitDisplayName-test.ts b/packages/typescript/src/utils/__tests__/getExplicitDisplayName-test.ts new file mode 100644 index 00000000000..01dccf24b0f --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getExplicitDisplayName-test.ts @@ -0,0 +1,13 @@ +import { getExplicitDisplayName } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds literal display name assignments', () => { + const file = parseFile(` + export function View() {} + View.displayName = 42; + `); + + expect(getExplicitDisplayName(file, 'View')).toBe(42); + expect(getExplicitDisplayName(file, 'Other')).toBeUndefined(); +}); diff --git a/packages/typescript/src/utils/__tests__/getMemberName-test.ts b/packages/typescript/src/utils/__tests__/getMemberName-test.ts new file mode 100644 index 00000000000..b909b21ead0 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getMemberName-test.ts @@ -0,0 +1,28 @@ +import { getBody, getMemberName } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns dotted member names', () => { + const file = parseFile('PropTypes.string.isRequired;'); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + + expect(expression && !Array.isArray(expression)).toBeTruthy(); + expect( + expression && !Array.isArray(expression) + ? getMemberName(expression.node) + : null, + ).toBe('PropTypes.string.isRequired'); +}); + +test('returns identifier names', () => { + const file = parseFile('useImperativeHandle();'); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + const callee = + expression && !Array.isArray(expression) ? expression.get('callee') : null; + + expect( + callee && !Array.isArray(callee) ? getMemberName(callee.node) : null, + ).toBe('useImperativeHandle'); +}); diff --git a/packages/typescript/src/utils/__tests__/getObjectProperties-test.ts b/packages/typescript/src/utils/__tests__/getObjectProperties-test.ts new file mode 100644 index 00000000000..fe3efa40f25 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getObjectProperties-test.ts @@ -0,0 +1,24 @@ +import { expect, test } from 'vitest'; +import { + getBody, + getObjectProperties, + isExpressionStatement, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('flattens local object spreads', () => { + const file = parseFile(` + const shared = { first: 1 }; + ({ ...shared, second: 2 }); + `); + const statement = getBody(file).at(-1); + + expect(statement && isExpressionStatement(statement.node)).toBe(true); + if (!statement || !isExpressionStatement(statement.node)) return; + + expect( + getObjectProperties(file, statement.node.expression).map( + (property) => property.key.type === 'Identifier' && property.key.name, + ), + ).toEqual(['first', 'second']); +}); diff --git a/packages/typescript/src/utils/__tests__/getParameterDefaults-test.ts b/packages/typescript/src/utils/__tests__/getParameterDefaults-test.ts new file mode 100644 index 00000000000..46a31b26945 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getParameterDefaults-test.ts @@ -0,0 +1,32 @@ +import { + findExportedDefinitions, + getParameterDefaults, + isFunctionDeclaration, + isObjectPattern, +} from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('collects destructured parameter defaults', () => { + const [definition] = findExportedDefinitions( + parseFile('export function View({ label = "Save", count }) {}'), + ); + + expect(definition).toBeDefined(); + + if (!definition || !isFunctionDeclaration(definition.node)) { + return; + } + + const [parameter] = definition.node.params; + + expect(parameter && isObjectPattern(parameter)).toBe(true); + + if (!parameter || !isObjectPattern(parameter)) { + return; + } + + expect([...getParameterDefaults(parameter)]).toEqual([ + ['label', expect.objectContaining({ type: 'Literal', value: 'Save' })], + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/getPropType-test.ts b/packages/typescript/src/utils/__tests__/getPropType-test.ts new file mode 100644 index 00000000000..05fc79078c6 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getPropType-test.ts @@ -0,0 +1,35 @@ +import { getBody, getPropType } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('extracts required built-in PropTypes', () => { + const file = parseFile('PropTypes.string.isRequired;'); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + + expect( + expression && !Array.isArray(expression) + ? getPropType(expression.node) + : null, + ).toEqual({ required: true, type: { name: 'string' } }); +}); + +test('extracts nested PropTypes calls', () => { + const file = parseFile( + 'PropTypes.oneOfType([PropTypes.string, PropTypes.number]);', + ); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + + expect( + expression && !Array.isArray(expression) + ? getPropType(expression.node) + : null, + ).toEqual({ + required: false, + type: { + name: 'union', + value: [{ name: 'string' }, { name: 'number' }], + }, + }); +}); diff --git a/packages/typescript/src/utils/__tests__/getPropertyName-test.ts b/packages/typescript/src/utils/__tests__/getPropertyName-test.ts new file mode 100644 index 00000000000..24ac2bac798 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getPropertyName-test.ts @@ -0,0 +1,30 @@ +import { expect, test } from 'vitest'; +import { + getPropertyName, + isObjectExpression, + isProperty, + isVariableDeclaration, + isVariableDeclarator, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('reads identifier and literal property names', () => { + const file = parseFile('const value = { plain: 1, ["text"]: 2, [2]: 3 };'); + const declaration = file.ast.body[0]; + const variable = + declaration && isVariableDeclaration(declaration) + ? declaration.declarations[0] + : null; + const object = + variable && isVariableDeclarator(variable) && variable.init + ? variable.init + : null; + const properties = + object && isObjectExpression(object) ? object.properties : []; + + expect( + properties.map((property) => + isProperty(property) ? getPropertyName(property.key) : null, + ), + ).toEqual(['plain', 'text', '2']); +}); diff --git a/packages/typescript/src/utils/__tests__/getPropsMembers-test.ts b/packages/typescript/src/utils/__tests__/getPropsMembers-test.ts new file mode 100644 index 00000000000..9b2d78d77b9 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getPropsMembers-test.ts @@ -0,0 +1,59 @@ +import { getBody } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; +import getPropsMembers from '../getPropsMembers.js'; + +function getMembers(source: string) { + const file = parseFile(source); + const body = getBody(file); + const exportPath = body.find( + ({ node }) => node.type === 'ExportNamedDeclaration', + ); + const declaration = exportPath?.get('declaration'); + const parameter = + declaration && !Array.isArray(declaration) + ? declaration.get('params') + : null; + const firstParameter = Array.isArray(parameter) ? parameter[0] : null; + const typeAnnotation = firstParameter?.get('typeAnnotation'); + const annotation = + typeAnnotation && !Array.isArray(typeAnnotation) + ? typeAnnotation.get('typeAnnotation') + : null; + + return annotation && !Array.isArray(annotation) + ? getPropsMembers(file, annotation.node) + : []; +} + +test('resolves referenced interface members', () => { + expect( + getMembers(` + interface Props { label: string; disabled?: boolean } + export function View(props: Props) {} + `).map((member) => member.type), + ).toEqual(['TSPropertySignature', 'TSPropertySignature']); +}); + +test('handles circular interface inheritance', () => { + expect( + getMembers(` + interface A extends B { a: number } + interface B extends A { b: number } + export function View(props: A) {} + `).map((member) => member.key), + ).toEqual([ + expect.objectContaining({ name: 'b' }), + expect.objectContaining({ name: 'a' }), + ]); +}); + +test('handles circular type aliases', () => { + expect( + getMembers(` + type Foo = Bar; + type Bar = Foo; + export function View(props: Foo) {} + `), + ).toEqual([]); +}); diff --git a/packages/typescript/src/utils/__tests__/getResolvedEnumValues-test.ts b/packages/typescript/src/utils/__tests__/getResolvedEnumValues-test.ts new file mode 100644 index 00000000000..9c30f1fae96 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getResolvedEnumValues-test.ts @@ -0,0 +1,33 @@ +import { expect, test } from 'vitest'; +import { + getResolvedEnumValues, + isCallExpression, + type AstNode, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('evaluates Object.keys passed to oneOf', () => { + const file = parseFile( + 'const values = { first: 1, second: 2 }; PropTypes.oneOf(Object.keys(values));', + ); + let call: AstNode | null = null; + + file.traverse( + { + CallExpression(path) { + if ( + isCallExpression(path.node) && + path.node.arguments[0]?.type === 'CallExpression' + ) { + call = path.node; + path.stop(); + } + }, + }, + undefined, + ); + expect(call ? getResolvedEnumValues(file, call) : null).toEqual([ + { computed: false, value: '"first"' }, + { computed: false, value: '"second"' }, + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/getTSType-test.ts b/packages/typescript/src/utils/__tests__/getTSType-test.ts new file mode 100644 index 00000000000..8604f2a6b62 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getTSType-test.ts @@ -0,0 +1,29 @@ +import { expect, test } from 'vitest'; +import { + isTSInterfaceDeclaration, + isTSPropertySignature, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; +import getTSType from '../getTSType.js'; + +test('serializes composite TypeScript types', () => { + const file = parseFile('interface Props { value: string | number[] }'); + const declaration = file.ast.body[0]; + const member = + declaration && isTSInterfaceDeclaration(declaration) + ? declaration.body.body[0] + : null; + + expect( + member && isTSPropertySignature(member) + ? getTSType(file, member.typeAnnotation) + : null, + ).toEqual({ + name: 'union', + raw: 'string | number[]', + elements: [ + { name: 'string' }, + { name: 'Array', elements: [{ name: 'number' }], raw: 'number[]' }, + ], + }); +}); diff --git a/packages/typescript/src/utils/__tests__/getTypeName-test.ts b/packages/typescript/src/utils/__tests__/getTypeName-test.ts new file mode 100644 index 00000000000..fb8cd91c071 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getTypeName-test.ts @@ -0,0 +1,28 @@ +import { getBody } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; +import getTypeName from '../getTypeName.js'; + +test('maps supported TypeScript annotations', () => { + const file = parseFile('type Props = { label: string; disabled: boolean };'); + const [alias] = getBody(file); + const annotation = alias?.get('typeAnnotation'); + const members = + annotation && !Array.isArray(annotation) ? annotation.get('members') : null; + + expect(Array.isArray(members)).toBe(true); + + if (!Array.isArray(members)) { + return; + } + + expect( + members.map((member) => { + const typeAnnotation = member.get('typeAnnotation'); + + return typeAnnotation && !Array.isArray(typeAnnotation) + ? getTypeName(typeAnnotation.node) + : null; + }), + ).toEqual(['string', 'boolean']); +}); diff --git a/packages/typescript/src/utils/__tests__/hasComponentAnnotation-test.ts b/packages/typescript/src/utils/__tests__/hasComponentAnnotation-test.ts new file mode 100644 index 00000000000..b8e757251f3 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/hasComponentAnnotation-test.ts @@ -0,0 +1,12 @@ +import { getBody, hasComponentAnnotation } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds an adjacent component annotation', () => { + const file = parseFile('// @component\nconst Component = () => null;'); + const [declaration] = getBody(file); + + expect(declaration && hasComponentAnnotation(file, declaration.node)).toBe( + true, + ); +}); diff --git a/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts b/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts new file mode 100644 index 00000000000..1de7d6dc9f1 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts @@ -0,0 +1,20 @@ +import { parseMethodDocblock } from '@react-docgen/core'; +import { expect, test } from 'vitest'; + +test('parses method summary, parameters, and return tags', () => { + const parsed = parseMethodDocblock( + 'Formats a value.\n@param {string=} value Input.\n@returns {number} Length.', + ); + + expect(parsed.description).toBe('Formats a value.'); + expect(parsed.params.get('value')).toEqual({ + description: 'Input.', + name: 'value', + optional: true, + type: { name: 'string' }, + }); + expect(parsed.returns).toEqual({ + description: 'Length.', + type: { name: 'number' }, + }); +}); diff --git a/packages/typescript/src/utils/__tests__/resolveComponentDefinition-test.ts b/packages/typescript/src/utils/__tests__/resolveComponentDefinition-test.ts new file mode 100644 index 00000000000..92bc156b81c --- /dev/null +++ b/packages/typescript/src/utils/__tests__/resolveComponentDefinition-test.ts @@ -0,0 +1,18 @@ +import { getBody, resolveComponentDefinition } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('resolves nested configured HOCs to their component', () => { + const file = parseFile(` + function View() {} + export default outer({ enabled: true }, inner('option', View)); + `); + const exportPath = getBody(file).at(-1); + const declaration = exportPath?.get('declaration'); + + expect( + declaration && !Array.isArray(declaration) + ? resolveComponentDefinition(file, declaration)?.node.type + : null, + ).toBe('FunctionDeclaration'); +}); diff --git a/packages/typescript/src/utils/__tests__/resolveValue-test.ts b/packages/typescript/src/utils/__tests__/resolveValue-test.ts new file mode 100644 index 00000000000..b87ea5b1d9e --- /dev/null +++ b/packages/typescript/src/utils/__tests__/resolveValue-test.ts @@ -0,0 +1,26 @@ +import { expect, test } from 'vitest'; +import { + isLiteral, + isVariableDeclaration, + isVariableDeclarator, + resolveValue, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('resolves a value imported from another file', () => { + const file = parseFile( + 'import { label } from "./values"; const value = label;', + 'component.tsx', + () => ({ code: 'export const label = "Save";', filename: 'values.ts' }), + ); + const declaration = file.ast.body[1]; + const variable = + declaration && isVariableDeclaration(declaration) + ? declaration.declarations[0] + : null; + const init = + variable && isVariableDeclarator(variable) ? variable.init : null; + const value = init ? resolveValue(file, init) : null; + + expect(value && isLiteral(value) ? value.value : null).toBe('Save'); +}); diff --git a/packages/typescript/src/utils/__tests__/unwrapExpression-test.ts b/packages/typescript/src/utils/__tests__/unwrapExpression-test.ts new file mode 100644 index 00000000000..92388637671 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/unwrapExpression-test.ts @@ -0,0 +1,18 @@ +import { expect, test } from 'vitest'; +import { unwrapExpression, type AstNode } from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('unwraps nested TypeScript expression wrappers', () => { + const file = parseFile('const value = (input as unknown as string)!;'); + const declaration = file.ast.body[0]; + const init = + declaration?.declarations && Array.isArray(declaration.declarations) + ? declaration.declarations[0]?.init + : null; + + expect( + init && typeof init === 'object' && 'type' in init + ? unwrapExpression(init as AstNode) + : null, + ).toMatchObject({ type: 'Identifier', name: 'input' }); +}); diff --git a/packages/typescript/src/utils/getComposedTypeNames.ts b/packages/typescript/src/utils/getComposedTypeNames.ts new file mode 100644 index 00000000000..35e2f1d22e1 --- /dev/null +++ b/packages/typescript/src/utils/getComposedTypeNames.ts @@ -0,0 +1,75 @@ +import { + isExportNamedDeclaration, + isIdentifier, + isTSInterfaceDeclaration, + isTSTypeReference, + type AstNode, + type FileState, + getBody, +} from '@react-docgen/core'; + +export default function getComposedTypeNames( + file: FileState, + annotation: AstNode | null, +): string[] { + if ( + !annotation || + !isTSTypeReference(annotation) || + !isIdentifier(annotation.typeName) + ) { + return []; + } + + const localNames = new Set( + getBody(file).flatMap((path) => { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + const id = declaration.id; + + return (isTSInterfaceDeclaration(declaration) || + declaration.type === 'TSTypeAliasDeclaration') && + id && + typeof id === 'object' && + 'type' in id && + isIdentifier(id as AstNode) + ? [(id as AstNode & { name: string }).name] + : []; + }), + ); + + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + + if ( + !isTSInterfaceDeclaration(declaration) || + declaration.id.name !== annotation.typeName.name + ) { + continue; + } + const heritage = Array.isArray(declaration.extends) + ? declaration.extends + : []; + + return heritage.flatMap((item) => { + if (!item || typeof item !== 'object' || !('expression' in item)) + return []; + const expression = item.expression; + + return expression && + typeof expression === 'object' && + 'type' in expression && + isIdentifier(expression as AstNode) + ? localNames.has((expression as { name: string }).name) + ? [] + : [(expression as { name: string }).name] + : []; + }); + } + + return []; +} diff --git a/packages/typescript/src/utils/getPropsMembers.ts b/packages/typescript/src/utils/getPropsMembers.ts new file mode 100644 index 00000000000..cab0846ee98 --- /dev/null +++ b/packages/typescript/src/utils/getPropsMembers.ts @@ -0,0 +1,213 @@ +import { + isIdentifier, + isExportNamedDeclaration, + isTSInterfaceDeclaration, + isTSTypeAliasDeclaration, + isTSTypeLiteral, + isTSTypeReference, + type AstNode, + type FileState, + getBody, + getValueFile, + resolveValue, +} from '@react-docgen/core'; + +function child(node: AstNode, key: string): AstNode | null { + const value = node[key]; + + return value && typeof value === 'object' && 'type' in value + ? (value as AstNode) + : null; +} + +function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function substitute(node: AstNode, parameters: Map): AstNode { + if (isIdentifier(node) && parameters.has(node.name)) { + const value = parameters.get(node.name); + + return value && isTSTypeReference(value) ? value.typeName : (value ?? node); + } + + const result: Record = { ...node }; + + for (const [key, value] of Object.entries(result)) { + if (Array.isArray(value)) { + result[key] = value.map((item) => + item && typeof item === 'object' && 'type' in item + ? substitute(item as AstNode, parameters) + : item, + ); + } else if (value && typeof value === 'object' && 'type' in value) { + result[key] = substitute(value as AstNode, parameters); + } + } + + return result as AstNode; +} + +function parametersFor( + declaration: AstNode, + reference: AstNode, +): Map { + const declared = child(declaration, 'typeParameters'); + const provided = + child(reference, 'typeArguments') ?? child(reference, 'typeParameters'); + const values = provided ? nodes(provided, 'params') : []; + + return new Map( + (declared ? nodes(declared, 'params') : []).flatMap((parameter, index) => { + const name = child(parameter, 'name') ?? parameter; + const value = values[index]; + + return isIdentifier(name) && value ? [[name.name, value]] : []; + }), + ); +} + +export default function getPropsMembers( + file: FileState, + annotation: AstNode | null, + seen = new WeakSet(), +): AstNode[] { + if (!annotation) return []; + if (isTSTypeLiteral(annotation)) return annotation.members; + + if (annotation.type === 'TSIntersectionType') { + return nodes(annotation, 'types').flatMap((type) => + getPropsMembers(file, type), + ); + } + + if (!isTSTypeReference(annotation)) return []; + const typeName = annotation.typeName; + + if (!isIdentifier(typeName)) { + const wrapperName = Array.isArray(typeName.range) + ? file.source.code.slice(typeName.range[0], typeName.range[1]) + : ''; + + if ( + /^(?:React\.)?Props(?:WithChildren|WithRef|WithoutRef)$/.test(wrapperName) + ) { + const argumentsNode = + child(annotation, 'typeArguments') ?? + child(annotation, 'typeParameters'); + const [wrapped] = argumentsNode ? nodes(argumentsNode, 'params') : []; + + return getPropsMembers(file, wrapped ?? null); + } + + return []; + } + + const importedDeclaration = resolveValue(file, typeName); + + if (importedDeclaration !== typeName) { + const importedFile = getValueFile(file, importedDeclaration); + + if (isTSTypeAliasDeclaration(importedDeclaration)) { + if (seen.has(importedDeclaration)) return []; + seen.add(importedDeclaration); + const members = getPropsMembers( + importedFile, + importedDeclaration.typeAnnotation, + seen, + ); + + seen.delete(importedDeclaration); + + return members; + } + if (isTSInterfaceDeclaration(importedDeclaration)) { + if (seen.has(importedDeclaration)) return []; + seen.add(importedDeclaration); + const inherited = nodes(importedDeclaration, 'extends').flatMap( + (heritage) => { + const expression = child(heritage, 'expression'); + + if (!expression) return []; + + return getPropsMembers( + importedFile, + { + ...heritage, + type: 'TSTypeReference', + typeName: expression, + } as AstNode, + seen, + ); + }, + ); + + seen.delete(importedDeclaration); + + return [...inherited, ...importedDeclaration.body.body]; + } + } + + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + + if ( + isTSTypeAliasDeclaration(declaration) && + declaration.id.name === typeName.name + ) { + if (seen.has(declaration)) return []; + seen.add(declaration); + const members = getPropsMembers( + file, + declaration.typeAnnotation, + seen, + ).map((member) => + substitute(member, parametersFor(declaration, annotation)), + ); + + seen.delete(declaration); + + return members; + } + + if ( + isTSInterfaceDeclaration(declaration) && + declaration.id.name === typeName.name + ) { + if (seen.has(declaration)) return []; + seen.add(declaration); + const parameters = parametersFor(declaration, annotation); + const inherited = nodes(declaration, 'extends').flatMap((heritage) => { + const expression = child(heritage, 'expression'); + + if (!expression) return []; + const reference = { + ...heritage, + type: 'TSTypeReference', + typeName: expression, + } as AstNode; + + return getPropsMembers(file, reference, seen); + }); + + const members = [...inherited, ...declaration.body.body].map((member) => + substitute(member, parameters), + ); + + seen.delete(declaration); + + return members; + } + } + + return []; +} diff --git a/packages/typescript/src/utils/getTSType.ts b/packages/typescript/src/utils/getTSType.ts new file mode 100644 index 00000000000..031a2b9c64a --- /dev/null +++ b/packages/typescript/src/utils/getTSType.ts @@ -0,0 +1,358 @@ +import { + isIdentifier, + isTSPropertySignature, + isTSTypeAliasDeclaration, + isTSTypeAnnotation, + isTSTypeReference, + type AstNode, + type FileState, + type TypeDescriptor, + getBody, + getDescription, + getPropertyName, +} from '@react-docgen/core'; + +function source(file: FileState, node: AstNode): string { + const value = Array.isArray(node.range) + ? file.source.code.slice(node.range[0], node.range[1]) + : ''; + + if (!value.includes('\n')) return value; + const lines = value.split('\n'); + const closingIndent = /^(\s*)/.exec(lines.at(-1) ?? '')?.[1]?.length ?? 0; + + return lines + .map((line, index) => + index === 0 ? line : line.slice(Math.min(closingIndent, line.length)), + ) + .join('\n'); +} + +function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function child(node: AstNode, key: string): AstNode | null { + const value = node[key]; + + return value && typeof value === 'object' && 'type' in value + ? (value as AstNode) + : null; +} + +function typeName(file: FileState, node: AstNode): string { + return isIdentifier(node) + ? node.name + : source(file, node).replaceAll('.', ''); +} + +function replaceTypeParameter( + node: AstNode, + name: string, + value: AstNode, +): AstNode { + if (isIdentifier(node, { name })) { + return isTSTypeReference(value) ? value.typeName : value; + } + const result: Record = { ...node }; + + for (const [key, item] of Object.entries(result)) { + if (Array.isArray(item)) { + result[key] = item.map((entry) => + entry && typeof entry === 'object' && 'type' in entry + ? replaceTypeParameter(entry as AstNode, name, value) + : entry, + ); + } else if (item && typeof item === 'object' && 'type' in item) { + result[key] = replaceTypeParameter(item as AstNode, name, value); + } + } + + return result as AstNode; +} + +function objectType( + file: FileState, + node: AstNode, + resolving: Set, +): TypeDescriptor { + const properties = nodes(node, 'members').flatMap((member) => { + if (!isTSPropertySignature(member)) return []; + const key = getPropertyName(member.key); + const annotation = member.typeAnnotation + ? getTSType(file, member.typeAnnotation, resolving) + : null; + const description = getDescription(file, member); + + return key && annotation + ? [ + { + key, + value: { ...annotation, required: !member.optional }, + ...(description ? { description } : {}), + }, + ] + : []; + }); + + return { + name: 'signature', + type: 'object', + raw: source(file, node), + signature: { properties }, + }; +} + +function functionType(file: FileState, node: AstNode): TypeDescriptor { + const parameters = nodes(node, 'params'); + const returnType = child(node, 'returnType'); + + return { + name: 'signature', + type: 'function', + raw: source(file, node), + signature: { + arguments: parameters.flatMap((parameter) => { + const annotation = child(parameter, 'typeAnnotation'); + const nameNode = + parameter.type === 'RestElement' + ? child(parameter, 'argument') + : parameter; + const name = + nameNode && isIdentifier(nameNode) + ? nameNode.name + : source(file, nameNode ?? parameter); + + return annotation + ? [ + { + type: getTSType(file, annotation), + name, + ...(parameter.type === 'RestElement' ? { rest: true } : {}), + ...(parameter.optional ? { optional: true } : {}), + }, + ] + : []; + }), + return: returnType ? getTSType(file, returnType) : { name: 'void' }, + }, + }; +} + +export default function getTSType( + file: FileState, + input: AstNode | undefined, + resolving = new Set(), +): TypeDescriptor | null { + if (!input) return null; + const node = isTSTypeAnnotation(input) ? input.typeAnnotation : input; + const keywords: Record = { + TSAnyKeyword: 'any', + TSBooleanKeyword: 'boolean', + TSNeverKeyword: 'never', + TSNullKeyword: 'null', + TSNumberKeyword: 'number', + TSObjectKeyword: 'object', + TSStringKeyword: 'string', + TSSymbolKeyword: 'symbol', + TSUndefinedKeyword: 'undefined', + TSUnknownKeyword: 'unknown', + TSVoidKeyword: 'void', + }; + const keyword = keywords[node.type]; + + if (keyword) return { name: keyword }; + + if (node.type === 'TSLiteralType') { + const literal = child(node, 'literal'); + + return literal ? { name: 'literal', value: source(file, literal) } : null; + } + + if (node.type === 'TSUnionType' || node.type === 'TSIntersectionType') { + return { + name: node.type === 'TSUnionType' ? 'union' : 'intersection', + raw: source(file, node), + elements: nodes(node, 'types').flatMap((item) => { + const type = getTSType(file, item); + + return type ? [type] : []; + }), + }; + } + + if (node.type === 'TSArrayType') { + const element = child(node, 'elementType'); + + return { + name: 'Array', + elements: element ? [getTSType(file, element)].filter(Boolean) : [], + raw: source(file, node), + }; + } + + if (node.type === 'TSTupleType') { + return { + name: 'tuple', + raw: source(file, node), + elements: nodes(node, 'elementTypes').flatMap((item) => { + const type = getTSType(file, item); + + return type ? [type] : []; + }), + }; + } + + if (node.type === 'TSFunctionType') return functionType(file, node); + if (node.type === 'TSTypeLiteral') return objectType(file, node, resolving); + + if (node.type === 'TSTypeReference') { + const nameNode = child(node, 'typeName'); + + if (!nameNode) return null; + const name = typeName(file, nameNode); + + for (const statement of getBody(file)) { + if ( + isTSTypeAliasDeclaration(statement.node) && + statement.node.id.name === name && + !resolving.has(name) && + (statement.node.typeAnnotation.type === 'TSTupleType' || + statement.node.typeAnnotation.type === 'TSUnionType' || + statement.node.typeAnnotation.type === 'TSIntersectionType' || + statement.node.typeAnnotation.type === 'TSTypeLiteral' || + statement.node.typeAnnotation.type === 'TSArrayType' || + statement.node.typeAnnotation.type === 'TSTypeReference') + ) { + resolving.add(name); + let annotation = statement.node.typeAnnotation; + const declared = child(statement.node, 'typeParameters'); + const provided = + child(node, 'typeArguments') ?? child(node, 'typeParameters'); + const [parameter] = declared ? nodes(declared, 'params') : []; + const [argument] = provided ? nodes(provided, 'params') : []; + const parameterName = parameter + ? (child(parameter, 'name') ?? parameter) + : null; + + if (parameterName && isIdentifier(parameterName) && argument) { + annotation = replaceTypeParameter( + annotation, + parameterName.name, + argument, + ); + } + const result = getTSType(file, annotation, resolving); + + resolving.delete(name); + + return result; + } + } + + const typeArguments = + child(node, 'typeArguments') ?? child(node, 'typeParameters'); + const elements = typeArguments + ? nodes(typeArguments, 'params').flatMap((item) => { + const type = getTSType(file, item); + + return type ? [type] : []; + }) + : []; + + return { + name, + ...(source(file, node) !== name && + (source(file, node).includes('<') || source(file, node).includes('.')) + ? { raw: source(file, node) } + : {}), + ...(elements.length ? { elements } : {}), + }; + } + + if (node.type === 'TSTypeQuery') { + const expression = child(node, 'exprName'); + + return { name: expression ? source(file, expression) : source(file, node) }; + } + + if (node.type === 'TSIndexedAccessType') { + const raw = source(file, node); + const object = child(node, 'objectType'); + const index = child(node, 'indexType'); + const name = + index?.type === 'TSTypeOperator' + ? `${object ? source(file, object).replace(/^./, (value) => value.toLowerCase()) : ''}[${getTSType(file, index, resolving)?.name ?? ''}]` + : raw.replace(/^typeof\s+/, ''); + + return { name, raw }; + } + + if (node.type === 'TSTypeOperator') { + const annotation = child(node, 'typeAnnotation'); + + if (node.operator === 'keyof' && annotation?.type === 'TSTypeLiteral') { + return { + name: 'union', + raw: source(file, node), + elements: nodes(annotation, 'members').flatMap((member) => { + if (!isTSPropertySignature(member)) return []; + const key = getPropertyName(member.key); + + return key ? [{ name: 'literal', value: key }] : []; + }), + }; + } + const raw = annotation ? source(file, annotation) : source(file, node); + + return { name: raw.replace(/^./, (value) => value.toLowerCase()) }; + } + + if (node.type === 'TSMappedType') { + const typeParameter = child(node, 'typeParameter'); + const constraint = + child(node, 'constraint') ?? + (typeParameter ? child(typeParameter, 'constraint') : null); + const annotation = child(node, 'typeAnnotation'); + const keyType = constraint ? getTSType(file, constraint, resolving) : null; + const resolvedValue = annotation + ? getTSType(file, annotation, resolving) + : null; + const valueType = resolvedValue + ? { + ...resolvedValue, + name: resolvedValue.name.replace(/^./, (value) => + value.toLowerCase(), + ), + } + : null; + + return { + name: 'signature', + type: 'object', + raw: source(file, node), + signature: { + properties: + keyType && valueType + ? [ + { + key: { + name: keyType.name, + required: !node.optional, + }, + value: valueType, + }, + ] + : [], + }, + }; + } + + return { name: source(file, node) || node.type }; +} diff --git a/packages/typescript/src/utils/getTypeName.ts b/packages/typescript/src/utils/getTypeName.ts new file mode 100644 index 00000000000..4ab64f39a74 --- /dev/null +++ b/packages/typescript/src/utils/getTypeName.ts @@ -0,0 +1,22 @@ +import { + isTSBooleanKeyword, + isTSStringKeyword, + isTSTypeAnnotation, + type AstNode, +} from '@react-docgen/core'; + +export default function getTypeName(node: AstNode | undefined): string | null { + if (!node || !isTSTypeAnnotation(node)) { + return null; + } + + if (isTSStringKeyword(node.typeAnnotation)) { + return 'string'; + } + + if (isTSBooleanKeyword(node.typeAnnotation)) { + return 'boolean'; + } + + return null; +} diff --git a/packages/typescript/tests/integration/babel-differential-test.ts b/packages/typescript/tests/integration/babel-differential-test.ts new file mode 100644 index 00000000000..3516c5b753d --- /dev/null +++ b/packages/typescript/tests/integration/babel-differential-test.ts @@ -0,0 +1,37 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { describe, expect, test } from 'vitest'; +import { parse as parseBabel } from '@react-docgen/babel'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { parse as parseTypeScript } from '../../src/index.js'; + +function importer(specifier: string, fromFilename: string) { + const base = path.resolve(path.dirname(fromFilename), specifier); + const extensionless = base.replace(/\.[^./]+$/, ''); + const filename = [base, `${extensionless}.js`, `${extensionless}.jsx`].find( + (candidate) => fs.existsSync(candidate), + ); + + if (!filename) throw new Error(`Cannot resolve ${specifier}.`); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; +} + +describe('Babel differential', () => { + for (const integrationCase of loadIntegrationCases({ languages: ['js'] })) { + if (!integrationCase.output) continue; + test(integrationCase.id, () => { + const typescriptOutput = parseTypeScript(integrationCase.source, { + filename: integrationCase.filename, + importer, + }); + const babelOutput = parseBabel(integrationCase.source, { + filename: integrationCase.filename, + importer, + }); + + expect(babelOutput).toEqual(typescriptOutput); + expect(typescriptOutput).toEqual(integrationCase.output); + }); + } +}); diff --git a/packages/typescript/tests/integration/integration-test.ts b/packages/typescript/tests/integration/integration-test.ts index b5304560aaa..bb8d5a8d87a 100644 --- a/packages/typescript/tests/integration/integration-test.ts +++ b/packages/typescript/tests/integration/integration-test.ts @@ -1,10 +1,72 @@ import { describe, expect, test } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; import { parse } from '../../src/index.js'; const supportedCases = [ 'js/definitions/function-declaration', + 'js/definitions/annotated-function', + 'js/definitions/custom-base-class-render', + 'js/definitions/configured-nested-hoc', + 'js/definitions/hoc-wrapped-component', + 'js/definitions/class-expression-static-assignments', + 'js/definitions/assigned-class-invalid-display-name', + 'js/definitions/numeric-display-name', + 'js/definitions/display-name-resolution', + 'js/definitions/react-create-class-assignment', + 'js/definitions/react-create-class-variable', + 'js/exports/commonjs-named', + 'js/exports/commonjs-module', + 'js/exports/computed-commonjs', + 'js/errors/missing-definition', + 'js/errors/multiple-definitions', + 'js/defaults/memo-forward-ref', + 'js/defaults/destructured-bindings', + 'js/defaults/function-default-props', + 'js/defaults/value-serialization', + 'js/defaults/computed-property', + 'js/defaults/spreads-and-parameters', + 'js/defaults/unresolved-enum', + 'js/props/all-proptypes', + 'js/props/package-proptypes-context', + 'js/props/react-proptypes-context', + 'js/props/shape-exact-and-union', + 'js/props/composed-and-custom-validators', + 'js/props/literal-computed-keys', + 'js/props/nested-shape-inheritance', + 'js/props/object-key-and-value-enums', + 'js/methods/class-methods', + 'js/methods/class-method-documentation', + 'js/methods/jsdoc-variants', + 'js/methods/parameter-shapes', + 'js/methods/imperative-handle', + 'js/regressions/class-static-getters', + 'js/imports/export-star-chain', + 'js/imports/imported-defaults-and-enums', + 'js/imports/member-proptypes', + 'js/imports/namespace-reexport', + 'js/imports/reexported-proptypes', + 'js/imports/spread-proptypes', 'typescript/defaults/function-default-parameters', + 'typescript/defaults/forward-ref-parameter-default', + 'typescript/definitions/anonymous-default-class', + 'typescript/exports/namespace-reexport', + 'typescript/types/comprehensive-props', + 'typescript/types/nested-object-and-union', + 'typescript/types/type-alias-intersection', + 'typescript/types/interface-composition', + 'typescript/types/react-prop-wrappers', + 'typescript/types/advanced-props', + 'typescript/types/indexed-access-constant', + 'typescript/types/generic-interface-extension', + 'typescript/methods/class-methods', + 'typescript/methods/modifiers-and-types', + 'typescript/regressions/circular-interface-inheritance', + 'typescript/regressions/circular-type-aliases', + 'typescript/regressions/polymorphic-forward-ref', + 'typescript/imports/extended-props', + 'typescript/imports/imported-props', ]; describe('integration', () => { @@ -12,11 +74,33 @@ describe('integration', () => { ids: supportedCases, })) { test(integrationCase.id, () => { - expect( + const run = () => parse(integrationCase.source, { filename: integrationCase.filename, - }), - ).toEqual(integrationCase.output); + importer(specifier, fromFilename) { + const base = path.resolve(path.dirname(fromFilename), specifier); + const extensionless = base.replace(/\.[^./]+$/, ''); + const filename = [ + base, + `${extensionless}.js`, + `${extensionless}.jsx`, + `${extensionless}.ts`, + `${extensionless}.tsx`, + ].find((candidate) => fs.existsSync(candidate)); + + if (!filename) throw new Error(`Cannot resolve ${specifier}.`); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; + }, + }); + + if (integrationCase.error) { + expect(run).toThrow( + expect.objectContaining({ code: integrationCase.error.code }), + ); + } else { + expect(run()).toEqual(integrationCase.output); + } }); } }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9159b671426..6329382608a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -233,6 +233,22 @@ importers: specifier: 5.0.5 version: 5.0.5(@types/node@22.20.5)(@vitest/coverage-v8@5.0.5)(vite@8.3.5(@types/node@22.20.5)(jiti@2.7.0)(yaml@2.9.1)) + packages/babel: + dependencies: + '@react-docgen/core': + specifier: workspace:* + version: link:../core + devDependencies: + '@babel/core': + specifier: 7.29.7 + version: 7.29.7(supports-color@7.2.0) + '@babel/types': + specifier: 7.29.8 + version: 7.29.8 + '@types/babel__core': + specifier: 7.20.5 + version: 7.20.5 + packages/benchmark: dependencies: benchmark: @@ -329,6 +345,9 @@ importers: '@react-docgen-internal/integration-tests': specifier: workspace:* version: link:../integration-tests + '@react-docgen/babel': + specifier: workspace:* + version: link:../babel packages/website: dependencies: @@ -355,7 +374,7 @@ importers: version: 19.3.0(@types/react@19.3.0) '@uiw/react-codemirror': specifier: 4.25.12 - version: 4.25.12(@babel/runtime@7.29.10)(@codemirror/autocomplete@6.20.3)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.15)(codemirror@6.0.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + version: 4.25.12(@babel/runtime@7.29.10)(@codemirror/autocomplete@6.20.4)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.15)(codemirror@6.0.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) clsx: specifier: 2.1.1 version: 2.1.1 @@ -581,8 +600,8 @@ packages: resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==} engines: {node: '>= 20.12.0'} - '@codemirror/autocomplete@6.20.3': - resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==} + '@codemirror/autocomplete@6.20.4': + resolution: {integrity: sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==} '@codemirror/commands@6.11.1': resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==} @@ -951,8 +970,8 @@ packages: '@keyv/serialize@1.1.1': resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} - '@lezer/common@1.5.3': - resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==} + '@lezer/common@1.5.4': + resolution: {integrity: sha512-xt3Q4z64xM+xhg4M7NXqw1N//1O74bUFo5kz6fwMeC4qwxSuRdwkYSmjcqCEEKYkNw5e67f2hcNqBoNERAEU0w==} '@lezer/highlight@1.2.5': resolution: {integrity: sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==} @@ -1228,8 +1247,8 @@ packages: cpu: [x64] os: [win32] - '@oxc-project/types@0.154.0': - resolution: {integrity: sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==} + '@oxc-project/types@0.155.0': + resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} '@pagefind/darwin-arm64@1.5.2': resolution: {integrity: sha512-MXpI+7HsAdPkvJ0gk9xj9g541BCqBZOBbdwj9g6lB5LCj6kSV6nqDSjzcAJwvOsfu0fjwvC8hQU+ecfhp+MpiQ==} @@ -1291,98 +1310,98 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 - '@rolldown/binding-android-arm-eabi@1.2.14': - resolution: {integrity: sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==} + '@rolldown/binding-android-arm-eabi@1.2.15': + resolution: {integrity: sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] - '@rolldown/binding-android-arm64@1.2.14': - resolution: {integrity: sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ==} + '@rolldown/binding-android-arm64@1.2.15': + resolution: {integrity: sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@rolldown/binding-darwin-arm64@1.2.14': - resolution: {integrity: sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw==} + '@rolldown/binding-darwin-arm64@1.2.15': + resolution: {integrity: sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rolldown/binding-darwin-x64@1.2.14': - resolution: {integrity: sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA==} + '@rolldown/binding-darwin-x64@1.2.15': + resolution: {integrity: sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rolldown/binding-freebsd-x64@1.2.14': - resolution: {integrity: sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA==} + '@rolldown/binding-freebsd-x64@1.2.15': + resolution: {integrity: sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rolldown/binding-linux-arm-gnueabihf@1.2.14': - resolution: {integrity: sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg==} + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': + resolution: {integrity: sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@rolldown/binding-linux-arm64-gnu@1.2.14': - resolution: {integrity: sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ==} + '@rolldown/binding-linux-arm64-gnu@1.2.15': + resolution: {integrity: sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-arm64-musl@1.2.14': - resolution: {integrity: sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg==} + '@rolldown/binding-linux-arm64-musl@1.2.15': + resolution: {integrity: sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@rolldown/binding-linux-ppc64-gnu@1.2.14': - resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==} + '@rolldown/binding-linux-ppc64-gnu@1.2.15': + resolution: {integrity: sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-s390x-gnu@1.2.14': - resolution: {integrity: sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A==} + '@rolldown/binding-linux-s390x-gnu@1.2.15': + resolution: {integrity: sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-gnu@1.2.14': - resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==} + '@rolldown/binding-linux-x64-gnu@1.2.15': + resolution: {integrity: sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-musl@1.2.14': - resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==} + '@rolldown/binding-linux-x64-musl@1.2.15': + resolution: {integrity: sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@rolldown/binding-openharmony-arm64@1.2.14': - resolution: {integrity: sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q==} + '@rolldown/binding-openharmony-arm64@1.2.15': + resolution: {integrity: sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@rolldown/binding-win32-arm64-msvc@1.2.14': - resolution: {integrity: sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA==} + '@rolldown/binding-win32-arm64-msvc@1.2.15': + resolution: {integrity: sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@rolldown/binding-win32-x64-msvc@1.2.14': - resolution: {integrity: sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ==} + '@rolldown/binding-win32-x64-msvc@1.2.15': + resolution: {integrity: sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -1419,8 +1438,8 @@ packages: '@shikijs/types@3.23.0': resolution: {integrity: sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==} - '@shikijs/vscode-textmate@10.0.2': - resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} + '@shikijs/vscode-textmate@10.1.0': + resolution: {integrity: sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==} '@sindresorhus/merge-streams@4.0.0': resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==} @@ -1521,14 +1540,14 @@ packages: '@tailwindcss/postcss@4.3.3': resolution: {integrity: sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg==} - '@tanstack/react-virtual@3.14.20': - resolution: {integrity: sha512-9hbhFlc0lznjXmWYDB/KEl7PJxEPz0Qnj2FzJFse98miGvXtx7jzjE5jlasmtczmZ6TxXsyI4v7PuyGQm2q1nQ==} + '@tanstack/react-virtual@3.14.21': + resolution: {integrity: sha512-wWE/ZJDNNDp18JHWy7n5PQooqerHePVkEEu6Op0twKQ2InF9DPhYMQptQY0syDEviMd3/r8D0OUvKJibDGm9HQ==} peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - '@tanstack/virtual-core@3.19.5': - resolution: {integrity: sha512-X/wq6DtSK/XClznMM+I4JE63yyIwmyPk4Ts83bD0VKaIbwHNdRsO5QipCPX+3OovqYyr0puQNpbmp8+SPhspNg==} + '@tanstack/virtual-core@3.19.6': + resolution: {integrity: sha512-CsTW892z23gy7IyxYTTorVu1uZWB+0N349rSMgKz4rFLPpLza7F7TpcCKeI5iUAwYQCt8QUlOU67J+KXCxtpGw==} '@theguild/remark-mermaid@0.3.0': resolution: {integrity: sha512-Fy1J4FSj8totuHsHFpaeWyWRaRSIvpzGTRoEfnNJc1JmLV9uV70sYE3zcT+Jj5Yw20Xq4iCsiT+3Ho49BBZcBQ==} @@ -1744,6 +1763,12 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/project-service@8.67.0': + resolution: {integrity: sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/project-service@8.72.0': resolution: {integrity: sha512-bzHngBbmIgzj6TsTjVUCntGx6FFLgE7mPjpO0PzHycOaZHXqS43XnrkFIHRS16LLr/xO6FHSXG3GJFo/F4bSBQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1754,6 +1779,12 @@ packages: resolution: {integrity: sha512-JewPyJOYcXBSAS7PIgufscHOwZqhTGyBRiQJhhuDln66tMchxvvt7nJ90JKKIoOelmdHA3kAQbm9cEUHc4JSEA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/tsconfig-utils@8.67.0': + resolution: {integrity: sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/tsconfig-utils@8.72.0': resolution: {integrity: sha512-0vbxCf7xLVPSjcOdm6eQbgViH8EDJ8xnl1laLT9yoqSz2YmcSfSg5Vdl0JUvZf6rcuJ0ZivJIuMD4edTg8obaA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1767,10 +1798,20 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/types@8.67.0': + resolution: {integrity: sha512-sBtgslww8nsMYUjhdPBiSyUqSzT8uR6g93A2QXnQC8+cGdjz0CyaOdqHDRJb1AtORbZCNUJBBeFA/tNR2uQmww==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/types@8.72.0': resolution: {integrity: sha512-Adfoy59kxNEjT5E5fnyrp7GpHYuWs8ONbdohu4ez6IU46qDq8LltG90tLmkucZB2uhYL8mqBjtXqGd8yhfjXqQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/typescript-estree@8.67.0': + resolution: {integrity: sha512-EKQBCE9yNlRJYm7jdTW5AhDacDUmSwQb0FAJAmK2EKYrNXIsa2vxcSZx6PvJ/dEdI6lS+Y9W+EXckLj0iPFGcw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/typescript-estree@8.72.0': resolution: {integrity: sha512-gwLfFgWcw15tN2KXDCJvxEOQjPn+P3j/n3eSqkZ5sX4VpW9Cosodr+tWwBZRvJT3TcKx6HnPRGZMCNAiP1Xhug==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1784,6 +1825,10 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/visitor-keys@8.67.0': + resolution: {integrity: sha512-fkv8dHRDqfGtTHuJeebdrQ7cX6Ad4WAS00rgHh9UGvMycF1mjBfsxry1XsLIFhWZ6Judlh6UdzK+TYlbpCXgnA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/visitor-keys@8.72.0': resolution: {integrity: sha512-E2mroviasaWecDzTGiGMtuEguuLVOeRggnrIn93CJuxYJzQBHbyymlT08aVQydbBal5538o+JkBKXh2sRuCyIA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2101,8 +2146,8 @@ packages: base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} - baseline-browser-mapping@2.11.29: - resolution: {integrity: sha512-YeesxhUmR4h5y5V8KF8iBCqJb8YFrBJ++XBTeGcWIaQOYXGN19JM0FoiOjAhwuDoln8owMgXcWBmgHtYSkky2w==} + baseline-browser-mapping@2.11.30: + resolution: {integrity: sha512-YJs6Pz17RMNv8HoyKREtCY38E3BV1nPkWVmIb+XN1uHC1Vqt3KZCH/uJH9ZKRoiKb/icZ6tvehyee6RZNbFfRA==} engines: {node: '>=6.0.0'} hasBin: true @@ -2128,8 +2173,8 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} - browserslist@4.29.3: - resolution: {integrity: sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==} + browserslist@4.29.4: + resolution: {integrity: sha512-2TcbbiwXEq+N0kD36tykpCfyyQigUXmuwNQbnPp4Xk4PX9JOqVIKjJlIDjpH7uY6tmRGoAd+apeT1p60T8wsdA==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true @@ -2164,8 +2209,8 @@ packages: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} - caniuse-lite@1.0.30001816: - resolution: {integrity: sha512-+8Yx7BXCoqk6IF8yTicjfUR6D/ldJzdlsodlEOiOSPmhK844WIgk67/zIQaGAOxNkZyyvBlrRFnLvqKIoqbAFw==} + caniuse-lite@1.0.30001819: + resolution: {integrity: sha512-LFUqIIAwpzsIuevnKnsR9qnStBcgzPShTX61lBwN9uFkkf8o8zLiebEjbW8AYtZiF+1YKDWfdt/pWDtMuG8Xwg==} ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} @@ -2556,8 +2601,8 @@ packages: engines: {node: '>=0.12.18'} hasBin: true - electron-to-chromium@1.5.457: - resolution: {integrity: sha512-RNKsgErRmkzRgC8nOV1wzFhSbfGlYJ6k4LT/aE7oFrDYaQgHhTh5oTp0ZgSbRRybKR8HlZIdCWc38Y+CDTk1Jw==} + electron-to-chromium@1.5.463: + resolution: {integrity: sha512-nVWNU6ltFjopvOdD44J4zoBkgO0M+WZiFKKFV7EjebOH9z0KNphk6bCEjplXtJofL21ARIuuwWOCsFkBVklm6w==} emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -3140,6 +3185,10 @@ packages: resolution: {integrity: sha512-/8UvqAPU9DGTI9k4mxtf49U37Isfwr8Uts96+SBHIkFxPJnHS0Ew4f00sM4Scd8V8EjM0jUNtVDdv1kPdt35lg==} engines: {node: '>= 4'} + ignore@7.0.13: + resolution: {integrity: sha512-2E8Q6rh+1RRSq/YdaGsNfXsEZy9FVqv6BSSrkmZJP7BnaoPnRfKL+YaofPvP+5rzdk144qSm6i4+hvPgUcbV4Q==} + engines: {node: '>= 4'} + import-fresh@3.3.1: resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} engines: {node: '>=6'} @@ -3876,8 +3925,8 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - napi-postinstall@0.3.4: - resolution: {integrity: sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==} + napi-postinstall@0.3.7: + resolution: {integrity: sha512-jyU4cU4kVAmy/3qjP+DcoQTNXfINHc+dFw54gGqWC8nu0mpV0kOnk7kff+J+Q18SbX0k3Np8Rm7yFjd3phatNQ==} engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} hasBin: true @@ -3959,8 +4008,8 @@ packages: resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} hasBin: true - node-releases@2.0.59: - resolution: {integrity: sha512-5qr2okC4ItAI0hG5SaV0HoYMpnM/Y6+Oqr7AmPYy/2uEoGvS+GbSKLeRxSS1uAdu59yz0ouzcuXievSgg///WA==} + node-releases@2.0.60: + resolution: {integrity: sha512-OmO8+GM1JUZqXET720VrJCwkjUCXmCMQm0Z3UDDRbfNLHS4NEAvY60j5jiFv0tkKw2PNNlqOLhahVmwJIOLDIQ==} engines: {node: '>=18'} npm-run-path@4.0.1: @@ -4435,8 +4484,8 @@ packages: robust-predicates@3.0.3: resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} - rolldown@1.2.14: - resolution: {integrity: sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw==} + rolldown@1.2.15: + resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true @@ -5101,8 +5150,8 @@ packages: zod@4.3.6: resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==} - zustand@5.0.15: - resolution: {integrity: sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==} + zustand@5.0.16: + resolution: {integrity: sha512-Uv7e327ihlCfayfja3hDc0M64Upev1LWBKpRobdK4NyovDDPeeX4imWXc/wzC1yc6fkYPoAY/ncKVPAs2jrtQw==} engines: {node: '>=12.20.0'} peerDependencies: '@types/react': '>=18.0.0' @@ -5171,7 +5220,7 @@ snapshots: dependencies: '@babel/compat-data': 7.29.7 '@babel/helper-validator-option': 7.29.7 - browserslist: 4.29.3 + browserslist: 4.29.4 lru-cache: 5.1.1 semver: 6.3.1 @@ -5390,28 +5439,28 @@ snapshots: fast-wrap-ansi: 0.2.2 sisteransi: 1.0.5 - '@codemirror/autocomplete@6.20.3': + '@codemirror/autocomplete@6.20.4': dependencies: '@codemirror/language': 6.13.1 '@codemirror/state': 6.7.6 '@codemirror/view': 6.43.15 - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@codemirror/commands@6.11.1': dependencies: '@codemirror/language': 6.13.1 '@codemirror/state': 6.7.6 '@codemirror/view': 6.43.15 - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@codemirror/lang-javascript@6.2.5': dependencies: - '@codemirror/autocomplete': 6.20.3 + '@codemirror/autocomplete': 6.20.4 '@codemirror/language': 6.13.1 '@codemirror/lint': 6.9.7 '@codemirror/state': 6.7.6 '@codemirror/view': 6.43.15 - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@lezer/javascript': 1.5.6 '@codemirror/lang-json@6.0.2': @@ -5424,7 +5473,7 @@ snapshots: '@codemirror/state': 6.7.6 '@codemirror/streamparser': 6.0.0 '@codemirror/view': 6.43.15 - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@lezer/highlight': 1.2.5 '@lezer/lr': 1.4.11 style-mod: 4.1.4 @@ -5586,7 +5635,7 @@ snapshots: '@floating-ui/react': 0.26.28(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@react-aria/focus': 3.22.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@react-aria/interactions': 3.28.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@tanstack/react-virtual': 3.14.20(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@tanstack/react-virtual': 3.14.21(react-dom@19.3.1(react@19.3.1))(react@19.3.1) react: 19.3.1 react-dom: 19.3.1(react@19.3.1) use-sync-external-store: 1.7.0(react@19.3.1) @@ -5765,27 +5814,27 @@ snapshots: '@keyv/serialize@1.1.1': {} - '@lezer/common@1.5.3': {} + '@lezer/common@1.5.4': {} '@lezer/highlight@1.2.5': dependencies: - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@lezer/javascript@1.5.6': dependencies: - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@lezer/highlight': 1.2.5 '@lezer/lr': 1.4.11 '@lezer/json@1.0.3': dependencies: - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@lezer/highlight': 1.2.5 '@lezer/lr': 1.4.11 '@lezer/lr@1.4.11': dependencies: - '@lezer/common': 1.5.3 + '@lezer/common': 1.5.4 '@manypkg/find-root@3.1.0': dependencies: @@ -5993,7 +6042,7 @@ snapshots: '@nx/nx-win32-x64-msvc@24.0.0': optional: true - '@oxc-project/types@0.154.0': {} + '@oxc-project/types@0.155.0': {} '@pagefind/darwin-arm64@1.5.2': optional: true @@ -6039,49 +6088,49 @@ snapshots: dependencies: react: 19.3.1 - '@rolldown/binding-android-arm-eabi@1.2.14': + '@rolldown/binding-android-arm-eabi@1.2.15': optional: true - '@rolldown/binding-android-arm64@1.2.14': + '@rolldown/binding-android-arm64@1.2.15': optional: true - '@rolldown/binding-darwin-arm64@1.2.14': + '@rolldown/binding-darwin-arm64@1.2.15': optional: true - '@rolldown/binding-darwin-x64@1.2.14': + '@rolldown/binding-darwin-x64@1.2.15': optional: true - '@rolldown/binding-freebsd-x64@1.2.14': + '@rolldown/binding-freebsd-x64@1.2.15': optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.2.14': + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': optional: true - '@rolldown/binding-linux-arm64-gnu@1.2.14': + '@rolldown/binding-linux-arm64-gnu@1.2.15': optional: true - '@rolldown/binding-linux-arm64-musl@1.2.14': + '@rolldown/binding-linux-arm64-musl@1.2.15': optional: true - '@rolldown/binding-linux-ppc64-gnu@1.2.14': + '@rolldown/binding-linux-ppc64-gnu@1.2.15': optional: true - '@rolldown/binding-linux-s390x-gnu@1.2.14': + '@rolldown/binding-linux-s390x-gnu@1.2.15': optional: true - '@rolldown/binding-linux-x64-gnu@1.2.14': + '@rolldown/binding-linux-x64-gnu@1.2.15': optional: true - '@rolldown/binding-linux-x64-musl@1.2.14': + '@rolldown/binding-linux-x64-musl@1.2.15': optional: true - '@rolldown/binding-openharmony-arm64@1.2.14': + '@rolldown/binding-openharmony-arm64@1.2.15': optional: true - '@rolldown/binding-win32-arm64-msvc@1.2.14': + '@rolldown/binding-win32-arm64-msvc@1.2.15': optional: true - '@rolldown/binding-win32-x64-msvc@1.2.14': + '@rolldown/binding-win32-x64-msvc@1.2.15': optional: true '@rolldown/pluginutils@1.0.1': {} @@ -6093,20 +6142,20 @@ snapshots: '@shikijs/core@3.23.0': dependencies: '@shikijs/types': 3.23.0 - '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/vscode-textmate': 10.1.0 '@types/hast': 3.0.5 hast-util-to-html: 9.0.5 '@shikijs/engine-javascript@3.23.0': dependencies: '@shikijs/types': 3.23.0 - '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/vscode-textmate': 10.1.0 oniguruma-to-es: 4.3.6 '@shikijs/engine-oniguruma@3.23.0': dependencies: '@shikijs/types': 3.23.0 - '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/vscode-textmate': 10.1.0 '@shikijs/langs@3.23.0': dependencies: @@ -6127,10 +6176,10 @@ snapshots: '@shikijs/types@3.23.0': dependencies: - '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/vscode-textmate': 10.1.0 '@types/hast': 3.0.5 - '@shikijs/vscode-textmate@10.0.2': {} + '@shikijs/vscode-textmate@10.1.0': {} '@sindresorhus/merge-streams@4.0.0': {} @@ -6207,13 +6256,13 @@ snapshots: postcss: 8.5.31 tailwindcss: 4.3.3 - '@tanstack/react-virtual@3.14.20(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + '@tanstack/react-virtual@3.14.21(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': dependencies: - '@tanstack/virtual-core': 3.19.5 + '@tanstack/virtual-core': 3.19.6 react: 19.3.1 react-dom: 19.3.1(react@19.3.1) - '@tanstack/virtual-core@3.19.5': {} + '@tanstack/virtual-core@3.19.6': {} '@theguild/remark-mermaid@0.3.0(react@19.3.1)': dependencies: @@ -6458,7 +6507,7 @@ snapshots: '@typescript-eslint/utils': 8.72.0(eslint@10.13.0(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3) '@typescript-eslint/visitor-keys': 8.72.0 eslint: 10.13.0(jiti@2.7.0)(supports-color@7.2.0) - ignore: 7.0.12 + ignore: 7.0.13 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@6.0.3) typescript: 6.0.3 @@ -6477,6 +6526,15 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/project-service@8.67.0(supports-color@7.2.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.67.0(typescript@6.0.3) + '@typescript-eslint/types': 8.67.0 + debug: 4.4.3(supports-color@7.2.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + '@typescript-eslint/project-service@8.72.0(supports-color@7.2.0)(typescript@6.0.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.72.0(typescript@6.0.3) @@ -6491,6 +6549,10 @@ snapshots: '@typescript-eslint/types': 8.72.0 '@typescript-eslint/visitor-keys': 8.72.0 + '@typescript-eslint/tsconfig-utils@8.67.0(typescript@6.0.3)': + dependencies: + typescript: 6.0.3 + '@typescript-eslint/tsconfig-utils@8.72.0(typescript@6.0.3)': dependencies: typescript: 6.0.3 @@ -6507,8 +6569,25 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/types@8.67.0': {} + '@typescript-eslint/types@8.72.0': {} + '@typescript-eslint/typescript-estree@8.67.0(supports-color@7.2.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/project-service': 8.67.0(supports-color@7.2.0)(typescript@6.0.3) + '@typescript-eslint/tsconfig-utils': 8.67.0(typescript@6.0.3) + '@typescript-eslint/types': 8.67.0 + '@typescript-eslint/visitor-keys': 8.67.0 + debug: 4.4.3(supports-color@7.2.0) + minimatch: 10.2.6 + semver: 7.8.5 + tinyglobby: 0.2.17 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + '@typescript-eslint/typescript-estree@8.72.0(supports-color@7.2.0)(typescript@6.0.3)': dependencies: '@typescript-eslint/project-service': 8.72.0(supports-color@7.2.0)(typescript@6.0.3) @@ -6535,6 +6614,11 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/visitor-keys@8.67.0': + dependencies: + '@typescript-eslint/types': 8.67.0 + eslint-visitor-keys: 5.0.1 + '@typescript-eslint/visitor-keys@8.72.0': dependencies: '@typescript-eslint/types': 8.72.0 @@ -6547,9 +6631,9 @@ snapshots: transitivePeerDependencies: - supports-color - '@uiw/codemirror-extensions-basic-setup@4.25.12(@codemirror/autocomplete@6.20.3)(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.43.15)': + '@uiw/codemirror-extensions-basic-setup@4.25.12(@codemirror/autocomplete@6.20.4)(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.43.15)': dependencies: - '@codemirror/autocomplete': 6.20.3 + '@codemirror/autocomplete': 6.20.4 '@codemirror/commands': 6.11.1 '@codemirror/language': 6.13.1 '@codemirror/lint': 6.9.7 @@ -6557,14 +6641,14 @@ snapshots: '@codemirror/state': 6.7.6 '@codemirror/view': 6.43.15 - '@uiw/react-codemirror@4.25.12(@babel/runtime@7.29.10)(@codemirror/autocomplete@6.20.3)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.15)(codemirror@6.0.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + '@uiw/react-codemirror@4.25.12(@babel/runtime@7.29.10)(@codemirror/autocomplete@6.20.4)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.15)(codemirror@6.0.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': dependencies: '@babel/runtime': 7.29.10 '@codemirror/commands': 6.11.1 '@codemirror/state': 6.7.6 '@codemirror/theme-one-dark': 6.1.3 '@codemirror/view': 6.43.15 - '@uiw/codemirror-extensions-basic-setup': 4.25.12(@codemirror/autocomplete@6.20.3)(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.43.15) + '@uiw/codemirror-extensions-basic-setup': 4.25.12(@codemirror/autocomplete@6.20.4)(@codemirror/commands@6.11.1)(@codemirror/language@6.13.1)(@codemirror/lint@6.9.7)(@codemirror/search@6.7.2)(@codemirror/state@6.7.6)(@codemirror/view@6.43.15) codemirror: 6.0.2 react: 19.3.1 react-dom: 19.3.1(react@19.3.1) @@ -6820,7 +6904,7 @@ snapshots: base64-js@1.5.1: {} - baseline-browser-mapping@2.11.29: {} + baseline-browser-mapping@2.11.30: {} benchmark@2.1.4: dependencies: @@ -6851,13 +6935,13 @@ snapshots: dependencies: fill-range: 7.1.1 - browserslist@4.29.3: + browserslist@4.29.4: dependencies: - baseline-browser-mapping: 2.11.29 - caniuse-lite: 1.0.30001816 - electron-to-chromium: 1.5.457 - node-releases: 2.0.59 - update-browserslist-db: 1.3.4(browserslist@4.29.3) + baseline-browser-mapping: 2.11.30 + caniuse-lite: 1.0.30001819 + electron-to-chromium: 1.5.463 + node-releases: 2.0.60 + update-browserslist-db: 1.3.4(browserslist@4.29.4) buffer@5.7.1: dependencies: @@ -6908,7 +6992,7 @@ snapshots: callsites@3.1.0: {} - caniuse-lite@1.0.30001816: {} + caniuse-lite@1.0.30001819: {} ccount@2.0.1: {} @@ -6967,7 +7051,7 @@ snapshots: codemirror@6.0.2: dependencies: - '@codemirror/autocomplete': 6.20.3 + '@codemirror/autocomplete': 6.20.4 '@codemirror/commands': 6.11.1 '@codemirror/language': 6.13.1 '@codemirror/lint': 6.9.7 @@ -7307,7 +7391,7 @@ snapshots: ejs@5.0.1: {} - electron-to-chromium@1.5.457: {} + electron-to-chromium@1.5.463: {} emoji-regex@8.0.0: {} @@ -8162,6 +8246,8 @@ snapshots: ignore@7.0.12: {} + ignore@7.0.13: {} + import-fresh@3.3.1: dependencies: parent-module: 1.0.1 @@ -9136,7 +9222,7 @@ snapshots: nanoid@3.3.20: {} - napi-postinstall@0.3.4: {} + napi-postinstall@0.3.7: {} natural-compare@1.4.0: {} @@ -9163,8 +9249,8 @@ snapshots: dependencies: '@next/env': 16.4.2 '@swc/helpers': 0.5.23 - baseline-browser-mapping: 2.11.29 - caniuse-lite: 1.0.30001816 + baseline-browser-mapping: 2.11.30 + caniuse-lite: 1.0.30001819 postcss: 8.5.23 react: 19.3.1 react-dom: 19.3.1(react@19.3.1) @@ -9196,7 +9282,7 @@ snapshots: react-dom: 19.3.1(react@19.3.1) scroll-into-view-if-needed: 3.1.0 zod: 4.3.6 - zustand: 5.0.15(@types/react@19.3.0)(react@19.3.1)(use-sync-external-store@1.7.0(react@19.3.1)) + zustand: 5.0.16(@types/react@19.3.0)(react@19.3.1)(use-sync-external-store@1.7.0(react@19.3.1)) transitivePeerDependencies: - '@types/react' - immer @@ -9269,7 +9355,7 @@ snapshots: node-gyp-build@4.8.4: {} - node-releases@2.0.59: {} + node-releases@2.0.60: {} npm-run-path@4.0.1: dependencies: @@ -9571,7 +9657,7 @@ snapshots: postcss-lightningcss@1.1.1(postcss@8.5.31): dependencies: - browserslist: 4.29.3 + browserslist: 4.29.4 lightningcss: 1.33.0 postcss: 8.5.31 @@ -9938,26 +10024,26 @@ snapshots: robust-predicates@3.0.3: {} - rolldown@1.2.14: + rolldown@1.2.15: dependencies: - '@oxc-project/types': 0.154.0 + '@oxc-project/types': 0.155.0 '@rolldown/pluginutils': 1.0.1 optionalDependencies: - '@rolldown/binding-android-arm-eabi': 1.2.14 - '@rolldown/binding-android-arm64': 1.2.14 - '@rolldown/binding-darwin-arm64': 1.2.14 - '@rolldown/binding-darwin-x64': 1.2.14 - '@rolldown/binding-freebsd-x64': 1.2.14 - '@rolldown/binding-linux-arm-gnueabihf': 1.2.14 - '@rolldown/binding-linux-arm64-gnu': 1.2.14 - '@rolldown/binding-linux-arm64-musl': 1.2.14 - '@rolldown/binding-linux-ppc64-gnu': 1.2.14 - '@rolldown/binding-linux-s390x-gnu': 1.2.14 - '@rolldown/binding-linux-x64-gnu': 1.2.14 - '@rolldown/binding-linux-x64-musl': 1.2.14 - '@rolldown/binding-openharmony-arm64': 1.2.14 - '@rolldown/binding-win32-arm64-msvc': 1.2.14 - '@rolldown/binding-win32-x64-msvc': 1.2.14 + '@rolldown/binding-android-arm-eabi': 1.2.15 + '@rolldown/binding-android-arm64': 1.2.15 + '@rolldown/binding-darwin-arm64': 1.2.15 + '@rolldown/binding-darwin-x64': 1.2.15 + '@rolldown/binding-freebsd-x64': 1.2.15 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.15 + '@rolldown/binding-linux-arm64-gnu': 1.2.15 + '@rolldown/binding-linux-arm64-musl': 1.2.15 + '@rolldown/binding-linux-ppc64-gnu': 1.2.15 + '@rolldown/binding-linux-s390x-gnu': 1.2.15 + '@rolldown/binding-linux-x64-gnu': 1.2.15 + '@rolldown/binding-linux-x64-musl': 1.2.15 + '@rolldown/binding-openharmony-arm64': 1.2.15 + '@rolldown/binding-win32-arm64-msvc': 1.2.15 + '@rolldown/binding-win32-x64-msvc': 1.2.15 roughjs@4.6.6: dependencies: @@ -10079,7 +10165,7 @@ snapshots: '@shikijs/langs': 3.23.0 '@shikijs/themes': 3.23.0 '@shikijs/types': 3.23.0 - '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/vscode-textmate': 10.1.0 '@types/hast': 3.0.5 side-channel-list@1.0.1: @@ -10485,7 +10571,7 @@ snapshots: unrs-resolver@1.12.2: dependencies: - napi-postinstall: 0.3.4 + napi-postinstall: 0.3.7 optionalDependencies: '@unrs/resolver-binding-android-arm-eabi': 1.12.2 '@unrs/resolver-binding-android-arm64': 1.12.2 @@ -10510,9 +10596,9 @@ snapshots: '@unrs/resolver-binding-win32-ia32-msvc': 1.12.2 '@unrs/resolver-binding-win32-x64-msvc': 1.12.2 - update-browserslist-db@1.3.4(browserslist@4.29.3): + update-browserslist-db@1.3.4(browserslist@4.29.4): dependencies: - browserslist: 4.29.3 + browserslist: 4.29.4 escalade: 3.2.0 picocolors: 1.1.1 @@ -10554,7 +10640,7 @@ snapshots: lightningcss: 1.33.0 picomatch: 4.0.7 postcss: 8.5.31 - rolldown: 1.2.14 + rolldown: 1.2.15 tinyglobby: 0.2.17 optionalDependencies: '@types/node': 22.20.5 @@ -10699,7 +10785,7 @@ snapshots: zod@4.3.6: {} - zustand@5.0.15(@types/react@19.3.0)(react@19.3.1)(use-sync-external-store@1.7.0(react@19.3.1)): + zustand@5.0.16(@types/react@19.3.0)(react@19.3.1)(use-sync-external-store@1.7.0(react@19.3.1)): optionalDependencies: '@types/react': 19.3.0 react: 19.3.1 From 0c5e399df6613a581e4309d7d7b52dba362c6a31 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Mon, 21 Sep 2026 16:47:42 +0200 Subject: [PATCH 06/22] add hermes --- PLAN.md | 26 +- packages/core/src/extract.ts | 1 + packages/core/src/handlers/methodHandler.ts | 1 + .../src/resolver/findExportedDefinitions.ts | 12 +- packages/core/src/utils/getDefaultValue.ts | 24 +- .../src/utils/resolveComponentDefinition.ts | 1 + packages/core/src/utils/unwrapExpression.ts | 1 + packages/hermes/package.json | 36 ++ packages/hermes/src/__tests__/parser-test.ts | 29 ++ .../hermes/src/handlers/flowPropsHandler.ts | 97 +++++ packages/hermes/src/hermes-parser.d.ts | 11 + packages/hermes/src/index.ts | 59 +++ packages/hermes/src/normalize.ts | 43 ++ packages/hermes/src/parser.ts | 26 ++ packages/hermes/src/utils/ast.ts | 108 +++++ packages/hermes/src/utils/getFlowType.ts | 387 ++++++++++++++++++ packages/hermes/src/utils/getPropsMembers.ts | 184 +++++++++ .../integration/babel-differential-test.ts | 27 ++ .../tests/integration/integration-test.ts | 39 ++ packages/hermes/tsconfig.json | 8 + packages/hermes/vitest.config.ts | 8 + pnpm-lock.yaml | 16 + 22 files changed, 1130 insertions(+), 14 deletions(-) create mode 100644 packages/hermes/package.json create mode 100644 packages/hermes/src/__tests__/parser-test.ts create mode 100644 packages/hermes/src/handlers/flowPropsHandler.ts create mode 100644 packages/hermes/src/hermes-parser.d.ts create mode 100644 packages/hermes/src/index.ts create mode 100644 packages/hermes/src/normalize.ts create mode 100644 packages/hermes/src/parser.ts create mode 100644 packages/hermes/src/utils/ast.ts create mode 100644 packages/hermes/src/utils/getFlowType.ts create mode 100644 packages/hermes/src/utils/getPropsMembers.ts create mode 100644 packages/hermes/tests/integration/babel-differential-test.ts create mode 100644 packages/hermes/tests/integration/integration-test.ts create mode 100644 packages/hermes/tsconfig.json create mode 100644 packages/hermes/vitest.config.ts diff --git a/PLAN.md b/PLAN.md index c26dadc1014..c790aeb4ca7 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2,9 +2,9 @@ ## Status -- Current milestone: 4 — Hermes and Flow -- Overall status: Milestone 3.1 complete; Milestone 4 not started -- Last updated: 2026-08-16 +- Current milestone: 5 — Mixed-parser projects +- Overall status: Milestone 4 complete +- Last updated: 2026-09-21 ## Decisions @@ -106,10 +106,10 @@ cannot silently regress. ## Milestone 4 — Hermes and Flow -- [ ] Add `@react-docgen/hermes` and normalize Hermes ESTree and Flow nodes. -- [ ] Port Flow extraction and component patterns. -- [ ] Run common fixtures through TypeScript, Hermes, and Babel adapters. -- [ ] Report unsupported syntax as explicit parser capability errors. +- [x] Add `@react-docgen/hermes` and normalize Hermes ESTree and Flow nodes. +- [x] Port Flow extraction and component patterns. +- [x] Run common fixtures through TypeScript, Hermes, and Babel adapters. +- [x] Report unsupported syntax as explicit parser capability errors. Exit criteria: common JS/JSX output agrees across adapters and Flow output matches the legacy implementation. @@ -190,6 +190,18 @@ import { parse } from '@react-docgen/typescript'; Record every material plan change here before or with implementation. +### 2026-09-21 — Completed Hermes and Flow milestone + +- Added `@react-docgen/hermes` as a thin Hermes parser adapter over shared core + extraction, with normalization for Hermes ESTree and Flow nodes. +- Ported Flow props and type extraction, including aliases, interfaces, + utilities, imports, generics, and recursive type protection. +- Added file-based Flow/JavaScript corpus coverage and Babel differential tests; + unsupported TypeScript-family files now produce an explicit parser capability + error. +- Reason: Hermes now matches legacy Flow output while common JavaScript output + remains consistent across parser adapters. + ### 2026-08-16 — Added shared React extraction milestone - Inserted Milestone 3.1 before Hermes work and temporarily made it current. diff --git a/packages/core/src/extract.ts b/packages/core/src/extract.ts index 5dde3b2a434..6cc304e47a5 100644 --- a/packages/core/src/extract.ts +++ b/packages/core/src/extract.ts @@ -14,6 +14,7 @@ export interface DefaultValueDescriptor { export interface PropDescriptor { defaultValue?: DefaultValueDescriptor; description?: string; + flowType?: TypeDescriptor; required: boolean; tsType?: TypeDescriptor; type?: TypeDescriptor; diff --git a/packages/core/src/handlers/methodHandler.ts b/packages/core/src/handlers/methodHandler.ts index 6991fe9b15d..56ad1498852 100644 --- a/packages/core/src/handlers/methodHandler.ts +++ b/packages/core/src/handlers/methodHandler.ts @@ -86,6 +86,7 @@ export default function createMethodHandler(getType?: TypeResolver): Handler { !fn || name === 'constructor' || name === 'render' || + name === 'UNSAFE_componentWillReceiveProps' || name === 'componentDidMount' || name === 'componentWillUnmount' ) diff --git a/packages/core/src/resolver/findExportedDefinitions.ts b/packages/core/src/resolver/findExportedDefinitions.ts index 4538ac2974a..e186318d780 100644 --- a/packages/core/src/resolver/findExportedDefinitions.ts +++ b/packages/core/src/resolver/findExportedDefinitions.ts @@ -100,7 +100,8 @@ const findExportedDefinitions: Resolver = (file) => { assignment.operator !== '=' || !isMemberExpression(assignment.left) || assignment.left.computed || - !isIdentifier(assignment.right) + (!isIdentifier(assignment.right) && + assignment.right.type !== 'CallExpression') ) { continue; } @@ -116,7 +117,14 @@ const findExportedDefinitions: Resolver = (file) => { continue; } - const definition = findTopLevelDefinition(file, assignment.right.name); + const expression = path.get('expression'); + const right = + expression && !Array.isArray(expression) ? expression.get('right') : null; + const definition = isIdentifier(assignment.right) + ? findTopLevelDefinition(file, assignment.right.name) + : right && !Array.isArray(right) + ? resolveComponentDefinition(file, right) + : null; if (definition) { definitions.add(definition); diff --git a/packages/core/src/utils/getDefaultValue.ts b/packages/core/src/utils/getDefaultValue.ts index a8bff73f8a2..faadb1938a1 100644 --- a/packages/core/src/utils/getDefaultValue.ts +++ b/packages/core/src/utils/getDefaultValue.ts @@ -5,21 +5,25 @@ import type { } from '../internal.js'; import { isIdentifier, isMemberExpression } from '../internal.js'; import resolveValue, { getValueFile } from './resolveValue.js'; +import unwrapExpression from './unwrapExpression.js'; export default function getDefaultValue( file: FileState, node: AstNode, ): DefaultValueDescriptor { + const wasTypeCast = node.type === 'TypeCastExpression'; + + node = unwrapExpression(node); if (isIdentifier(node) || isMemberExpression(node)) { - const original = node; const resolved = resolveValue(file, node); const resolvedFile = getValueFile(file, resolved); - if (resolvedFile.source.filename !== file.source.filename) { + if ( + resolved !== node && + (wasTypeCast || resolvedFile.source.filename !== file.source.filename) + ) { node = resolved; file = resolvedFile; - } else { - node = original; } } file = getValueFile(file, node); @@ -33,9 +37,19 @@ export default function getDefaultValue( return { computed: true, value: '' }; } + let value = file.source.code.slice(range[0], range[1]); + + if (wasTypeCast && node.type === 'ObjectExpression') { + const closingIndent = value.match(/\n([ \t]*)}$/)?.[1]; + + if (closingIndent) { + value = value.replaceAll(`\n${closingIndent}`, '\n'); + } + } + return { computed: node.type === 'CallExpression' || node.type === 'MemberExpression', - value: file.source.code.slice(range[0], range[1]), + value, }; } diff --git a/packages/core/src/utils/resolveComponentDefinition.ts b/packages/core/src/utils/resolveComponentDefinition.ts index ad7bec567f8..3c9c91e826c 100644 --- a/packages/core/src/utils/resolveComponentDefinition.ts +++ b/packages/core/src/utils/resolveComponentDefinition.ts @@ -21,6 +21,7 @@ export default function resolveComponentDefinition( ): AstPath | null { if ( path.node.type === 'ChainExpression' || + path.node.type === 'TypeCastExpression' || path.node.type === 'TSAsExpression' || path.node.type === 'TSNonNullExpression' || path.node.type === 'TSSatisfiesExpression' || diff --git a/packages/core/src/utils/unwrapExpression.ts b/packages/core/src/utils/unwrapExpression.ts index 326b335b94c..b8d2b13193a 100644 --- a/packages/core/src/utils/unwrapExpression.ts +++ b/packages/core/src/utils/unwrapExpression.ts @@ -2,6 +2,7 @@ import type { AstNode } from '../internal.js'; const wrappers = new Set([ 'ChainExpression', + 'TypeCastExpression', 'TSAsExpression', 'TSNonNullExpression', 'TSSatisfiesExpression', diff --git a/packages/hermes/package.json b/packages/hermes/package.json new file mode 100644 index 00000000000..fd79b9d8b56 --- /dev/null +++ b/packages/hermes/package.json @@ -0,0 +1,36 @@ +{ + "name": "@react-docgen/hermes", + "version": "0.0.0", + "description": "Hermes and Flow parser adapter for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/hermes" + }, + "type": "module", + "files": [ + "dist" + ], + "engines": { + "node": "^22.13.0 || >=24" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + }, + "dependencies": { + "@react-docgen/core": "workspace:*", + "hermes-parser": "0.25.1" + }, + "devDependencies": { + "@react-docgen/babel": "workspace:*", + "@react-docgen-internal/integration-tests": "workspace:*" + }, + "license": "MIT" +} diff --git a/packages/hermes/src/__tests__/parser-test.ts b/packages/hermes/src/__tests__/parser-test.ts new file mode 100644 index 00000000000..012a9b3ed2a --- /dev/null +++ b/packages/hermes/src/__tests__/parser-test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from 'vitest'; +import parser from '../parser.js'; + +describe('parser', () => { + test('parses JavaScript and Flow syntax', () => { + const program = parser.parse({ + code: 'type Props = { label: string }; const View = (props: Props) =>
;', + filename: 'component.js', + }); + + expect(program.type).toBe('Program'); + expect(program.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: 'TypeAlias' }), + expect.objectContaining({ type: 'VariableDeclaration' }), + ]), + ); + }); + + test('reports unsupported TypeScript files', () => { + expect(() => + parser.parse({ code: 'const value: string = "x";', filename: 'file.ts' }), + ).toThrow( + expect.objectContaining({ + code: 'ERR_REACTDOCGEN_PARSER_CAPABILITY', + }), + ); + }); +}); diff --git a/packages/hermes/src/handlers/flowPropsHandler.ts b/packages/hermes/src/handlers/flowPropsHandler.ts new file mode 100644 index 00000000000..b84998021d6 --- /dev/null +++ b/packages/hermes/src/handlers/flowPropsHandler.ts @@ -0,0 +1,97 @@ +import { + getDescription, + getParameterDefaults, + isArrowFunctionExpression, + isClassDeclaration, + isClassExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isObjectPattern, + resolveComponentDefinition, + type AstNode, + type Handler, +} from '@react-docgen/core'; +import getFlowType from '../utils/getFlowType.js'; +import getPropsMembers from '../utils/getPropsMembers.js'; +import { child, nodes } from '../utils/ast.js'; + +function annotationFor(node: AstNode): AstNode | null { + const parameter = + isFunctionDeclaration(node) || + isFunctionExpression(node) || + isArrowFunctionExpression(node) + ? node.params[0] + : null; + + if (parameter) { + return child( + child(parameter, 'typeAnnotation') ?? parameter, + 'typeAnnotation', + ); + } + + if (isClassDeclaration(node) || isClassExpression(node)) { + const superTypes = child(node, 'superTypeParameters'); + const params = superTypes ? nodes(superTypes, 'params') : []; + + return params[params.length === 3 ? 1 : 0] ?? null; + } + + return null; +} + +const flowPropsHandler: Handler = (documentation, path, file) => { + const component = resolveComponentDefinition(file, path) ?? path; + const parameter = + isFunctionDeclaration(component.node) || + isFunctionExpression(component.node) || + isArrowFunctionExpression(component.node) + ? component.node.params[0] + : null; + const annotation = annotationFor(component.node); + const { composes, members, parameters } = getPropsMembers(file, annotation); + const defaults = getParameterDefaults( + parameter && isObjectPattern(parameter) ? parameter : null, + ); + + if (composes.length > 0) documentation.composes = [...new Set(composes)]; + if (members.length === 0) return; + + documentation.props ??= {}; + + for (const member of members) { + if (member.type !== 'ObjectTypeProperty') continue; + const key = child(member, 'key'); + const value = child(member, 'value'); + + if (!key || !isIdentifier(key) || !value) continue; + const flowType = getFlowType(file, value, parameters); + + if (!flowType) continue; + const defaultNode = defaults.get(key.name); + + documentation.props[key.name] = { + ...documentation.props[key.name], + description: getDescription(file, member), + flowType, + required: member.optional !== true, + ...(defaultNode && isLiteral(defaultNode) + ? { + defaultValue: { + computed: false, + value: + defaultNode.raw ?? + file.source.code.slice( + defaultNode.range[0], + defaultNode.range[1], + ), + }, + } + : {}), + }; + } +}; + +export default flowPropsHandler; diff --git a/packages/hermes/src/hermes-parser.d.ts b/packages/hermes/src/hermes-parser.d.ts new file mode 100644 index 00000000000..f7847f6cea2 --- /dev/null +++ b/packages/hermes/src/hermes-parser.d.ts @@ -0,0 +1,11 @@ +declare module 'hermes-parser' { + export const FlowVisitorKeys: Record; + export function parse( + code: string, + options: { + flow: 'all' | 'detect'; + sourceType: 'module' | 'script' | 'unambiguous'; + tokens?: boolean; + }, + ): unknown; +} diff --git a/packages/hermes/src/index.ts b/packages/hermes/src/index.ts new file mode 100644 index 00000000000..d5fe8845f4e --- /dev/null +++ b/packages/hermes/src/index.ts @@ -0,0 +1,59 @@ +import { + componentHandler, + contextHandler, + createDocgen, + createMethodHandler, + defaultPropsHandler, + propTypesHandler, + resolveComponentDefinitions, + type ComponentDocumentation, + type Importer, + type AstNode, + type FileState, + isIdentifier, +} from '@react-docgen/core'; +import flowPropsHandler from './handlers/flowPropsHandler.js'; +import parser from './parser.js'; +import getFlowType from './utils/getFlowType.js'; +import { child, typeName } from './utils/ast.js'; + +export { default as parser, visitorKeys } from './parser.js'; + +export interface ParseOptions { + filename?: string; + importer?: Importer; +} + +const docgen = createDocgen({ + handlers: [ + componentHandler, + propTypesHandler, + flowPropsHandler, + defaultPropsHandler, + contextHandler, + createMethodHandler((file: FileState, annotation: AstNode) => { + const type = getFlowType(file, annotation); + const unwrapped = + annotation.type === 'TypeAnnotation' + ? child(annotation, 'typeAnnotation') + : annotation; + const id = + unwrapped?.type === 'GenericTypeAnnotation' + ? child(unwrapped, 'id') + : null; + + return type?.name === 'signature' && id && isIdentifier(id) + ? { ...type, alias: typeName(id) } + : type; + }), + ], + parser, + resolver: resolveComponentDefinitions, +}); + +export function parse( + code: string, + { filename = 'component.js', importer }: ParseOptions = {}, +): ComponentDocumentation[] { + return docgen(code, { filename, importer }); +} diff --git a/packages/hermes/src/normalize.ts b/packages/hermes/src/normalize.ts new file mode 100644 index 00000000000..7c8eb4e72e8 --- /dev/null +++ b/packages/hermes/src/normalize.ts @@ -0,0 +1,43 @@ +import { isAstNode, type AstNode } from '@react-docgen/core'; + +const typeNames: Record = { + BigIntLiteral: 'Literal', + BooleanLiteral: 'Literal', + ClassProperty: 'PropertyDefinition', + NullLiteral: 'Literal', + NumericLiteral: 'Literal', + RegExpLiteral: 'Literal', + StringLiteral: 'Literal', +}; + +function normalizeValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(normalizeValue); + if (!value || typeof value !== 'object') return value; + + const input = value as Record; + const output: Record = {}; + + for (const [key, child] of Object.entries(input)) { + output[key] = normalizeValue(child); + } + + const originalType = typeof input.type === 'string' ? input.type : ''; + + output.type = typeNames[originalType] ?? originalType; + + if (output.type === 'Literal' && output.raw === undefined) { + output.raw = originalType === 'NullLiteral' ? 'null' : input.value; + } + + return output; +} + +export default function normalize(node: unknown): AstNode { + const normalized = normalizeValue(node); + + if (!isAstNode(normalized)) { + throw new TypeError('Hermes did not return an AST node.'); + } + + return normalized; +} diff --git a/packages/hermes/src/parser.ts b/packages/hermes/src/parser.ts new file mode 100644 index 00000000000..191e023b16c --- /dev/null +++ b/packages/hermes/src/parser.ts @@ -0,0 +1,26 @@ +import { FlowVisitorKeys, parse } from 'hermes-parser'; +import type { Parser, VisitorKeys } from '@react-docgen/core'; +import normalize from './normalize.js'; + +export const visitorKeys: VisitorKeys = FlowVisitorKeys; + +const parser: Parser = { + parse(source) { + if (/\.(?:cts|mts|ts|tsx)$/.test(source.filename)) { + throw Object.assign( + new Error('The Hermes adapter does not support TypeScript syntax.'), + { code: 'ERR_REACTDOCGEN_PARSER_CAPABILITY' }, + ); + } + + return normalize( + parse(source.code, { + flow: 'all', + sourceType: 'unambiguous', + }), + ); + }, + visitorKeys, +}; + +export default parser; diff --git a/packages/hermes/src/utils/ast.ts b/packages/hermes/src/utils/ast.ts new file mode 100644 index 00000000000..11fe1c6de48 --- /dev/null +++ b/packages/hermes/src/utils/ast.ts @@ -0,0 +1,108 @@ +import { + isExportNamedDeclaration, + isIdentifier, + isLiteral, + type AstNode, + type FileState, + getBody, +} from '@react-docgen/core'; + +export function child(node: AstNode, key: string): AstNode | null { + const value = node[key]; + + return value && typeof value === 'object' && 'type' in value + ? (value as AstNode) + : null; +} + +export function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function source(node: AstNode): string | null { + const value = child(node, 'source'); + + return value && isLiteral(value) && typeof value.value === 'string' + ? value.value + : null; +} + +export function resolveType( + file: FileState, + name: string, + seen = new Set(), +): { declaration: AstNode; file: FileState } | null { + const key = `${file.source.filename}:${name}`; + + if (seen.has(key)) return null; + seen.add(key); + + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + const id = child(declaration, 'id'); + + if ( + (declaration.type === 'TypeAlias' || + declaration.type === 'InterfaceDeclaration') && + id && + isIdentifier(id, { name }) + ) { + return { declaration, file }; + } + + if (path.node.type === 'ImportDeclaration') { + for (const specifier of nodes(path.node, 'specifiers')) { + const local = child(specifier, 'local'); + + if (!local || !isIdentifier(local, { name })) continue; + const imported = child(specifier, 'imported'); + const importedName = + specifier.type === 'ImportDefaultSpecifier' + ? 'default' + : imported && isIdentifier(imported) + ? imported.name + : name; + const specifierSource = source(path.node); + + if (!specifierSource) return null; + + try { + return resolveType(file.import(specifierSource), importedName, seen); + } catch { + return null; + } + } + } + } + + return null; +} + +export function raw(file: FileState, node: AstNode): string { + return Array.isArray(node.range) + ? file.source.code.slice(node.range[0], node.range[1]) + : ''; +} + +export function typeName(node: AstNode): string { + if (isIdentifier(node)) return node.name; + if (node.type === 'QualifiedTypeIdentifier') { + const qualification = child(node, 'qualification'); + const id = child(node, 'id'); + + return `${qualification ? typeName(qualification) : ''}${ + id && isIdentifier(id) ? id.name : '' + }`; + } + + return ''; +} diff --git a/packages/hermes/src/utils/getFlowType.ts b/packages/hermes/src/utils/getFlowType.ts new file mode 100644 index 00000000000..ade13c1f7d1 --- /dev/null +++ b/packages/hermes/src/utils/getFlowType.ts @@ -0,0 +1,387 @@ +import { + getDescription, + isIdentifier, + type AstNode, + type FileState, + type TypeDescriptor, + resolveValue, +} from '@react-docgen/core'; +import { child, nodes, raw, resolveType, typeName } from './ast.js'; + +type Parameters = Map; + +const primitiveTypes: Record = { + AnyTypeAnnotation: 'any', + BooleanTypeAnnotation: 'boolean', + EmptyTypeAnnotation: 'empty', + MixedTypeAnnotation: 'mixed', + NullLiteralTypeAnnotation: 'null', + NumberTypeAnnotation: 'number', + StringTypeAnnotation: 'string', + VoidTypeAnnotation: 'void', +}; + +function literal(file: FileState, node: AstNode): TypeDescriptor { + return { + name: 'literal', + value: raw(file, node), + }; +} + +function withRequired(type: TypeDescriptor, node: AstNode): TypeDescriptor { + return { ...type, required: node.optional !== true }; +} + +function parametersFor( + declaration: AstNode, + reference: AstNode, + inherited: Parameters, +): Parameters { + const result = new Map(inherited); + const declared = child(declaration, 'typeParameters'); + const provided = child(reference, 'typeParameters'); + const values = provided ? nodes(provided, 'params') : []; + + for (const [index, parameter] of (declared + ? nodes(declared, 'params') + : [] + ).entries()) { + const value = values[index]; + + const name = isIdentifier(parameter) + ? parameter.name + : typeof parameter.name === 'string' + ? parameter.name + : null; + + if (name && value) result.set(name, value); + } + + return result; +} + +function objectType( + file: FileState, + node: AstNode, + parameters: Parameters, + seen: WeakSet, +): TypeDescriptor { + const properties: Array> = []; + + for (const indexer of nodes(node, 'indexers')) { + const key = child(indexer, 'key'); + const value = child(indexer, 'value'); + + if (key && value) { + properties.push({ + key: resolve(file, key, parameters, seen), + value: withRequired(resolve(file, value, parameters, seen), indexer), + ...(getDescription(file, indexer) + ? { description: getDescription(file, indexer) } + : {}), + }); + } + } + + for (const property of nodes(node, 'properties')) { + if (property.type === 'ObjectTypeSpreadProperty') { + const argument = child(property, 'argument'); + const spread = argument + ? resolve(file, argument, parameters, seen) + : null; + + if ( + spread && + spread.signature && + typeof spread.signature === 'object' && + 'properties' in spread.signature && + Array.isArray(spread.signature.properties) + ) { + properties.push(...spread.signature.properties); + } + continue; + } + if (property.type !== 'ObjectTypeProperty') continue; + const key = child(property, 'key'); + const value = child(property, 'value'); + + if (!key || !value) continue; + properties.push({ + key: isIdentifier(key) ? key.name : String(key.value ?? ''), + value: withRequired(resolve(file, value, parameters, seen), property), + ...(getDescription(file, property) + ? { description: getDescription(file, property) } + : {}), + }); + } + + const descriptor: TypeDescriptor = { + name: 'signature', + type: 'object', + raw: raw(file, node), + signature: { properties }, + }; + const callProperty = nodes(node, 'callProperties')[0]; + const callValue = callProperty ? child(callProperty, 'value') : null; + + if (callValue) { + (descriptor.signature as Record)['constructor'] = resolve( + file, + callValue, + parameters, + seen, + ); + } + + return descriptor; +} + +function genericType( + file: FileState, + node: AstNode, + parameters: Parameters, + seen: WeakSet, +): TypeDescriptor { + const id = child(node, 'id'); + const name = id ? typeName(id) : 'unknown'; + const parameter = parameters.get(name); + + if (parameter) { + const parameterId = child(parameter, 'id'); + + return parameter.type === 'GenericTypeAnnotation' && + parameterId && + typeName(parameterId) === name + ? { name } + : resolve(file, parameter, parameters, seen); + } + + const resolved = name ? resolveType(file, name) : null; + + if (resolved?.declaration.type === 'TypeAlias') { + if (seen.has(resolved.declaration)) { + const [first] = nodes(child(node, 'typeParameters') ?? node, 'params'); + const firstId = + first?.type === 'GenericTypeAnnotation' ? child(first, 'id') : null; + + return firstId + ? { name: typeName(firstId) } + : first + ? resolve(file, first, new Map(), seen) + : { name }; + } + seen.add(resolved.declaration); + const type = resolve( + resolved.file, + child(resolved.declaration, 'right') ?? node, + parametersFor(resolved.declaration, node, parameters), + seen, + ); + + seen.delete(resolved.declaration); + + return type; + } + + const params = nodes(child(node, 'typeParameters') ?? node, 'params'); + + if (name === '$Keys' && params[0]?.type === 'TypeofTypeAnnotation') { + const argument = child(params[0], 'argument'); + const typeId = + argument?.type === 'GenericTypeAnnotation' + ? child(argument, 'id') + : argument; + const object = typeId ? resolveValue(file, typeId) : null; + const keys = + object?.type === 'ObjectExpression' + ? nodes(object, 'properties').flatMap((property) => { + const key = child(property, 'key'); + + return key && isIdentifier(key) ? [key.name] : []; + }) + : []; + + if (keys.length > 0) { + return { + name: 'union', + raw: raw(file, node), + elements: keys.map((value) => ({ name: 'literal', value })), + }; + } + } + + return { + name, + ...(id?.type === 'QualifiedTypeIdentifier' ? { raw: raw(file, id) } : {}), + ...(params.length > 0 + ? { + elements: params.map((item) => resolve(file, item, parameters, seen)), + raw: raw(file, node), + } + : {}), + }; +} + +function resolve( + file: FileState, + node: AstNode, + parameters: Parameters, + seen: WeakSet, +): TypeDescriptor { + if (node.type === 'TypeAnnotation') { + const annotation = child(node, 'typeAnnotation'); + + return annotation + ? resolve(file, annotation, parameters, seen) + : { name: 'unknown' }; + } + const primitive = primitiveTypes[node.type]; + + if (primitive) return { name: primitive }; + if ( + node.type === 'BooleanLiteralTypeAnnotation' || + node.type === 'NumberLiteralTypeAnnotation' || + node.type === 'StringLiteralTypeAnnotation' || + node.type === 'BigIntLiteralTypeAnnotation' + ) { + return literal(file, node); + } + + if (node.type === 'GenericTypeAnnotation') { + return genericType(file, node, parameters, seen); + } + if (node.type === 'ArrayTypeAnnotation') { + const element = child(node, 'elementType'); + + return { + name: 'Array', + elements: element ? [resolve(file, element, parameters, seen)] : [], + raw: raw(file, node), + }; + } + if ( + node.type === 'UnionTypeAnnotation' || + node.type === 'IntersectionTypeAnnotation' + ) { + return { + name: node.type === 'UnionTypeAnnotation' ? 'union' : 'intersection', + raw: raw(file, node), + elements: nodes(node, 'types').map((item) => + resolve(file, item, parameters, seen), + ), + }; + } + if (node.type === 'TupleTypeAnnotation') { + return { + name: 'tuple', + raw: raw(file, node), + elements: nodes(node, 'types').map((item) => + resolve(file, item, parameters, seen), + ), + }; + } + if (node.type === 'NullableTypeAnnotation') { + const annotation = child(node, 'typeAnnotation'); + + return { + ...(annotation + ? resolve(file, annotation, parameters, seen) + : { name: 'unknown' }), + nullable: true, + }; + } + if (node.type === 'ObjectTypeAnnotation') { + return objectType(file, node, parameters, seen); + } + if (node.type === 'FunctionTypeAnnotation') { + const returnType = child(node, 'returnType'); + const args: Array> = nodes(node, 'params').map( + (parameter) => { + const name = child(parameter, 'name'); + const annotation = child(parameter, 'typeAnnotation'); + + return { + name: name && isIdentifier(name) ? name.name : '', + ...(annotation + ? { type: resolve(file, annotation, parameters, seen) } + : {}), + }; + }, + ); + const rest = child(node, 'rest'); + + if (rest) { + const name = child(rest, 'name'); + const annotation = child(rest, 'typeAnnotation'); + + args.push({ + name: name && isIdentifier(name) ? name.name : '', + ...(annotation + ? { type: resolve(file, annotation, parameters, seen) } + : {}), + rest: true, + }); + } + + return { + name: 'signature', + type: 'function', + raw: raw(file, node), + signature: { + arguments: args, + return: returnType + ? resolve(file, returnType, parameters, seen) + : { name: 'unknown' }, + }, + }; + } + if (node.type === 'TypeofTypeAnnotation') { + const argument = child(node, 'argument'); + + if (argument && isIdentifier(argument)) return { name: argument.name }; + + return argument + ? resolve(file, argument, parameters, seen) + : { name: 'unknown' }; + } + if (node.type === 'IndexedAccessType') { + const object = child(node, 'objectType'); + const index = child(node, 'indexType'); + const objectDescriptor = object + ? resolve(file, object, parameters, seen) + : { name: 'unknown' }; + const indexType = index + ? resolve(file, index, parameters, seen) + : { name: 'unknown' }; + const properties = + objectDescriptor.signature && + typeof objectDescriptor.signature === 'object' && + 'properties' in objectDescriptor.signature && + Array.isArray(objectDescriptor.signature.properties) + ? objectDescriptor.signature.properties + : []; + const key = + typeof indexType.value === 'string' + ? indexType.value.replace(/['"]/g, '') + : indexType.name; + const property = properties.find( + (item) => item && typeof item === 'object' && item.key === key, + ) as { value?: TypeDescriptor } | undefined; + + return property?.value + ? { name: property.value.name, raw: raw(file, node) } + : { name: 'unknown' }; + } + + return { name: 'unknown' }; +} + +export default function getFlowType( + file: FileState, + annotation: AstNode | null | undefined, + parameters: Parameters = new Map(), +): TypeDescriptor | null { + return annotation + ? resolve(file, annotation, parameters, new WeakSet()) + : null; +} diff --git a/packages/hermes/src/utils/getPropsMembers.ts b/packages/hermes/src/utils/getPropsMembers.ts new file mode 100644 index 00000000000..c1cf9bb9752 --- /dev/null +++ b/packages/hermes/src/utils/getPropsMembers.ts @@ -0,0 +1,184 @@ +import { isIdentifier, type AstNode, type FileState } from '@react-docgen/core'; +import { child, nodes, resolveType, typeName } from './ast.js'; + +type Parameters = Map; + +function parametersFor( + declaration: AstNode, + reference: AstNode, + inherited: Parameters, +): Parameters { + const parameters = new Map(inherited); + const declared = child(declaration, 'typeParameters'); + const provided = child(reference, 'typeParameters'); + const values = provided ? nodes(provided, 'params') : []; + + for (const [index, parameter] of (declared + ? nodes(declared, 'params') + : [] + ).entries()) { + const value = values[index]; + + const name = isIdentifier(parameter) + ? parameter.name + : typeof parameter.name === 'string' + ? parameter.name + : null; + + if (name && value) parameters.set(name, value); + } + + return parameters; +} + +function substitute(node: AstNode, parameters: Parameters): AstNode { + if (node.type === 'GenericTypeAnnotation') { + const id = child(node, 'id'); + + if (id && isIdentifier(id) && parameters.has(id.name)) { + return parameters.get(id.name) ?? node; + } + } + + const result: Record = { ...node }; + + for (const [key, value] of Object.entries(result)) { + if (Array.isArray(value)) { + result[key] = value.map((item) => + item && typeof item === 'object' && 'type' in item + ? substitute(item as AstNode, parameters) + : item, + ); + } else if (value && typeof value === 'object' && 'type' in value) { + result[key] = substitute(value as AstNode, parameters); + } + } + + return result as AstNode; +} + +export interface PropsMembers { + composes: string[]; + members: AstNode[]; + parameters: Parameters; +} + +export default function getPropsMembers( + file: FileState, + annotation: AstNode | null, + parameters: Parameters = new Map(), + seen = new WeakSet(), +): PropsMembers { + if (!annotation) return { composes: [], members: [], parameters }; + + if (annotation.type === 'ObjectTypeAnnotation') { + const members: AstNode[] = []; + const composes: string[] = []; + + for (const property of nodes(annotation, 'properties')) { + if (property.type !== 'ObjectTypeSpreadProperty') { + members.push(substitute(property, parameters)); + continue; + } + const spread = getPropsMembers( + file, + child(property, 'argument'), + parameters, + seen, + ); + + members.push(...spread.members); + composes.push(...spread.composes); + } + + return { composes, members, parameters }; + } + + if (annotation.type === 'IntersectionTypeAnnotation') { + const results = nodes(annotation, 'types').map((type) => + getPropsMembers(file, type, parameters, seen), + ); + + return { + composes: results.flatMap(({ composes }) => composes), + members: results.flatMap(({ members }) => members), + parameters, + }; + } + + if (annotation.type !== 'GenericTypeAnnotation') { + return { composes: [], members: [], parameters }; + } + + const id = child(annotation, 'id'); + const name = id ? typeName(id) : ''; + + if (['$Exact', '$ReadOnly'].includes(name)) { + const wrapped = nodes( + child(annotation, 'typeParameters') ?? annotation, + 'params', + )[0]; + + return getPropsMembers(file, wrapped ?? null, parameters, seen); + } + + const resolved = name ? resolveType(file, name) : null; + + if (!resolved) { + return { + composes: name && !name.startsWith('React') ? [name] : [], + members: [], + parameters, + }; + } + if (seen.has(resolved.declaration)) { + return { composes: [], members: [], parameters }; + } + + seen.add(resolved.declaration); + const nextParameters = parametersFor( + resolved.declaration, + annotation, + parameters, + ); + + if (resolved.declaration.type === 'TypeAlias') { + const result = getPropsMembers( + resolved.file, + child(resolved.declaration, 'right'), + nextParameters, + seen, + ); + + seen.delete(resolved.declaration); + + return result; + } + + const inherited = nodes(resolved.declaration, 'extends').map((heritage) => { + const heritageId = child(heritage, 'id'); + + return getPropsMembers( + resolved.file, + heritageId + ? ({ + ...heritage, + type: 'GenericTypeAnnotation', + id: heritageId, + } as AstNode) + : null, + nextParameters, + seen, + ); + }); + const body = child(resolved.declaration, 'body'); + const members = [ + ...inherited.flatMap((result) => result.members), + ...(body ? nodes(body, 'properties') : []), + ].map((member) => substitute(member, nextParameters)); + const composes = inherited.flatMap((result) => result.composes); + + seen.delete(resolved.declaration); + + return { composes, members, parameters: nextParameters }; +} diff --git a/packages/hermes/tests/integration/babel-differential-test.ts b/packages/hermes/tests/integration/babel-differential-test.ts new file mode 100644 index 00000000000..d770489a0f5 --- /dev/null +++ b/packages/hermes/tests/integration/babel-differential-test.ts @@ -0,0 +1,27 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { parse as parseBabel } from '@react-docgen/babel'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { describe, expect, test } from 'vitest'; +import { parse as parseHermes } from '../../src/index.js'; + +describe('Babel differential', () => { + for (const integrationCase of loadIntegrationCases({ languages: ['js'] })) { + if (integrationCase.error) continue; + + test(integrationCase.id, () => { + const options = { + filename: integrationCase.filename, + importer(specifier: string, fromFilename: string) { + const filename = path.resolve(path.dirname(fromFilename), specifier); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; + }, + }; + + expect(parseHermes(integrationCase.source, options)).toEqual( + parseBabel(integrationCase.source, options), + ); + }); + } +}); diff --git a/packages/hermes/tests/integration/integration-test.ts b/packages/hermes/tests/integration/integration-test.ts new file mode 100644 index 00000000000..5941ad68bf4 --- /dev/null +++ b/packages/hermes/tests/integration/integration-test.ts @@ -0,0 +1,39 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { describe, expect, test } from 'vitest'; +import { parse } from '../../src/index.js'; + +describe('integration', () => { + for (const integrationCase of loadIntegrationCases({ + languages: ['flow', 'js'], + })) { + test(integrationCase.id, () => { + const run = () => + parse(integrationCase.source, { + filename: integrationCase.filename, + importer(specifier, fromFilename) { + const base = path.resolve(path.dirname(fromFilename), specifier); + const extensionless = base.replace(/\.[^./]+$/, ''); + const filename = [ + base, + `${extensionless}.js`, + `${extensionless}.jsx`, + ].find((candidate) => fs.existsSync(candidate)); + + if (!filename) throw new Error(`Cannot resolve ${specifier}.`); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; + }, + }); + + if (integrationCase.error) { + expect(run).toThrow( + expect.objectContaining({ code: integrationCase.error.code }), + ); + } else { + expect(run()).toEqual(integrationCase.output); + } + }); + } +}); diff --git a/packages/hermes/tsconfig.json b/packages/hermes/tsconfig.json new file mode 100644 index 00000000000..5a24989cd30 --- /dev/null +++ b/packages/hermes/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/packages/hermes/vitest.config.ts b/packages/hermes/vitest.config.ts new file mode 100644 index 00000000000..46f4209c233 --- /dev/null +++ b/packages/hermes/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'hermes', + include: ['**/__tests__/**/*-test.ts', '**/tests/integration/**/*-test.ts'], + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6329382608a..535c28d189c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -272,6 +272,22 @@ importers: packages/core: {} + packages/hermes: + dependencies: + '@react-docgen/core': + specifier: workspace:* + version: link:../core + hermes-parser: + specifier: 0.25.1 + version: 0.25.1 + devDependencies: + '@react-docgen-internal/integration-tests': + specifier: workspace:* + version: link:../integration-tests + '@react-docgen/babel': + specifier: workspace:* + version: link:../babel + packages/integration-tests: {} packages/react-docgen: From f706fddf0cab20b19c1740a7840d5f9557df876f Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Mon, 21 Sep 2026 17:59:19 +0200 Subject: [PATCH 07/22] support mixed parser projects --- .github/workflows/build.yml | 8 +- PLAN.md | 26 +++-- package.json | 2 +- packages/babel/package.json | 2 +- packages/babel/src/index.ts | 7 +- packages/babel/src/normalize.ts | 45 -------- packages/core/package.json | 8 +- packages/core/src/ProjectContext.ts | 15 ++- .../src/__tests__/createParserRouter-test.ts | 109 ++++++++++++++++++ packages/core/src/createDocgen.ts | 21 +++- packages/core/src/createParserRouter.ts | 49 ++++++++ packages/core/src/index.ts | 7 ++ .../core/src/utils/parseMethodDocblock.ts | 101 +++++++++------- packages/hermes/package.json | 2 +- packages/hermes/src/hermes-parser.d.ts | 15 ++- packages/hermes/src/index.ts | 6 +- packages/hermes/src/parser.ts | 6 +- packages/react-docgen-cli/package.json | 2 +- .../src/commands/parse/command.ts | 44 +++++-- .../__fixtures__/config/Component.js | 3 + .../config/react-docgen.config.mjs | 5 + .../tests/integration/cli-test.ts | 15 +++ packages/react-docgen/package.json | 2 +- packages/typescript/package.json | 2 +- packages/typescript/src/index.ts | 6 +- packages/typescript/src/normalize.ts | 24 +--- packages/typescript/src/parser.ts | 8 +- .../__tests__/parseMethodDocblock-test.ts | 28 +++++ pnpm-lock.yaml | 21 +++- 29 files changed, 423 insertions(+), 166 deletions(-) create mode 100644 packages/core/src/__tests__/createParserRouter-test.ts create mode 100644 packages/core/src/createParserRouter.ts create mode 100644 packages/react-docgen-cli/tests/integration/__fixtures__/config/Component.js create mode 100644 packages/react-docgen-cli/tests/integration/__fixtures__/config/react-docgen.config.mjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3ed2aa99ca8..3eb1e83e7ef 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,19 +10,19 @@ on: permissions: {} env: - NODE_VERSION: 24 + NODE_VERSION: 24.11.0 jobs: tests: strategy: matrix: - node: ["22.13.0", "24", "25", "26"] + node: ["22.13.0", "24.11.0", "26.0.0"] os: ["ubuntu"] include: - os: macos - node: "24" + node: "24.11.0" - os: windows - node: "24" + node: "24.11.0" name: Tests (Node.js v${{ matrix.node }}, ${{ matrix.os }}) runs-on: ${{ matrix.os }}-latest diff --git a/PLAN.md b/PLAN.md index c790aeb4ca7..73390ec7fcf 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2,8 +2,8 @@ ## Status -- Current milestone: 5 — Mixed-parser projects -- Overall status: Milestone 4 complete +- Current milestone: 6 — Stable release and migration +- Overall status: Milestone 5 complete - Last updated: 2026-09-21 ## Decisions @@ -132,12 +132,12 @@ package; all applicable JavaScript output remains identical. ## Milestone 5 — Mixed-parser projects -- [ ] Add ordered `createParserRouter()` rules using filename, glob, or a custom +- [x] Add ordered `createParserRouter()` rules using filename, glob, or a custom selector. -- [ ] Require filenames when multiple parsers are configured. -- [ ] Route every imported file independently. -- [ ] Support parser-specific options per route and explicit no-match errors. -- [ ] Add CLI config for single-parser and mixed-parser projects. +- [x] Require filenames when multiple parsers are configured. +- [x] Route every imported file independently. +- [x] Support parser-specific options per route and explicit no-match errors. +- [x] Add CLI config for single-parser and mixed-parser projects. Exit criteria: TypeScript and Hermes files can import each other while preserving exports, bindings, descriptions, and props. @@ -190,6 +190,18 @@ import { parse } from '@react-docgen/typescript'; Record every material plan change here before or with implementation. +### 2026-09-21 — Completed mixed-parser projects milestone + +- Added ordered parser routing for exact filenames, globs, regular expressions, + and custom selectors, including per-route parser options and explicit no-match + errors. +- Required entry filenames when a router has multiple routes and kept imported + files on the same independent routing path. +- Added CLI config modules that can supply a preconfigured single-parser or + mixed-parser parse function. +- Reason: parser choice now follows each file through the whole project instead + of being fixed by the entry point. + ### 2026-09-21 — Completed Hermes and Flow milestone - Added `@react-docgen/hermes` as a thin Hermes parser adapter over shared core diff --git a/package.json b/package.json index 071ed65dcc4..baefdc9d41e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "engines": { - "node": "^22.13.0 || >=24", + "node": "^22.13.0 || ^24.11.0 || >=26", "pnpm": ">=10.6.2" }, "type": "module", diff --git a/packages/babel/package.json b/packages/babel/package.json index c7c9cbba449..505263ede73 100644 --- a/packages/babel/package.json +++ b/packages/babel/package.json @@ -14,7 +14,7 @@ "type": "module", "files": ["dist"], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26" }, "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/babel/src/index.ts b/packages/babel/src/index.ts index e6d481779ee..e18ef90e54b 100644 --- a/packages/babel/src/index.ts +++ b/packages/babel/src/index.ts @@ -1,4 +1,4 @@ -import { parseSync } from '@babel/core'; +import { parseSync, type TransformOptions } from '@babel/core'; import { VISITOR_KEYS } from '@babel/types'; import { createDocgen, @@ -20,14 +20,15 @@ export const visitorKeys: VisitorKeys = { }; const parser: Parser = { - parse(source) { + parse(source, options) { const ast = parseSync(source.code, { ast: true, code: false, filename: source.filename, parserOpts: { - plugins: ['jsx', 'typescript'], + plugins: ['jsx', 'typescript', 'estree'], }, + ...(options as TransformOptions | undefined), }); if (!ast) throw new TypeError('Babel did not return an AST.'); diff --git a/packages/babel/src/normalize.ts b/packages/babel/src/normalize.ts index d8dfce4dad2..713c966b16a 100644 --- a/packages/babel/src/normalize.ts +++ b/packages/babel/src/normalize.ts @@ -1,21 +1,10 @@ import { isAstNode, type AstNode } from '@react-docgen/core'; const typeNames: Record = { - BigIntLiteral: 'Literal', - BooleanLiteral: 'Literal', - ClassMethod: 'MethodDefinition', - ClassPrivateMethod: 'MethodDefinition', ClassPrivateProperty: 'PropertyDefinition', ClassProperty: 'PropertyDefinition', CommentBlock: 'Block', CommentLine: 'Line', - DecimalLiteral: 'Literal', - NullLiteral: 'Literal', - NumericLiteral: 'Literal', - ObjectMethod: 'Property', - ObjectProperty: 'Property', - RegExpLiteral: 'Literal', - StringLiteral: 'Literal', }; function normalizeValue(value: unknown): unknown { @@ -49,40 +38,6 @@ function normalizeValue(value: unknown): unknown { output.range = [input.start, input.end]; } - if (output.type === 'Literal') { - output.raw = - input.extra && typeof input.extra === 'object' && 'raw' in input.extra - ? (input.extra as { raw: unknown }).raw - : originalType === 'NullLiteral' - ? 'null' - : input.value; - if (originalType === 'NullLiteral') output.value = null; - } - - if (originalType === 'ObjectMethod') { - output.value = { - type: 'FunctionExpression', - range: output.range, - params: output.params, - body: output.body, - async: output.async, - generator: output.generator, - returnType: output.returnType, - }; - } - - if (originalType === 'ClassMethod' || originalType === 'ClassPrivateMethod') { - output.value = { - type: 'FunctionExpression', - range: output.range, - params: output.params, - body: output.body, - async: output.async, - generator: output.generator, - returnType: output.returnType, - }; - } - return output; } diff --git a/packages/core/package.json b/packages/core/package.json index 69379c765b2..5387acbf412 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -16,7 +16,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26" }, "main": "dist/index.js", "types": "dist/index.d.ts", @@ -24,5 +24,9 @@ "build": "rimraf dist/ && tsc", "test": "vitest run" }, - "license": "MIT" + "license": "MIT", + "dependencies": { + "comment-parser": "^1.4.9", + "jsdoc-type-pratt-parser": "8.0.0" + } } diff --git a/packages/core/src/ProjectContext.ts b/packages/core/src/ProjectContext.ts index 6b674c868f8..7910d46bf23 100644 --- a/packages/core/src/ProjectContext.ts +++ b/packages/core/src/ProjectContext.ts @@ -10,10 +10,15 @@ export interface SourceFile { export interface Parser { readonly visitorKeys: VisitorKeys; - parse(source: SourceFile): AstNode; + parse(source: SourceFile, options?: unknown): AstNode; } -export type ParserSelector = (filename: string) => Parser; +export interface ParserSelection { + readonly options?: unknown; + readonly parser: Parser; +} + +export type ParserSelector = (filename: string) => Parser | ParserSelection; export type Importer = (specifier: string, fromFilename: string) => SourceFile; export class FileState { @@ -61,8 +66,10 @@ export default class ProjectContext { } parse(source: SourceFile): FileState { - const parser = this.#selectParser(source.filename); - const ast = parser.parse(source); + const selection = this.#selectParser(source.filename); + const { options, parser } = + 'parser' in selection ? selection : { parser: selection }; + const ast = parser.parse(source, options); return new FileState(this, source, ast, parser.visitorKeys); } diff --git a/packages/core/src/__tests__/createParserRouter-test.ts b/packages/core/src/__tests__/createParserRouter-test.ts new file mode 100644 index 00000000000..a875ea82ed1 --- /dev/null +++ b/packages/core/src/__tests__/createParserRouter-test.ts @@ -0,0 +1,109 @@ +import { describe, expect, test, vi } from 'vitest'; +import { + createDocgen, + createParserRouter, + type Handler, + type Parser, + type Resolver, +} from '../index.js'; + +const resolver: Resolver = (file) => [file.path]; +const handler: Handler = (documentation, _path, file) => { + documentation.description = file.ast.type; +}; + +function makeParser(type: string): Parser { + return { + parse: vi.fn((_source, options) => ({ type, options })), + visitorKeys: {}, + }; +} + +describe('createParserRouter', () => { + test('uses the first matching filename, glob, or custom rule', () => { + const exact = makeParser('Exact'); + const glob = makeParser('Glob'); + const custom = makeParser('Custom'); + const router = createParserRouter([ + { test: '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/project/special.tsx', parser: exact }, + { test: '**/*.tsx', parser: glob, options: { jsx: true } }, + { test: (filename) => filename.endsWith('.js'), parser: custom }, + ]); + + expect(router('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/project/special.tsx')).toEqual({ + options: undefined, + parser: exact, + }); + expect(router('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/project/Button.tsx')).toEqual({ + options: { jsx: true }, + parser: glob, + }); + expect(router('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/project/Button.js')).toEqual({ + options: undefined, + parser: custom, + }); + }); + + test('supports standard glob syntax', () => { + const parser = makeParser('Matched'); + const router = createParserRouter([{ test: '**/*.{js,tsx}', parser }]); + + expect(router('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/project/Button.tsx').parser).toBe(parser); + expect(router('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/project/Button.js').parser).toBe(parser); + expect(() => router('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/project/Button.css')).toThrow(); + }); + + test('passes route options and requires a filename for multiple parsers', () => { + const typescript = makeParser('TypeScriptFile'); + const hermes = makeParser('HermesFile'); + const parse = createDocgen({ + handlers: [handler], + parser: createParserRouter([ + { test: /\.tsx$/, parser: typescript, options: { jsx: true } }, + { test: /\.js$/, parser: hermes }, + ]), + resolver, + }); + + expect(() => parse('')).toThrow( + 'A filename is required when multiple parsers are configured.', + ); + expect(parse('', { filename: 'Button.tsx' })).toEqual([ + { description: 'TypeScriptFile', methods: [] }, + ]); + expect(typescript.parse).toHaveBeenCalledWith( + { code: '', filename: 'Button.tsx' }, + { jsx: true }, + ); + }); + + test('routes imported files independently', () => { + const parse = createDocgen({ + handlers: [ + (_documentation, _path, file) => { + _documentation.description = file.import('./support.js').ast.type; + }, + ], + importer: () => ({ code: '', filename: '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/project/support.js' }), + parser: createParserRouter([ + { test: '**/*.tsx', parser: makeParser('TypeScriptFile') }, + { test: '**/*.js', parser: makeParser('HermesFile') }, + ]), + resolver, + }); + + expect(parse('', { filename: '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/project/Button.tsx' })).toEqual([ + { description: 'HermesFile', methods: [] }, + ]); + }); + + test('reports an explicit no-match error', () => { + const router = createParserRouter([ + { test: '**/*.tsx', parser: makeParser('TypeScriptFile') }, + ]); + + expect(() => router('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/project/Button.js')).toThrow( + 'No parser route matched "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/project/Button.js".', + ); + }); +}); diff --git a/packages/core/src/createDocgen.ts b/packages/core/src/createDocgen.ts index 5e822b8b59a..f9c95ae2b78 100644 --- a/packages/core/src/createDocgen.ts +++ b/packages/core/src/createDocgen.ts @@ -6,12 +6,14 @@ import extract, { import ProjectContext, { type Importer, type Parser, + type ParserSelector, } from './ProjectContext.js'; +import type { ParserRouter } from './createParserRouter.js'; export interface CreateDocgenOptions { handlers: readonly Handler[]; importer?: Importer; - parser: Parser; + parser: Parser | ParserSelector; resolver: Resolver; } @@ -29,7 +31,20 @@ export default function createDocgen({ code: string, options?: DocgenParseOptions, ) => ComponentDocumentation[] { - return (code, { filename = 'component.js', importer } = {}) => { + return (code, options = {}) => { + const { importer } = options; + const filename = options.filename ?? 'component.js'; + + if ( + typeof parser === 'function' && + (parser as ParserRouter).requiresFilename && + options.filename == null + ) { + throw new TypeError( + 'A filename is required when multiple parsers are configured.', + ); + } + const project = new ProjectContext({ importer: importer ?? @@ -37,7 +52,7 @@ export default function createDocgen({ (() => { throw new Error('An importer is required to resolve imported files.'); }), - selectParser: () => parser, + selectParser: typeof parser === 'function' ? parser : () => parser, }); const file = project.parse({ code, filename }); diff --git a/packages/core/src/createParserRouter.ts b/packages/core/src/createParserRouter.ts new file mode 100644 index 00000000000..390fc51f122 --- /dev/null +++ b/packages/core/src/createParserRouter.ts @@ -0,0 +1,49 @@ +import { matchesGlob } from 'node:path'; +import type { + Parser, + ParserSelection, + ParserSelector, +} from './ProjectContext.js'; + +export type ParserRouteTest = RegExp | string | ((filename: string) => boolean); + +export interface ParserRoute { + readonly options?: unknown; + readonly parser: Parser; + readonly test: ParserRouteTest; +} + +export interface ParserRouter extends ParserSelector { + readonly requiresFilename: boolean; +} + +function matches(test: ParserRouteTest, filename: string): boolean { + if (typeof test === 'function') return test(filename); + if (typeof test === 'string') return matchesGlob(filename, test); + + test.lastIndex = 0; + + return test.test(filename); +} + +export default function createParserRouter( + routes: readonly ParserRoute[], +): ParserRouter { + if (routes.length === 0) { + throw new TypeError('Parser routes must not be empty.'); + } + + const router = (filename: string): ParserSelection => { + const route = routes.find(({ test }) => matches(test, filename)); + + if (!route) { + throw Object.assign(new Error(`No parser route matched "${filename}".`), { + code: 'ERR_REACTDOCGEN_PARSER_NO_MATCH', + }); + } + + return { options: route.options, parser: route.parser }; + }; + + return Object.assign(router, { requiresFilename: routes.length > 1 }); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3364202e029..bfcce2b70b3 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,5 +1,6 @@ export { default as AstPath } from './AstPath.js'; export { default as createDocgen } from './createDocgen.js'; +export { default as createParserRouter } from './createParserRouter.js'; export { isAstNode } from './AstNode.js'; export { default as extract } from './extract.js'; export * from './guards.js'; @@ -48,6 +49,7 @@ export type * from './nodes.js'; export type { Importer, Parser, + ParserSelection, ParserSelector, SourceFile, } from './ProjectContext.js'; @@ -55,6 +57,11 @@ export type { CreateDocgenOptions, DocgenParseOptions, } from './createDocgen.js'; +export type { + ParserRoute, + ParserRouter, + ParserRouteTest, +} from './createParserRouter.js'; export type { Binding, BindingKind } from './Scope.js'; export type { TypeResolver } from './handlers/methodHandler.js'; export type { diff --git a/packages/core/src/utils/parseMethodDocblock.ts b/packages/core/src/utils/parseMethodDocblock.ts index 698b86b09e3..971956c3e58 100644 --- a/packages/core/src/utils/parseMethodDocblock.ts +++ b/packages/core/src/utils/parseMethodDocblock.ts @@ -1,3 +1,5 @@ +import { parse } from 'comment-parser'; +import { stringify, tryParse, type RootResult } from 'jsdoc-type-pratt-parser'; import type { TypeDescriptor } from '../internal.js'; export interface DocblockParam { @@ -13,67 +15,80 @@ export interface ParsedMethodDocblock { returns: { description?: string; type?: TypeDescriptor } | null; } -function parseType(raw: string): TypeDescriptor { - const value = raw.replace(/=$/, ''); - - if (value === '*') return { name: 'mixed' }; - if (value.startsWith('[') && value.endsWith(']')) { - return { - name: 'tuple', - elements: value - .slice(1, -1) - .split(',') - .map((part) => parseType(part.trim())), - }; - } - if (value.includes('|')) { - return { name: 'union', elements: value.split('|').map(parseType) }; - } - if (value.endsWith('[]')) { - return { name: 'Array', elements: [parseType(value.slice(0, -2))] }; +function typeDescriptor(type: RootResult): TypeDescriptor { + switch (type.type) { + case 'JsdocTypeAny': + return { name: 'mixed' }; + case 'JsdocTypeName': + return { name: type.value }; + case 'JsdocTypeGeneric': + return { + name: typeDescriptor(type.left).name, + elements: type.elements.map(typeDescriptor), + }; + case 'JsdocTypeTuple': + return { + name: 'tuple', + elements: type.elements.map((element) => + element.type === 'JsdocTypeKeyValue' + ? element.right + ? typeDescriptor(element.right) + : { name: element.key } + : typeDescriptor(element), + ), + }; + case 'JsdocTypeUnion': + return { name: 'union', elements: type.elements.map(typeDescriptor) }; + case 'JsdocTypeNotNullable': + case 'JsdocTypeNullable': + case 'JsdocTypeOptional': + case 'JsdocTypeParenthesis': + return typeDescriptor(type.element); + case 'JsdocTypeVariadic': + return type.element + ? typeDescriptor(type.element) + : { name: stringify(type) }; + default: + return { name: stringify(type) }; } +} - return { name: value }; +function parseType(raw: string): TypeDescriptor { + const parsed = tryParse(raw, ['typescript', 'jsdoc']); + + return parsed ? typeDescriptor(parsed) : { name: raw }; } export default function parseMethodDocblock( docblock: string, ): ParsedMethodDocblock { + const source = `/**\n${docblock + .split('\n') + .map((line) => ` * ${line}`) + .join('\n')}\n */`; + const block = parse(source)[0]; const params = new Map(); let returns: ParsedMethodDocblock['returns'] = null; - const description: string[] = []; - - for (const line of docblock.split('\n')) { - const trimmed = line.trim(); - const param = /^@param\s+\{([^}]+)\}\s+(\S+)(?:\s+(.*))?$/.exec(trimmed); - if (param) { - const [, rawType = '', rawName = '', text] = param; - const name = rawName.replace(/^\.\.\./, '').replace(/^\[|\]$/g, ''); + for (const tag of block?.tags ?? []) { + if (tag.tag === 'param') { + const name = tag.name.replace(/^\.\.\./, ''); params.set(name, { name, - optional: rawType.endsWith('=') || /^\[/.test(rawName), - type: parseType(rawType), - ...(text ? { description: text } : {}), + optional: tag.optional || tag.type.endsWith('='), + ...(tag.type ? { type: parseType(tag.type) } : {}), + ...(tag.description ? { description: tag.description } : {}), }); - continue; - } - const returned = /^@returns?\s*(?:\{([^}]+)\})?\s*(.*)$/.exec(trimmed); - - if (returned && !returns) { - const [, rawType, text] = returned; + } else if ((tag.tag === 'return' || tag.tag === 'returns') && !returns) { + const description = [tag.name, tag.description].filter(Boolean).join(' '); returns = { - ...(rawType ? { type: parseType(rawType) } : {}), - ...(text ? { description: text } : {}), + ...(tag.type ? { type: parseType(tag.type) } : {}), + ...(description ? { description } : {}), }; - continue; - } - if (!trimmed.startsWith('@') && (description.length > 0 || trimmed)) { - description.push(trimmed); } } - return { description: description.join('\n').trim(), params, returns }; + return { description: block?.description ?? '', params, returns }; } diff --git a/packages/hermes/package.json b/packages/hermes/package.json index fd79b9d8b56..f907004b653 100644 --- a/packages/hermes/package.json +++ b/packages/hermes/package.json @@ -16,7 +16,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26" }, "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/hermes/src/hermes-parser.d.ts b/packages/hermes/src/hermes-parser.d.ts index f7847f6cea2..fe75ca8c84e 100644 --- a/packages/hermes/src/hermes-parser.d.ts +++ b/packages/hermes/src/hermes-parser.d.ts @@ -1,11 +1,10 @@ declare module 'hermes-parser' { + export interface ParserOptions { + flow: 'all' | 'detect'; + sourceType: 'module' | 'script' | 'unambiguous'; + tokens?: boolean; + } + export const FlowVisitorKeys: Record; - export function parse( - code: string, - options: { - flow: 'all' | 'detect'; - sourceType: 'module' | 'script' | 'unambiguous'; - tokens?: boolean; - }, - ): unknown; + export function parse(code: string, options: ParserOptions): unknown; } diff --git a/packages/hermes/src/index.ts b/packages/hermes/src/index.ts index d5fe8845f4e..806159a0244 100644 --- a/packages/hermes/src/index.ts +++ b/packages/hermes/src/index.ts @@ -17,7 +17,11 @@ import parser from './parser.js'; import getFlowType from './utils/getFlowType.js'; import { child, typeName } from './utils/ast.js'; -export { default as parser, visitorKeys } from './parser.js'; +export { + default as parser, + visitorKeys, + type ParserOptions, +} from './parser.js'; export interface ParseOptions { filename?: string; diff --git a/packages/hermes/src/parser.ts b/packages/hermes/src/parser.ts index 191e023b16c..bcc60133f75 100644 --- a/packages/hermes/src/parser.ts +++ b/packages/hermes/src/parser.ts @@ -1,11 +1,12 @@ -import { FlowVisitorKeys, parse } from 'hermes-parser'; +import { FlowVisitorKeys, parse, type ParserOptions } from 'hermes-parser'; import type { Parser, VisitorKeys } from '@react-docgen/core'; import normalize from './normalize.js'; export const visitorKeys: VisitorKeys = FlowVisitorKeys; +export type { ParserOptions }; const parser: Parser = { - parse(source) { + parse(source, options) { if (/\.(?:cts|mts|ts|tsx)$/.test(source.filename)) { throw Object.assign( new Error('The Hermes adapter does not support TypeScript syntax.'), @@ -17,6 +18,7 @@ const parser: Parser = { parse(source.code, { flow: 'all', sourceType: 'unambiguous', + ...(options as Partial | undefined), }), ); }, diff --git a/packages/react-docgen-cli/package.json b/packages/react-docgen-cli/package.json index 4336a14c918..835b75d3829 100644 --- a/packages/react-docgen-cli/package.json +++ b/packages/react-docgen-cli/package.json @@ -19,7 +19,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26" }, "scripts": { "build": "rimraf dist/ && tsc", diff --git a/packages/react-docgen-cli/src/commands/parse/command.ts b/packages/react-docgen-cli/src/commands/parse/command.ts index 18a1a12c2c4..70699a9098c 100644 --- a/packages/react-docgen-cli/src/commands/parse/command.ts +++ b/packages/react-docgen-cli/src/commands/parse/command.ts @@ -10,6 +10,7 @@ import { resolve } from 'path'; import slash from '../../utils/slash.js'; import type { Documentation } from 'react-docgen'; import { ResolverConfigs } from './options/loadResolvers.js'; +import importFile from '../../utils/importFile.js'; const debug = debugFactory('react-docgen:cli'); @@ -38,6 +39,7 @@ function collect(value: string, previous: string[]): string[] { } interface CLIOptions { + config?: string; defaultIgnores: boolean; failOnWarning: boolean; handler?: string[]; @@ -54,6 +56,10 @@ export default function createParseCommand(): Command { 'Extract meta information from React components.\n' + 'Either specify a paths to files or a glob pattern that matches multiple files.', ) + .option( + '-c, --config ', + 'Trusted module exporting a parse function, or an object with a parse function, for single-parser or mixed-parser projects.', + ) .option( '-o, --out ', 'Store extracted information in the specified file instead of printing to stdout. If the file exists it will be overwritten.', @@ -96,6 +102,7 @@ export default function createParseCommand(): Command { .argument('', 'Can be globs or paths to files') .action(async (globs: string[], input: CLIOptions) => { const { + config, defaultIgnores, failOnWarning, handler, @@ -115,11 +122,24 @@ export default function createParseCommand(): Command { finalIgnores = []; } - const options = await loadOptions({ - handler, - importer, - resolver, - }); + const configured = config + ? await importFile(config) + : undefined; + + if (config && !configured) { + throw new TypeError(`Could not load config '${config}'.`); + } + const configuredParse = + typeof configured === 'function' ? configured : configured?.parse; + + if (configured && typeof configuredParse !== 'function') { + throw new TypeError( + `Config '${config}' must export a parse function or an object with a parse function.`, + ); + } + const options = configuredParse + ? undefined + : await loadOptions({ handler, importer, resolver }); // we use slash to convert windows backslashes to unix format so fast-glob works const files = await glob(globs.map(slash), { ignore: finalIgnores?.map((ignorePath) => { @@ -143,12 +163,14 @@ export default function createParseCommand(): Command { const content = await readFile(path, 'utf-8'); try { - result[path] = parse(content, { - filename: path, - handlers: options.handlers, - importer: options.importer, - resolver: options.resolver, - }); + result[path] = configuredParse + ? configuredParse(content, { filename: path }) + : parse(content, { + filename: path, + handlers: options?.handlers, + importer: options?.importer, + resolver: options?.resolver, + }); } catch (error) { const isError = outputError(error as Error, path, { failOnWarning, diff --git a/packages/react-docgen-cli/tests/integration/__fixtures__/config/Component.js b/packages/react-docgen-cli/tests/integration/__fixtures__/config/Component.js new file mode 100644 index 00000000000..005f6c6604e --- /dev/null +++ b/packages/react-docgen-cli/tests/integration/__fixtures__/config/Component.js @@ -0,0 +1,3 @@ +export function Component() { + return null; +} diff --git a/packages/react-docgen-cli/tests/integration/__fixtures__/config/react-docgen.config.mjs b/packages/react-docgen-cli/tests/integration/__fixtures__/config/react-docgen.config.mjs new file mode 100644 index 00000000000..29feeee4896 --- /dev/null +++ b/packages/react-docgen-cli/tests/integration/__fixtures__/config/react-docgen.config.mjs @@ -0,0 +1,5 @@ +export default { + parse(_code, { filename }) { + return [{ displayName: filename.endsWith('.js') ? 'Configured' : 'Wrong' }]; + }, +}; diff --git a/packages/react-docgen-cli/tests/integration/cli-test.ts b/packages/react-docgen-cli/tests/integration/cli-test.ts index f0beefec846..c0a34c72b20 100644 --- a/packages/react-docgen-cli/tests/integration/cli-test.ts +++ b/packages/react-docgen-cli/tests/integration/cli-test.ts @@ -5,6 +5,21 @@ import { describe, expect, test } from 'vitest'; import withFixture from './utils/withFixture'; describe('cli', () => { + test('loads a single-parser or mixed-parser config module', async () => { + await withFixture('config', async ({ dir, run }) => { + const { stdout, stderr } = await run([ + '--config', + join(dir, 'react-docgen.config.mjs'), + join(dir, 'Component.js'), + ]); + + expect(stderr).toBe(''); + expect(JSON.parse(stdout)).toEqual({ + [join(dir, 'Component.js')]: [{ displayName: 'Configured' }], + }); + }); + }); + describe('glob', () => { test('reads files provided as command line arguments', async () => { await withFixture('basic', async ({ dir, run }) => { diff --git a/packages/react-docgen/package.json b/packages/react-docgen/package.json index 8dc16cf259a..7301b2ec8b7 100644 --- a/packages/react-docgen/package.json +++ b/packages/react-docgen/package.json @@ -22,7 +22,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26" }, "main": "dist/main.js", "typings": "dist/main.d.ts", diff --git a/packages/typescript/package.json b/packages/typescript/package.json index a374dd14756..0b9913641da 100644 --- a/packages/typescript/package.json +++ b/packages/typescript/package.json @@ -16,7 +16,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26" }, "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/typescript/src/index.ts b/packages/typescript/src/index.ts index 3edfc133df6..915ae11231a 100644 --- a/packages/typescript/src/index.ts +++ b/packages/typescript/src/index.ts @@ -13,7 +13,11 @@ import typescriptPropsHandler from './handlers/typescriptPropsHandler.js'; import parser from './parser.js'; import getTSType from './utils/getTSType.js'; -export { default as parser, visitorKeys } from './parser.js'; +export { + default as parser, + visitorKeys, + type ParserOptions, +} from './parser.js'; export interface ParseOptions { filename?: string; diff --git a/packages/typescript/src/normalize.ts b/packages/typescript/src/normalize.ts index bdb638d4615..fc66776153e 100644 --- a/packages/typescript/src/normalize.ts +++ b/packages/typescript/src/normalize.ts @@ -1,29 +1,9 @@ import { isAstNode, type AstNode } from '@react-docgen/core'; -function normalizeValue(value: unknown): unknown { - if (Array.isArray(value)) { - return value.map(normalizeValue); - } - - if (typeof value !== 'object' || value === null) { - return value; - } - - const normalized: Record = {}; - - for (const [key, child] of Object.entries(value)) { - normalized[key] = normalizeValue(child); - } - - return normalized; -} - export default function normalize(node: unknown): AstNode { - const normalized = normalizeValue(node); - - if (!isAstNode(normalized)) { + if (!isAstNode(node)) { throw new TypeError('Parser did not return an AST node.'); } - return normalized; + return node; } diff --git a/packages/typescript/src/parser.ts b/packages/typescript/src/parser.ts index 2e5deb207f8..dd54be0416d 100644 --- a/packages/typescript/src/parser.ts +++ b/packages/typescript/src/parser.ts @@ -1,19 +1,21 @@ -import { parse } from '@typescript-eslint/typescript-estree'; +import { parse as parseTypeScript } from '@typescript-eslint/typescript-estree'; import { visitorKeys as typescriptVisitorKeys } from '@typescript-eslint/visitor-keys'; import type { Parser, VisitorKeys } from '@react-docgen/core'; import normalize from './normalize.js'; export const visitorKeys: VisitorKeys = typescriptVisitorKeys; +export type ParserOptions = NonNullable[1]>; const parser: Parser = { - parse(source) { + parse(source, options) { return normalize( - parse(source.code, { + parseTypeScript(source.code, { comment: true, filePath: source.filename, jsx: true, loc: true, range: true, + ...(options as ParserOptions | undefined), }), ); }, diff --git a/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts b/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts index 1de7d6dc9f1..534c2041561 100644 --- a/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts +++ b/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts @@ -18,3 +18,31 @@ test('parses method summary, parameters, and return tags', () => { type: { name: 'number' }, }); }); + +test('parses JSDoc compound types and untyped tags', () => { + const parsed = parseMethodDocblock(` +@param {[string, number]} tuple +@param {string|Object|some[]} value +@param [label] Optional label. +@returns The result. + `); + + expect(parsed.params.get('tuple')?.type).toEqual({ + name: 'tuple', + elements: [{ name: 'string' }, { name: 'number' }], + }); + expect(parsed.params.get('value')?.type).toEqual({ + name: 'union', + elements: [ + { name: 'string' }, + { name: 'Object' }, + { name: 'Array', elements: [{ name: 'some' }] }, + ], + }); + expect(parsed.params.get('label')).toEqual({ + description: 'Optional label.', + name: 'label', + optional: true, + }); + expect(parsed.returns).toEqual({ description: 'The result.' }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 535c28d189c..e171ea3af34 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -270,7 +270,14 @@ importers: specifier: npm:react-docgen@6.0.0 version: react-docgen@6.0.0(supports-color@7.2.0) - packages/core: {} + packages/core: + dependencies: + comment-parser: + specifier: ^1.4.9 + version: 1.4.9 + jsdoc-type-pratt-parser: + specifier: 8.0.0 + version: 8.0.0 packages/hermes: dependencies: @@ -2331,6 +2338,10 @@ packages: resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} engines: {node: '>= 12'} + comment-parser@1.4.9: + resolution: {integrity: sha512-+2AvZKjJaNq9GQljm3tr0utwrig5BL+jgJGvz5rDpGKNIp+ojcRXWUwBbh/sGIi1QCprR6PsKFakub+w1v+4hQ==} + engines: {node: '>= 12.0.0'} + compute-scroll-into-view@3.1.1: resolution: {integrity: sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==} @@ -3441,6 +3452,10 @@ packages: resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} hasBin: true + jsdoc-type-pratt-parser@8.0.0: + resolution: {integrity: sha512-uQu/fXVqVaMg6gM8/E5G5+eygVcZ1NV0Z51CvqhNa2bDWxvHMl484ETr6vph4oPyC+KUcbP/w2W2pewfCiR9aQ==} + engines: {node: '>=20.0.0'} + jsesc@3.1.0: resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} engines: {node: '>=6'} @@ -7097,6 +7112,8 @@ snapshots: commander@8.3.0: {} + comment-parser@1.4.9: {} + compute-scroll-into-view@3.1.1: {} concat-map@0.0.1: {} @@ -8485,6 +8502,8 @@ snapshots: dependencies: argparse: 2.0.1 + jsdoc-type-pratt-parser@8.0.0: {} + jsesc@3.1.0: {} json-schema-traverse@0.4.1: {} From e4bdb35e4dba918c4a54c95192329a64e5cfb058 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sun, 25 Oct 2026 10:52:43 +0100 Subject: [PATCH 08/22] plan --- PLAN.md | 90 ++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 73 insertions(+), 17 deletions(-) diff --git a/PLAN.md b/PLAN.md index 73390ec7fcf..2ea3568d6d6 100644 --- a/PLAN.md +++ b/PLAN.md @@ -3,9 +3,26 @@ ## Status - Current milestone: 6 — Stable release and migration -- Overall status: Milestone 5 complete +- Overall status: Default extraction parity complete; public API and release + hardening remain - Last updated: 2026-09-21 +## Release-readiness summary + +- Default JavaScript and PropTypes behavior is covered across the TypeScript, + Hermes, and Babel adapters. +- TypeScript behavior is covered except for one fixture that uses Babel-only + `export defaultFrom from` syntax and must be reclassified. +- Flow behavior is covered through Hermes. +- Defaults, descriptions, methods, imports, exports, and parser-neutral error + output are represented by portable fixtures. +- Neutral handler, resolver, importer, and parser contracts exist, but not every + legacy public extension point has a stable replacement yet. +- Parser routing is implemented per file, but the mixed TypeScript/Hermes exit + criterion still needs a real cross-parser integration fixture. +- The parser-neutral `react-docgen` facade, native CLI parser configuration, + migration documentation, and package release validation are not complete. + ## Decisions 1. `@react-docgen/core` will not depend on Babel, Hermes, or TypeScript. @@ -95,14 +112,15 @@ output; no Babel types leak from new APIs. - [x] Replace the monolithic snapshot with one JSON outcome per case. - [x] Run all cases through legacy `react-docgen` and a temporary supported-case allowlist through `@react-docgen/typescript`. -- [x] Map disabled unit-test behaviors to portable fixtures or narrow, evidenced exclusions. +- [x] Map disabled unit-test behaviors to portable fixtures or narrow, evidenced + exclusions. - [x] Add coverage-driven fixtures without production changes or coverage hints. - [x] Record the integration-only plateau and enforce its integer-floor coverage thresholds. -Exit criteria: migrated output remains unchanged; all public behavior represented -by disabled unit tests is covered or classified; legacy integration coverage -cannot silently regress. +Exit criteria: migrated output remains unchanged; all public behavior +represented by disabled unit tests is covered or classified; legacy integration +coverage cannot silently regress. ## Milestone 4 — Hermes and Flow @@ -122,8 +140,8 @@ matches the legacy implementation. extraction. - [x] Keep TypeScript-only type helpers and handler composition in `@react-docgen/typescript`. -- [x] Expose preconfigured `parse()` from `@react-docgen/babel` using only - Babel plus shared core extraction. +- [x] Expose preconfigured `parse()` from `@react-docgen/babel` using only Babel + plus shared core extraction. - [x] Keep focused utility tests and JavaScript differential fixtures green. Exit criteria: Babel and TypeScript adapters share React extraction without @@ -144,12 +162,34 @@ preserving exports, bindings, descriptions, and props. ## Milestone 6 — Stable release and migration -- [ ] Stabilize scoped packages after parity and extension API validation. +- [ ] Decide the final package boundary before freezing APIs: keep shared React + extraction in core or move it to `@react-docgen/react`, and decide whether + method JSDoc parsing becomes an optional composition package. +- [ ] Reconcile the intended convenience API with the current composition API: + either make `createDocgen({ parser })` supply standard React behavior or + document the required handlers and resolver explicitly. +- [ ] Add a real mixed-parser integration fixture in which TypeScript and Hermes + files import each other while preserving exports, bindings, descriptions, + defaults, and props. +- [ ] Reclassify `typescript/imports/reexported-default-values`, whose + `export defaultFrom from` syntax is Babel-specific, or assert an explicit + parser capability error. +- [ ] Stabilize scoped packages after parity and extension API validation, + including exported types and parser-specific options. - [ ] Release the next `react-docgen` major as a parser-neutral facade with no implicit `parse()` backend. - [ ] Remove Babel-specific extension contracts from the new major. -- [ ] Publish migration guide, README guidance, release notes, and CLI - documentation. +- [ ] Inventory every legacy public handler, resolver, importer, utility, error, + `FileState`, and Babel `NodePath` export; implement or document its + neutral replacement. +- [ ] Update the CLI to configure scoped single-parser and mixed-parser projects + directly instead of relying only on a custom `parse` function escape + hatch. +- [ ] Publish package READMEs, a migration guide, release notes, and CLI + configuration documentation. +- [ ] Validate packed tarballs, clean consumer installs, declaration output, + package exports, changesets, and the supported Node matrix before + versioning. - [ ] Keep `react-docgen@8` available for legacy Babel behavior. Exit criteria: users must explicitly install/select a parser, and every legacy @@ -167,6 +207,8 @@ const parser = createParserRouter([ { test: /\.(?:js|jsx|mjs|cjs)$/, parser: hermes }, ]); +// Final milestone 6 decision: either this convenience form supplies the +// standard React resolver/handlers, or callers compose them explicitly. const docgen = createDocgen({ parser }); ``` @@ -190,6 +232,19 @@ import { parse } from '@react-docgen/typescript'; Record every material plan change here before or with implementation. +### 2026-09-21 — Audited release readiness after mixed-parser implementation + +- Confirmed default JavaScript, TypeScript, and Flow extraction parity across + the portable corpus, apart from one Babel-only export-syntax fixture currently + classified as TypeScript. +- Distinguished implemented parser routing from the still-missing real + TypeScript/Hermes cross-import integration proof. +- Expanded Milestone 6 to cover package boundaries, facade/API stabilization, + legacy extension migration, native CLI configuration, documentation, and + packed-package validation. +- Reason: the extraction engine is largely complete, but the stable public + product surface requires more than publishing the scoped packages. + ### 2026-09-21 — Completed mixed-parser projects milestone - Added ordered parser routing for exact filenames, globs, regular expressions, @@ -285,8 +340,8 @@ Record every material plan change here before or with implementation. `@react-docgen-internal/integration-tests`, grouped by language and behavior. - Replaced parser capability metadata with language directories and added a validating dependency-free loader. -- Added coverage-driven public behavior cases and a TypeScript adapter allowlist; - the legacy package remains the complete reference runner. +- Added coverage-driven public behavior cases and a TypeScript adapter + allowlist; the legacy package remains the complete reference runner. - Started disabled unit-test dispositions in the corpus audit and expanded integration-only coverage from 71.33% to 79.28% statements. - Reason: parser implementations need one portable observable-output contract; @@ -296,10 +351,11 @@ Record every material plan change here before or with implementation. - Removed the initial 79/68/89/79 thresholds and withdrew the claimed behavioral plateau. -- Kept 92% coverage from the complete unit-and-integration suite as the practical - reachability benchmark for the integration corpus. +- Kept 92% coverage from the complete unit-and-integration suite as the + practical reachability benchmark for the integration corpus. - Reason: the earlier audit classified broad utility groups too aggressively; - the existing unit suite proves substantially more production code is reachable. + the existing unit suite proves substantially more production code is + reachable. ### 2026-08-16 — Established default-parse coverage plateau @@ -338,8 +394,8 @@ Record every material plan change here before or with implementation. applicable JavaScript and TypeScript corpus: exports, stable resolver errors, local/imported values and types, PropTypes, contexts, defaults, classes, methods, docblocks, HOCs, imperative handles, and TypeScript type shapes. -- Kept extraction utilities in one-purpose files and added focused tests for - new resolution, type, docblock, class, enum, expression, and method helpers. +- Kept extraction utilities in one-purpose files and added focused tests for new + resolution, type, docblock, class, enum, expression, and method helpers. - Added parser-neutral `createDocgen()` composition to `@react-docgen/core` and compile/runtime-tested custom `Parser`, `Resolver`, `Handler`, and `Importer` contracts without Babel types. From 5e4e0a9d10bbe80012675f81b2ac4c55c017bce3 Mon Sep 17 00:00:00 2001 From: ALF <263217947+askalf@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:39:09 -0400 Subject: [PATCH 09/22] fix: detect useCallback methods in imperative handles (#1139) * fix: detect useCallback methods in imperative handles * test: cover imperative handle callback references * fix: document the function a useCallback method wraps The handler recognised a useCallback-wrapped property as a method, but the documentation was built from the call expression, so the method came out with no parameters and no return type. resolveToMethodFunction now resolves a value to the function it documents, unwrapping a React useCallback call, and both the handler's method test and the documentation builder use it. The tests assert the wrapped function's signature and cover a local function named useCallback, a call with no arguments and a non-function argument. * test: cover every surface that documents a useCallback method The handler's unwrapping now runs for every method node path, so add the surfaces it reaches beyond the imperative handle identifier: a callback written inline in the handle object, an ObjectExpression component, a statics object, a class property and a Component.foo assignment, plus the docblock and the async/generator modifiers of the wrapped function, a renamed useCallback import and a handle that precedes the declaration. The controls pin the guards the unwrapping keeps: a local useCallback, a missing or non-function argument, a spread argument, a nested call and useMemo. * test: pin the zero-parameter, unannotated useCallback method Every positive callback fixture carried a typed parameter and a return annotation, so the empty-signature path the boundary ledger claims was never exercised. Admit useCallback(() => {}, []) through useImperativeHandle and assert an empty params list and a null return. * chore: add changeset for the useCallback method fix * test: run the reported component through the parser The handler tests build a component definition and call the handler directly, so none of them exercise the resolver path the issue reports: a memo(forwardRef) component whose method is exposed as a shorthand property. Parse that component verbatim through the public parse() and assert the documented method, with the same component without useCallback as a control for memo/forwardRef resolution. * fix: keep the useCallback unwrapping on the imperative handle path Documenting the function a useCallback call wraps changed every method surface, including class fields and statics objects where hooks are not valid React usage. Pass the imperative handle down to getMethodDocumentation and unwrap only there; the other surfaces keep documenting plain function values only. The surface tests become controls: they assert that an object, statics and class-property useCallback stays undocumented, next to a plain function on the same surface that still is. * test: drop the out-of-scope assignment case findAssignedMethods only collects assignments whose right-hand side resolves to a function, so Component.foo = useCallback(...) never reaches getMethodDocumentation through the handler. Remove the unit test that implied the assignment surface supported it. * test: pin the lifecycle filter on an unwrapped callback The imperative handle admission keeps the React lifecycle check, so a handle property named after a lifecycle method stays undocumented even when its value is a useCallback call. Control: it passes with and without the unwrapping. --------- Co-authored-by: askalf (cherry picked from commit a73f036e71d3fa8da78196994d80ee073bf32d68) --- .changeset/quiet-hooks-listen.md | 5 + .../imperativeHandleCallbacks-test.ts | 97 +++++ ...omponentMethodsHandler-useCallback-test.ts | 354 ++++++++++++++++++ .../src/handlers/componentMethodsHandler.ts | 29 +- .../src/utils/getMethodDocumentation.ts | 65 +++- 5 files changed, 537 insertions(+), 13 deletions(-) create mode 100644 .changeset/quiet-hooks-listen.md create mode 100644 packages/react-docgen/src/__tests__/imperativeHandleCallbacks-test.ts create mode 100644 packages/react-docgen/src/handlers/__tests__/componentMethodsHandler-useCallback-test.ts diff --git a/.changeset/quiet-hooks-listen.md b/.changeset/quiet-hooks-listen.md new file mode 100644 index 00000000000..c28e0a744ee --- /dev/null +++ b/.changeset/quiet-hooks-listen.md @@ -0,0 +1,5 @@ +--- +'react-docgen': patch +--- + +Document methods declared with `useCallback` and exposed through `useImperativeHandle` diff --git a/packages/react-docgen/src/__tests__/imperativeHandleCallbacks-test.ts b/packages/react-docgen/src/__tests__/imperativeHandleCallbacks-test.ts new file mode 100644 index 00000000000..7985d096b9b --- /dev/null +++ b/packages/react-docgen/src/__tests__/imperativeHandleCallbacks-test.ts @@ -0,0 +1,97 @@ +import { parse } from '../main.js'; +import { describe, expect, test } from 'vitest'; + +function parseSource(source: string) { + return parse(source, { + filename: 'file.tsx', + babelOptions: { babelrc: false }, + }); +} + +const method = { + name: '_myMethod', + params: [{ name: 'argument', optional: false, type: { name: 'string' } }], + returns: { type: { name: 'number' } }, +}; + +describe('useImperativeHandle methods', () => { + // The component reported in + // https://github.com/reactjs/react-docgen/issues/856, verbatim. + test('documents a useCallback method of a memo(forwardRef) component', () => { + const docs = parseSource(` + import React, { + forwardRef, + memo, + useCallback, + useImperativeHandle, + useMemo, + useRef, + } from 'react'; + + export const MyComponent = + memo(forwardRef((_, ref) => { + + const _myMethod = useCallback((argument:string) : number => {}); + + useImperativeHandle( + ref, + () => ({ + /** myMethod description */ + _myMethod, + }), + [], + ); + + return
; + })); + `); + + expect(docs).toHaveLength(1); + expect(docs[0]).toMatchObject({ + methods: [ + { + ...method, + docblock: 'myMethod description', + description: 'myMethod description', + }, + ], + }); + }); + + test('documents a useCallback method of a forwardRef component', () => { + const docs = parseSource(` + import React, { forwardRef, useCallback, useImperativeHandle } from 'react'; + + export const MyComponent = forwardRef((_, ref) => { + const _myMethod = useCallback((argument: string): number => 1, []); + + useImperativeHandle(ref, () => ({ _myMethod }), []); + + return
; + }); + `); + + expect(docs).toHaveLength(1); + expect(docs[0]).toMatchObject({ methods: [method] }); + }); + + test('documents a plain function method of a memo(forwardRef) component (control)', () => { + // Controls for the wrapper resolution itself: the same component without + // useCallback is documented before this change, so the two tests above + // fail on the unwrapping and not on memo/forwardRef. + const docs = parseSource(` + import React, { forwardRef, memo, useImperativeHandle } from 'react'; + + export const MyComponent = memo(forwardRef((_, ref) => { + const _myMethod = (argument: string): number => 1; + + useImperativeHandle(ref, () => ({ _myMethod }), []); + + return
; + })); + `); + + expect(docs).toHaveLength(1); + expect(docs[0]).toMatchObject({ methods: [method] }); + }); +}); diff --git a/packages/react-docgen/src/handlers/__tests__/componentMethodsHandler-useCallback-test.ts b/packages/react-docgen/src/handlers/__tests__/componentMethodsHandler-useCallback-test.ts new file mode 100644 index 00000000000..df518c0fce4 --- /dev/null +++ b/packages/react-docgen/src/handlers/__tests__/componentMethodsHandler-useCallback-test.ts @@ -0,0 +1,354 @@ +import { parse } from '../../../tests/utils'; +import componentMethodsHandler from '../componentMethodsHandler.js'; +import DocumentationBuilder from '../../Documentation'; +import type DocumentationMock from '../../__mocks__/Documentation'; +import type { + ClassDeclaration, + FunctionDeclaration, + ObjectExpression, +} from '@babel/types'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +vi.mock('../../Documentation.js'); + +describe('componentMethodsHandler useImperativeHandle callbacks', () => { + let documentation: DocumentationBuilder & DocumentationMock; + + beforeEach(() => { + documentation = new DocumentationBuilder() as DocumentationBuilder & + DocumentationMock; + }); + + const wrappedSignature = { + name: 'method', + params: [{ name: 'argument', optional: false, type: { name: 'string' } }], + returns: { type: { name: 'number' } }, + }; + + test.each([ + { + name: 'a directly-declared callback', + imports: "import { useCallback, useImperativeHandle } from 'react';", + setup: '', + value: 'useCallback((argument: string): number => 1, [])', + imperativeHandle: 'useImperativeHandle', + }, + { + name: 'a callback identifier', + imports: "import { useCallback, useImperativeHandle } from 'react';", + setup: 'const callback = (argument: string): number => 1;', + value: 'useCallback(callback, [])', + imperativeHandle: 'useImperativeHandle', + }, + { + name: 'a React namespace callback', + imports: "import * as React from 'react';", + setup: '', + value: 'React.useCallback((argument: string): number => 1, [])', + imperativeHandle: 'React.useImperativeHandle', + }, + { + name: 'a renamed useCallback import', + imports: + "import { useCallback as useCb, useImperativeHandle } from 'react';", + setup: '', + value: 'useCb((argument: string): number => 1, [])', + imperativeHandle: 'useImperativeHandle', + }, + ])( + 'extracts a method wrapped with $name', + ({ imports, setup, value, imperativeHandle }) => { + const definition = parse.statementLast(` + ${imports} + function Component() { + ${setup} + const method = ${value}; + ${imperativeHandle}(ref, () => ({ method })); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + // The wrapped function's own signature is what gets documented, not + // the useCallback call around it. + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject(wrappedSignature); + }, + ); + + test('extracts a callback written inline in the handle object', () => { + const definition = parse.statementLast(` + import { useCallback, useImperativeHandle } from 'react'; + function Component() { + useImperativeHandle(ref, () => ({ + method: useCallback((argument: string): number => 1, []), + })); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject(wrappedSignature); + }); + + test('extracts a callback declared after the imperative handle', () => { + const definition = parse.statementLast(` + import { useCallback, useImperativeHandle } from 'react'; + function Component() { + useImperativeHandle(ref, () => ({ method })); + const method = useCallback((argument: string): number => 1, []); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject(wrappedSignature); + }); + + test('carries the docblock of the handle property', () => { + const definition = parse.statementLast(` + import { useCallback, useImperativeHandle } from 'react'; + function Component() { + const method = useCallback((argument: string): number => 1, []); + useImperativeHandle(ref, () => ({ + /** + * The method + */ + method, + })); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject({ + ...wrappedSignature, + docblock: 'The method', + }); + }); + + test.each([ + { + name: 'async', + callback: 'async (argument: string): number => 1', + modifiers: ['async'], + }, + { + name: 'generator', + callback: 'function* (argument: string): number {}', + modifiers: ['generator'], + }, + ])( + 'records the $name modifier of the wrapped function', + ({ callback, modifiers }) => { + const definition = parse.statementLast(` + import { useCallback, useImperativeHandle } from 'react'; + function Component() { + const method = useCallback(${callback}, []); + useImperativeHandle(ref, () => ({ method })); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject({ + name: 'method', + modifiers, + }); + }, + ); + + test('extracts a zero-parameter callback with no return annotation', () => { + const definition = parse.statementLast(` + import { useCallback, useImperativeHandle } from 'react'; + function Component() { + const method = useCallback(() => {}, []); + useImperativeHandle(ref, () => ({ method })); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject({ + name: 'method', + params: [], + returns: null, + }); + }); + + test('documents a plain function exposed through the handle (control)', () => { + // Controls for the imperative handle surface itself: it documented plain + // function values before this change, so the callback cases above fail on + // the unwrapping, not on the handle. + const definition = parse.statementLast(` + import { useImperativeHandle } from 'react'; + function Component() { + const method = (argument: string): number => 1; + useImperativeHandle(ref, () => ({ method })); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject(wrappedSignature); + }); + + test('does not document a lifecycle name exposed as a callback (control)', () => { + // The React lifecycle filter still applies to an unwrapped callback, the + // same way it applies to a plain function property. + const definition = parse.statementLast(` + import { useCallback, useImperativeHandle } from 'react'; + function Component() { + const render = useCallback((argument: string): number => 1, []); + useImperativeHandle(ref, () => ({ render })); + return
; + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(0); + }); + + // Hooks are only valid inside a function component, so the unwrapping stays + // on the imperative handle path: these surfaces document plain functions and + // keep ignoring useCallback calls. + test('does not document a callback method on an ObjectExpression component (control)', () => { + const definition = parse.expressionLast(` + import { useCallback } from 'react'; + ({ + method: useCallback((argument: string): number => 1, []), + }) + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(0); + }); + + test('does not document a callback method in a statics object (control)', () => { + const definition = parse.expressionLast(` + import { useCallback } from 'react'; + ({ + statics: { + method: useCallback((argument: string): number => 1, []), + }, + }) + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(0); + }); + + test('does not document a callback class property (control)', () => { + const definition = parse.statementLast(` + import React, { useCallback } from 'react'; + class Test extends React.Component { + method = useCallback((argument: string): number => 1, []); + render() { return null; } + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(0); + }); + + test('documents a plain function class property (control)', () => { + // Controls for the class-property surface: it still documents plain + // function values, so the callback class property above is undocumented + // because of the scoping and not because the surface stopped working. + const definition = parse.statementLast(` + import React from 'react'; + class Test extends React.Component { + method = (argument: string): number => 1; + render() { return null; } + } + `); + + componentMethodsHandler(documentation, definition); + + expect(documentation.methods).toHaveLength(1); + expect(documentation.methods[0]).toMatchObject(wrappedSignature); + }); + + // Each of these pins one guard the unwrapping must keep: they are already + // undocumented before this change, and must stay undocumented after it. + test.each([ + { + // the call has to resolve to React's useCallback, not any binding of + // that name + name: 'a local function named useCallback (control)', + imports: "import { useImperativeHandle } from 'react';", + setup: + 'function useCallback(fn: unknown, deps: unknown[]) { return fn; }', + value: 'useCallback((argument: string): number => 1, [])', + }, + { + // there has to be a first argument at all + name: 'a useCallback call with no arguments (control)', + imports: "import { useCallback, useImperativeHandle } from 'react';", + setup: '', + value: 'useCallback()', + }, + { + // the first argument has to resolve to a function + name: 'a useCallback call whose first argument is not a function (control)', + imports: "import { useCallback, useImperativeHandle } from 'react';", + setup: '', + value: 'useCallback(42, [])', + }, + { + // a spread element is not the callback, even when it spreads one + name: 'a useCallback call whose argument is spread (control)', + imports: "import { useCallback, useImperativeHandle } from 'react';", + setup: 'const args = [(argument: string): number => 1, []];', + value: 'useCallback(...args)', + }, + { + // the unwrapping is one level deep, not recursive + name: 'a nested useCallback call (control)', + imports: "import { useCallback, useImperativeHandle } from 'react';", + setup: '', + value: + 'useCallback(useCallback((argument: string): number => 1, []), [])', + }, + { + // only useCallback is unwrapped, not every React builtin that returns + // a function + name: 'a useMemo call returning a function (control)', + imports: "import { useMemo, useImperativeHandle } from 'react';", + setup: '', + value: 'useMemo(() => (argument: string): number => 1, [])', + }, + ])('does not document $name', ({ imports, setup, value }) => { + const definition = parse.statementLast(` + ${imports} + function Component() { + ${setup} + const method = ${value}; + useImperativeHandle(ref, () => ({ method })); + return
; + } + `); + + expect(() => + componentMethodsHandler(documentation, definition), + ).not.toThrow(); + expect(documentation.methods).toHaveLength(0); + }); +}); diff --git a/packages/react-docgen/src/handlers/componentMethodsHandler.ts b/packages/react-docgen/src/handlers/componentMethodsHandler.ts index 2bbcd571473..93b9965002f 100644 --- a/packages/react-docgen/src/handlers/componentMethodsHandler.ts +++ b/packages/react-docgen/src/handlers/componentMethodsHandler.ts @@ -1,6 +1,8 @@ import getMemberValuePath from '../utils/getMemberValuePath.js'; import type { MethodNodePath } from '../utils/getMethodDocumentation.js'; -import getMethodDocumentation from '../utils/getMethodDocumentation.js'; +import getMethodDocumentation, { + resolveToUseCallbackFunction, +} from '../utils/getMethodDocumentation.js'; import isReactComponentClass from '../utils/isReactComponentClass.js'; import isReactComponentMethod from '../utils/isReactComponentMethod.js'; import type Documentation from '../Documentation.js'; @@ -48,6 +50,22 @@ function isMethod(path: NodePath): path is MethodNodePath { return isProbablyMethod && !isReactComponentMethod(path); } +/** + * A method exposed through `useImperativeHandle` is also a method when it is + * wrapped in `useCallback`, which is how such methods are usually memoized. + */ +function isImperativeHandleMethod(path: NodePath): path is MethodNodePath { + if (isMethod(path)) { + return true; + } + + return ( + path.isObjectProperty() && + resolveToUseCallbackFunction(path.get('value') as NodePath) !== null && + !isReactComponentMethod(path) + ); +} + interface TraverseState { readonly scope: Scope | undefined; readonly name: string; @@ -79,6 +97,7 @@ const explodedVisitors = visitors.explode({ interface MethodDefinition { path: MethodNodePath; + isImperativeHandle?: boolean; isStatic?: boolean; } @@ -121,7 +140,7 @@ const explodedImperativeHandleVisitors = // We found the object body, now add all of the properties as methods. definition?.get('properties').forEach((p) => { - if (isMethod(p)) { + if (isImperativeHandleMethod(p)) { state.results.push(p); } }); @@ -166,7 +185,7 @@ function findImperativeHandleMethods( body.traverse(explodedImperativeHandleVisitors, state); - return state.results.map((p) => ({ path: p })); + return state.results.map((p) => ({ path: p, isImperativeHandle: true })); } function findAssignedMethods( @@ -267,7 +286,9 @@ const componentMethodsHandler: Handler = function ( documentation.set( 'methods', methodPaths - .map(({ path: p, isStatic }) => getMethodDocumentation(p, { isStatic })) + .map(({ path: p, isImperativeHandle, isStatic }) => + getMethodDocumentation(p, { isImperativeHandle, isStatic }), + ) .filter(Boolean), ); }; diff --git a/packages/react-docgen/src/utils/getMethodDocumentation.ts b/packages/react-docgen/src/utils/getMethodDocumentation.ts index 3dc0162ea53..119dbc3f8ce 100644 --- a/packages/react-docgen/src/utils/getMethodDocumentation.ts +++ b/packages/react-docgen/src/utils/getMethodDocumentation.ts @@ -14,6 +14,7 @@ import getTSType from './getTSType.js'; import getParameterName from './getParameterName.js'; import getPropertyName from './getPropertyName.js'; import getTypeAnnotation from './getTypeAnnotation.js'; +import isReactBuiltinCall from './isReactBuiltinCall.js'; import resolveToValue from './resolveToValue.js'; import printValue from './printValue.js'; import type { @@ -32,8 +33,42 @@ export type MethodNodePath = | NodePath | NodePath; +export interface MethodOptions { + /** + * Set for methods exposed through `useImperativeHandle`, which are allowed + * to be wrapped in `useCallback`. + */ + isImperativeHandle?: boolean; + isStatic?: boolean; +} + +/** + * Returns the function that a React `useCallback` call wraps, or null when + * the path is not such a call or does not wrap a function. + */ +export function resolveToUseCallbackFunction( + path: NodePath, +): NodePath | null { + const value = resolveToValue(path); + + if (value.isCallExpression() && isReactBuiltinCall(value, 'useCallback')) { + const callback = value.get('arguments')[0]; + + if (callback && !Array.isArray(callback)) { + const wrapped = resolveToValue(callback); + + if (wrapped.isFunction()) { + return wrapped; + } + } + } + + return null; +} + function getMethodFunctionExpression( methodPath: MethodNodePath, + options: MethodOptions, ): NodePath | null { if (methodPath.isClassMethod() || methodPath.isObjectMethod()) { return methodPath; @@ -49,6 +84,12 @@ function getMethodFunctionExpression( return functionExpression; } + // An imperative handle method is documented through the function its + // `useCallback` wraps, because that is where its signature is declared. + if (options.isImperativeHandle) { + return resolveToUseCallbackFunction(potentialFunctionExpression); + } + return null; } @@ -68,9 +109,12 @@ function getMethodParamOptional( return identifier.isIdentifier() ? Boolean(identifier.node.optional) : false; } -function getMethodParamsDoc(methodPath: MethodNodePath): MethodParameter[] { +function getMethodParamsDoc( + methodPath: MethodNodePath, + options: MethodOptions, +): MethodParameter[] { const params: MethodParameter[] = []; - const functionExpression = getMethodFunctionExpression(methodPath); + const functionExpression = getMethodFunctionExpression(methodPath, options); if (functionExpression) { // Extract param types. @@ -106,8 +150,11 @@ function getMethodParamsDoc(methodPath: MethodNodePath): MethodParameter[] { } // Extract flow return type. -function getMethodReturnDoc(methodPath: MethodNodePath): MethodReturn | null { - const functionExpression = getMethodFunctionExpression(methodPath); +function getMethodReturnDoc( + methodPath: MethodNodePath, + options: MethodOptions, +): MethodReturn | null { + const functionExpression = getMethodFunctionExpression(methodPath, options); if (functionExpression && functionExpression.node.returnType) { const returnType = getTypeAnnotation(functionExpression.get('returnType')); @@ -128,7 +175,7 @@ function getMethodReturnDoc(methodPath: MethodNodePath): MethodReturn | null { function getMethodModifiers( methodPath: MethodNodePath, - options: { isStatic?: boolean }, + options: MethodOptions, ): MethodModifier[] { if (methodPath.isAssignmentExpression()) { return ['static']; @@ -146,7 +193,7 @@ function getMethodModifiers( modifiers.push('static'); } - const functionExpression = getMethodFunctionExpression(methodPath); + const functionExpression = getMethodFunctionExpression(methodPath, options); if (functionExpression) { if ( @@ -230,7 +277,7 @@ function getMethodDocblock(methodPath: MethodNodePath): string | null { // or as assignment expression of the form `Component.foo = function() {}` export default function getMethodDocumentation( methodPath: MethodNodePath, - options: { isStatic?: boolean } = {}, + options: MethodOptions = {}, ): MethodDescriptor | null { if ( getMethodAccessibility(methodPath) === 'private' || @@ -247,7 +294,7 @@ export default function getMethodDocumentation( name, docblock: getMethodDocblock(methodPath), modifiers: getMethodModifiers(methodPath, options), - params: getMethodParamsDoc(methodPath), - returns: getMethodReturnDoc(methodPath), + params: getMethodParamsDoc(methodPath, options), + returns: getMethodReturnDoc(methodPath, options), }; } From 6227063bd29bd30a9fd3bac72e545e9512a29d6c Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 11:55:26 +0100 Subject: [PATCH 10/22] fix: port imperative handle callbacks to parser-neutral extraction Carry #1139 into the shared method handler and portable fixture corpus. Resolve local callback bindings and React import aliases while keeping useCallback unwrapping limited to imperative handles. Co-authored-by: ALF <263217947+askalf@users.noreply.github.com> --- .changeset/neutral-imperative-callbacks.md | 10 + .../findImperativeHandleMethods-test.ts | 124 +++++++++ packages/core/src/handlers/methodHandler.ts | 181 +++++++------ .../src/utils/findImperativeHandleMethods.ts | 244 ++++++++++++++++-- .../imperative-handle-callbacks/index.js | 10 + .../imperative-handle-callbacks/output.json | 28 ++ .../index.jsx | 48 ++++ .../output.json | 15 ++ .../imperative-handle-callbacks/index.jsx | 31 +++ .../imperative-handle-callbacks/output.json | 48 ++++ .../imperative-handle-callbacks/index.tsx | 18 ++ .../imperative-handle-callbacks/output.json | 28 ++ .../findImperativeHandleMethods-test.ts | 3 +- .../tests/integration/integration-test.ts | 3 + 14 files changed, 690 insertions(+), 101 deletions(-) create mode 100644 .changeset/neutral-imperative-callbacks.md create mode 100644 packages/core/src/__tests__/findImperativeHandleMethods-test.ts create mode 100644 packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/index.js create mode 100644 packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/output.json create mode 100644 packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/index.jsx create mode 100644 packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/output.json create mode 100644 packages/integration-tests/cases/js/methods/imperative-handle-callbacks/index.jsx create mode 100644 packages/integration-tests/cases/js/methods/imperative-handle-callbacks/output.json create mode 100644 packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/index.tsx create mode 100644 packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/output.json diff --git a/.changeset/neutral-imperative-callbacks.md b/.changeset/neutral-imperative-callbacks.md new file mode 100644 index 00000000000..b2dcbe8bac2 --- /dev/null +++ b/.changeset/neutral-imperative-callbacks.md @@ -0,0 +1,10 @@ +--- +'@react-docgen/core': patch +--- + +Document methods wrapped in React `useCallback` and exposed through +`useImperativeHandle`, preserving their parameters, return types, descriptions, +and async/generator modifiers across parser adapters. + +Ported from [#1139](https://github.com/reactjs/react-docgen/pull/1139) by +[@askalf](https://github.com/askalf). diff --git a/packages/core/src/__tests__/findImperativeHandleMethods-test.ts b/packages/core/src/__tests__/findImperativeHandleMethods-test.ts new file mode 100644 index 00000000000..8c0c9d337d5 --- /dev/null +++ b/packages/core/src/__tests__/findImperativeHandleMethods-test.ts @@ -0,0 +1,124 @@ +import { expect, test } from 'vitest'; +import { ProjectContext, type AstNode } from '../index.js'; +import findImperativeHandleMethods from '../utils/findImperativeHandleMethods.js'; + +const id = (name: string): AstNode => ({ type: 'Identifier', name }); +const fn = (): AstNode => ({ + type: 'ArrowFunctionExpression', + params: [], + body: { type: 'BlockStatement', body: [] }, +}); +const variable = (name: string, init: AstNode): AstNode => ({ + type: 'VariableDeclaration', + declarations: [{ type: 'VariableDeclarator', id: id(name), init }], +}); +const call = (name: string, args: AstNode[]): AstNode => ({ + type: 'CallExpression', + callee: id(name), + arguments: args, +}); + +function findMethods({ + declarations = [], + params = [], + source = 'react', + value = call('useCb', [fn()]), +}: { + declarations?: AstNode[]; + params?: AstNode[]; + source?: string; + value?: AstNode; +} = {}) { + const property = { type: 'Property', key: id('focus'), value: id('method') }; + const ast: AstNode = { + type: 'Program', + body: [ + { + type: 'ImportDeclaration', + source: { type: 'Literal', value: source }, + specifiers: ['useCallback', 'useImperativeHandle'].map( + (name, index) => ({ + type: 'ImportSpecifier', + imported: id(name), + local: id(index === 0 ? 'useCb' : name), + }), + ), + }, + { + type: 'FunctionDeclaration', + id: id('Input'), + params, + body: { + type: 'BlockStatement', + body: [ + ...declarations, + variable('method', value), + { + type: 'ExpressionStatement', + expression: call('useImperativeHandle', [ + id('ref'), + { + type: 'ArrowFunctionExpression', + params: [], + body: { type: 'ObjectExpression', properties: [property] }, + }, + ]), + }, + ], + }, + }, + ], + }; + const project = new ProjectContext({ + importer() { + throw new Error('Unexpected import'); + }, + selectParser: () => ({ + parse: () => ast, + visitorKeys: { + BlockStatement: ['body'], + ExpressionStatement: ['expression'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + }, + }), + }); + const file = project.parse({ code: '', filename: 'input.js' }); + const body = file.path.get('body'); + const component = Array.isArray(body) ? body[1] : null; + + if (!component) throw new Error('Missing component'); + + return findImperativeHandleMethods(file, component); +} + +test('resolves React aliases and component-local callback identifiers', () => { + const callback = fn(); + const methods = findMethods({ + declarations: [variable('callback', callback)], + value: call('useCb', [id('callback')]), + }); + + expect(methods).toHaveLength(1); + expect(methods[0]?.fn).toBe(callback); +}); + +test('does not mistake a component parameter for an imported React hook', () => { + expect(findMethods({ params: [id('useCb')] })).toEqual([]); +}); + +test('does not unwrap hooks imported from another package', () => { + expect(findMethods({ source: 'other-library' })).toEqual([]); +}); + +test('stops resolving circular callback aliases', () => { + expect( + findMethods({ + declarations: [ + variable('first', id('second')), + variable('second', id('first')), + ], + value: call('useCb', [id('first')]), + }), + ).toEqual([]); +}); diff --git a/packages/core/src/handlers/methodHandler.ts b/packages/core/src/handlers/methodHandler.ts index 56ad1498852..dba59dc624e 100644 --- a/packages/core/src/handlers/methodHandler.ts +++ b/packages/core/src/handlers/methodHandler.ts @@ -17,10 +17,33 @@ import getPropertyName from '../utils/getPropertyName.js'; import parseMethodDocblock from '../utils/parseMethodDocblock.js'; import findImperativeHandleMethods from '../utils/findImperativeHandleMethods.js'; +const reactMethods = new Set([ + 'componentDidMount', + 'componentDidReceiveProps', + 'componentDidUpdate', + 'componentWillMount', + 'UNSAFE_componentWillMount', + 'componentWillReceiveProps', + 'UNSAFE_componentWillReceiveProps', + 'componentWillUnmount', + 'componentWillUpdate', + 'UNSAFE_componentWillUpdate', + 'getChildContext', + 'getDefaultProps', + 'getInitialState', + 'render', + 'shouldComponentUpdate', + 'getDerivedStateFromProps', + 'getDerivedStateFromError', + 'getSnapshotBeforeUpdate', + 'componentDidCatch', +]); + function addImperativeMethods( documentation: Parameters[0], path: Parameters[1], file: Parameters[2], + getType?: TypeResolver, ): void { if ( !isFunctionDeclaration(path.node) && @@ -28,20 +51,17 @@ function addImperativeMethods( !isArrowFunctionExpression(path.node) ) return; - for (const property of findImperativeHandleMethods(path.node)) { + for (const { property, fn } of findImperativeHandleMethods(file, path)) { const name = getPropertyName(property.key); - if (!name) continue; - const description = getDescription(file, property); + if (!name || reactMethods.has(name)) continue; + const modifiers: string[] = []; - documentation.methods.push({ - name, - docblock: description || null, - modifiers: [], - params: [], - returns: null, - ...(description ? { description } : {}), - }); + if (fn.generator) modifiers.push('generator'); + if (fn.async) modifiers.push('async'); + documentation.methods.push( + methodDocumentation(file, property, fn, name, modifiers, getType), + ); } } @@ -50,9 +70,81 @@ export type TypeResolver = ( annotation: AstNode, ) => TypeDescriptor | null; +function methodDocumentation( + file: FileState, + member: AstNode, + fn: AstNode, + name: string, + modifiers: string[], + getType?: TypeResolver, +) { + const params = Array.isArray(fn.params) ? (fn.params as AstNode[]) : []; + const returnType = + fn.returnType && + typeof fn.returnType === 'object' && + 'type' in fn.returnType + ? (fn.returnType as AstNode) + : null; + const description = getDescription(file, member); + const parsedDocblock = parseMethodDocblock(description); + + return { + name, + docblock: description || null, + modifiers, + params: params.map((parameter) => { + const annotation = + parameter.typeAnnotation && + typeof parameter.typeAnnotation === 'object' && + 'type' in parameter.typeAnnotation + ? (parameter.typeAnnotation as AstNode) + : null; + const rawName = Array.isArray(parameter.range) + ? file.source.code + .slice(parameter.range[0], parameter.range[1]) + .replace(/\??:\s*[\s\S]*$/, '') + : isIdentifier(parameter) + ? parameter.name + : ''; + const normalizedName = rawName + .replace(/^\.\.\./, '') + .replace(/\s*=.*$/, ''); + const documented = + parameter.type === 'Identifier' || + parameter.type === 'AssignmentPattern' + ? parsedDocblock.params.get(normalizedName) + : undefined; + const type = + documented?.type ?? + (annotation && getType ? getType(file, annotation) : null); + + return { + name: rawName.replace(/\s*=.*$/, ''), + optional: Boolean( + documented?.optional || + parameter.optional || + parameter.type === 'AssignmentPattern', + ), + ...(!description || documented || parameter.type === 'Identifier' + ? { type } + : {}), + ...(documented?.description + ? { description: documented.description } + : {}), + }; + }), + returns: + parsedDocblock.returns ?? + (returnType && getType ? { type: getType(file, returnType) } : null), + ...(parsedDocblock.description + ? { description: parsedDocblock.description } + : {}), + }; +} + export default function createMethodHandler(getType?: TypeResolver): Handler { return (documentation, path, file) => { - addImperativeMethods(documentation, path, file); + addImperativeMethods(documentation, path, file, getType); if (!isClassDeclaration(path.node) && !isClassExpression(path.node)) return; for (const member of path.node.body.body) { @@ -92,68 +184,9 @@ export default function createMethodHandler(getType?: TypeResolver): Handler { ) continue; - const params = Array.isArray(fn.params) ? (fn.params as AstNode[]) : []; - const returnType = - fn.returnType && - typeof fn.returnType === 'object' && - 'type' in fn.returnType - ? (fn.returnType as AstNode) - : null; - const description = getDescription(file, member); - const parsedDocblock = parseMethodDocblock(description); - - documentation.methods.push({ - name, - docblock: description || null, - modifiers, - params: params.map((parameter) => { - const annotation = - parameter.typeAnnotation && - typeof parameter.typeAnnotation === 'object' && - 'type' in parameter.typeAnnotation - ? (parameter.typeAnnotation as AstNode) - : null; - const rawName = Array.isArray(parameter.range) - ? file.source.code - .slice(parameter.range[0], parameter.range[1]) - .replace(/\??:\s*[\s\S]*$/, '') - : isIdentifier(parameter) - ? parameter.name - : ''; - const normalizedName = rawName - .replace(/^\.\.\./, '') - .replace(/\s*=.*$/, ''); - const documented = - parameter.type === 'Identifier' || - parameter.type === 'AssignmentPattern' - ? parsedDocblock.params.get(normalizedName) - : undefined; - const type = - documented?.type ?? - (annotation && getType ? getType(file, annotation) : null); - - return { - name: rawName.replace(/\s*=.*$/, ''), - optional: Boolean( - documented?.optional || - parameter.optional || - parameter.type === 'AssignmentPattern', - ), - ...(!description || documented || parameter.type === 'Identifier' - ? { type } - : {}), - ...(documented?.description - ? { description: documented.description } - : {}), - }; - }), - returns: - parsedDocblock.returns ?? - (returnType && getType ? { type: getType(file, returnType) } : null), - ...(parsedDocblock.description - ? { description: parsedDocblock.description } - : {}), - }); + documentation.methods.push( + methodDocumentation(file, member, fn, name, modifiers, getType), + ); } }; } diff --git a/packages/core/src/utils/findImperativeHandleMethods.ts b/packages/core/src/utils/findImperativeHandleMethods.ts index 60f15d4c98d..bf5fbe99637 100644 --- a/packages/core/src/utils/findImperativeHandleMethods.ts +++ b/packages/core/src/utils/findImperativeHandleMethods.ts @@ -1,46 +1,238 @@ import { isArrowFunctionExpression, isCallExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isMemberExpression, isObjectExpression, isProperty, type AstNode, + type AstPath, + type FileState, type Property, } from '../internal.js'; -import getMemberName from './getMemberName.js'; -export default function findImperativeHandleMethods(node: AstNode): Property[] { - const methods: Property[] = []; +function child(path: AstPath, key: string): AstPath | null { + const value = path.get(key); - function visit(current: AstNode): void { - if ( - isCallExpression(current) && - getMemberName(current.callee)?.split('.').at(-1) === 'useImperativeHandle' - ) { - const factory = current.arguments[1]; - - if ( - factory && - isArrowFunctionExpression(factory) && - isObjectExpression(factory.body) - ) { - methods.push(...factory.body.properties.filter(isProperty)); - } + return Array.isArray(value) ? null : value; +} + +function children(path: AstPath, key: string): AstPath[] { + const value = path.get(key); + + return Array.isArray(value) ? value : []; +} + +function isFunction(node: AstNode): boolean { + return ( + isArrowFunctionExpression(node) || + isFunctionExpression(node) || + isFunctionDeclaration(node) + ); +} + +function binds(path: AstPath, name: string): boolean { + if (isIdentifier(path.node)) return path.node.name === name; + if (path.node.type === 'AssignmentPattern') { + const left = child(path, 'left'); + + return Boolean(left && binds(left, name)); + } + if (path.node.type === 'RestElement') { + const argument = child(path, 'argument'); + + return Boolean(argument && binds(argument, name)); + } + if (path.node.type === 'ObjectPattern') { + return children(path, 'properties').some((property) => { + const value = child(property, 'value') ?? child(property, 'argument'); + + return Boolean(value && binds(value, name)); + }); + } + + return children(path, 'elements').some((element) => binds(element, name)); +} + +function binding(path: AstPath, name: string): AstPath | null { + for (let scope = path.parentPath; scope; scope = scope.parentPath) { + if (isFunction(scope.node)) { + const id = child(scope, 'id'); + + if (id && binds(id, name)) return scope; + const parameter = children(scope, 'params').find((param) => + binds(param, name), + ); + + if (parameter) return parameter; + } + if (scope.node.type === 'CatchClause') { + const parameter = child(scope, 'param'); + + if (parameter && binds(parameter, name)) return parameter; } + if (scope.node.type !== 'Program' && scope.node.type !== 'BlockStatement') + continue; + + for (const statement of children(scope, 'body')) { + const declaration = child(statement, 'declaration') ?? statement; + const id = child(declaration, 'id'); - for (const value of Object.values(current)) { - if (Array.isArray(value)) { - for (const child of value) { - if (child && typeof child === 'object' && 'type' in child) { - visit(child as AstNode); - } + if (id && binds(id, name)) return declaration; + for (const variable of children(declaration, 'declarations')) { + const variableId = child(variable, 'id'); + + if (variableId && binds(variableId, name)) { + return isIdentifier(variableId.node) + ? (child(variable, 'init') ?? variableId) + : variableId; } - } else if (value && typeof value === 'object' && 'type' in value) { - visit(value as AstNode); + } + for (const specifier of children(declaration, 'specifiers')) { + const local = child(specifier, 'local'); + + if (local && binds(local, name)) return specifier; } } } - visit(node); + return null; +} + +function resolve(path: AstPath, seen = new Set()): AstPath { + if (!isIdentifier(path.node) || seen.has(path.node)) return path; + seen.add(path.node); + const value = binding(path, path.node.name); + + return value ? resolve(value, seen) : path; +} + +function isReactImport(path: AstPath): boolean { + const source = path.parentPath && child(path.parentPath, 'source'); + + return Boolean( + source && + isLiteral(source.node) && + ['react', 'react/addons', 'react-native'].includes( + String(source.node.value), + ), + ); +} + +function isReactHook(path: AstPath, name: string): boolean { + const value = resolve(path); + + if (isMemberExpression(value.node) && !value.node.computed) { + if (!isIdentifier(value.node.property, { name })) return false; + const object = child(value, 'object'); + + if (!object) return false; + const imported = resolve(object); + + return ( + ['ImportDefaultSpecifier', 'ImportNamespaceSpecifier'].includes( + imported.node.type, + ) && isReactImport(imported) + ); + } + const imported = child(value, 'imported'); + + return Boolean( + value.node.type === 'ImportSpecifier' && + imported && + isIdentifier(imported.node, { name }) && + isReactImport(value), + ); +} + +export interface ImperativeHandleMethod { + property: Property; + fn: AstNode; +} + +export default function findImperativeHandleMethods( + file: FileState, + component: AstPath, +): ImperativeHandleMethod[] { + const methods: ImperativeHandleMethod[] = []; + + function visit(path: AstPath, visitor: (path: AstPath) => boolean): void { + if ( + visitor(path) || + isFunction(path.node) || + path.node.type === 'ClassDeclaration' || + path.node.type === 'ClassExpression' + ) + return; + for (const key of file.visitorKeys[path.node.type] ?? []) { + const value = path.get(key); + + for (const nested of Array.isArray(value) + ? value + : value + ? [value] + : []) { + visit(nested, visitor); + } + } + } + + const body = child(component, 'body'); + + if (!body) return methods; + visit(body, (path) => { + if (!isCallExpression(path.node)) return false; + const callee = child(path, 'callee'); + const factory = children(path, 'arguments')[1]; + + if ( + !callee || + !isReactHook(callee, 'useImperativeHandle') || + !factory || + !isFunction(factory.node) + ) + return true; + const factoryBody = child(factory, 'body'); + + if (!factoryBody) return true; + let object = resolve(factoryBody); + + if (!isObjectExpression(object.node)) { + visit(factoryBody, (returned) => { + if (returned.node.type !== 'ReturnStatement') return false; + const argument = child(returned, 'argument'); + + if (argument && isObjectExpression(resolve(argument).node)) + object = resolve(argument); + + return true; + }); + } + if (!isObjectExpression(object.node)) return true; + + for (const property of children(object, 'properties')) { + if (!isProperty(property.node)) continue; + const value = child(property, 'value'); + + if (!value) continue; + let fn = resolve(value); + + if (isCallExpression(fn.node)) { + const hook = child(fn, 'callee'); + const callback = children(fn, 'arguments')[0]; + + if (!hook || !isReactHook(hook, 'useCallback') || !callback) continue; + fn = resolve(callback); + } + if (isFunction(fn.node)) + methods.push({ property: property.node, fn: fn.node }); + } + + return true; + }); return methods; } diff --git a/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/index.js b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/index.js new file mode 100644 index 00000000000..b84833215be --- /dev/null +++ b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/index.js @@ -0,0 +1,10 @@ +import * as React from 'react'; + +export const Input = React.forwardRef((_, ref) => { + const focus = React.useCallback((value: string): number => 1, []); + React.useImperativeHandle(ref, () => ({ + /** Focus the input. */ + focus, + })); + return ; +}); diff --git a/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/output.json b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/output.json new file mode 100644 index 00000000000..3c179d48ab4 --- /dev/null +++ b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/output.json @@ -0,0 +1,28 @@ +[ + { + "description": "", + "displayName": "Input", + "methods": [ + { + "name": "focus", + "docblock": "Focus the input.", + "modifiers": [], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "number" + } + }, + "description": "Focus the input." + } + ] + } +] diff --git a/packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/index.jsx b/packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/index.jsx new file mode 100644 index 00000000000..f57481e1de1 --- /dev/null +++ b/packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/index.jsx @@ -0,0 +1,48 @@ +import { useCallback, useImperativeHandle, useMemo } from 'react'; + +export function Input(props) { + const missing = useCallback(); + const number = useCallback(42, []); + const args = [() => {}, []]; + const spread = useCallback(...args); + const nested = useCallback( + useCallback(() => {}, []), + [], + ); + const memoized = useMemo(() => () => {}, []); + const render = useCallback(() => {}, []); + + { + const useCallback = (fn) => fn; + const local = useCallback(() => {}, []); + useImperativeHandle(props.ref, () => ({ local })); + } + + try { + } catch (useCallback) { + const caught = useCallback(() => {}, []); + useImperativeHandle(props.ref, () => ({ caught })); + } + + { + const useImperativeHandle = (ref, factory) => factory(); + useImperativeHandle(props.ref, () => ({ unrelated() {} })); + } + + function nestedComponent() { + const hidden = useCallback(() => {}, []); + useImperativeHandle(props.ref, () => ({ hidden })); + } + + useImperativeHandle(props.ref, () => ({ + missing, + number, + spread, + nested, + memoized, + render, + notAMethod: 42, + plain() {}, + })); + return ; +} diff --git a/packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/output.json b/packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/output.json new file mode 100644 index 00000000000..f42c5fb0db4 --- /dev/null +++ b/packages/integration-tests/cases/js/methods/imperative-handle-callback-guards/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "displayName": "Input", + "methods": [ + { + "name": "plain", + "docblock": null, + "modifiers": [], + "params": [], + "returns": null + } + ] + } +] diff --git a/packages/integration-tests/cases/js/methods/imperative-handle-callbacks/index.jsx b/packages/integration-tests/cases/js/methods/imperative-handle-callbacks/index.jsx new file mode 100644 index 00000000000..6334db97341 --- /dev/null +++ b/packages/integration-tests/cases/js/methods/imperative-handle-callbacks/index.jsx @@ -0,0 +1,31 @@ +import React, { + memo, + forwardRef, + useCallback as useCb, + useImperativeHandle as useHandle, +} from 'react'; + +export const Input = memo( + forwardRef(function Input(_props, ref) { + const callback = (value = 'default') => value; + const focus = useCb(callback, []); + const reset = React.useCallback(() => {}, []); + const save = useCb(async (value) => value, []); + const values = useCb(function* () { + yield 1; + }, []); + + useHandle(ref, () => { + const handle = { + /** Focus the input. */ + focus, + reset, + save, + values, + }; + return handle; + }); + + return ; + }), +); diff --git a/packages/integration-tests/cases/js/methods/imperative-handle-callbacks/output.json b/packages/integration-tests/cases/js/methods/imperative-handle-callbacks/output.json new file mode 100644 index 00000000000..97e695314ec --- /dev/null +++ b/packages/integration-tests/cases/js/methods/imperative-handle-callbacks/output.json @@ -0,0 +1,48 @@ +[ + { + "description": "", + "displayName": "Input", + "methods": [ + { + "name": "focus", + "docblock": "Focus the input.", + "modifiers": [], + "params": [ + { + "name": "value", + "optional": true + } + ], + "returns": null, + "description": "Focus the input." + }, + { + "name": "reset", + "docblock": null, + "modifiers": [], + "params": [], + "returns": null + }, + { + "name": "save", + "docblock": null, + "modifiers": ["async"], + "params": [ + { + "name": "value", + "optional": false, + "type": null + } + ], + "returns": null + }, + { + "name": "values", + "docblock": null, + "modifiers": ["generator"], + "params": [], + "returns": null + } + ] + } +] diff --git a/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/index.tsx b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/index.tsx new file mode 100644 index 00000000000..688a420bd34 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/index.tsx @@ -0,0 +1,18 @@ +import { memo, forwardRef, useCallback, useImperativeHandle } from 'react'; + +export const MyComponent = memo( + forwardRef((_, ref) => { + const _myMethod = useCallback((argument: string): number => 1, []); + + useImperativeHandle( + ref, + () => ({ + /** myMethod description */ + _myMethod, + }), + [], + ); + + return
; + }), +); diff --git a/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/output.json b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/output.json new file mode 100644 index 00000000000..c4ad8df17ed --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/output.json @@ -0,0 +1,28 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [ + { + "name": "_myMethod", + "docblock": "myMethod description", + "modifiers": [], + "params": [ + { + "name": "argument", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "number" + } + }, + "description": "myMethod description" + } + ] + } +] diff --git a/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts b/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts index 6abb60a4d07..201c8e2521a 100644 --- a/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts +++ b/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts @@ -7,6 +7,7 @@ import parseFile from '../../__tests__/testUtils.js'; test('finds methods exposed through useImperativeHandle', () => { const file = parseFile(` + import { forwardRef, useImperativeHandle } from 'react'; export const Input = forwardRef(function Input(props, ref) { useImperativeHandle(ref, () => ({ focus() {}, reset() {} })); }); @@ -15,6 +16,6 @@ test('finds methods exposed through useImperativeHandle', () => { expect(definition?.node.type).toBe('FunctionExpression'); expect( - definition && findImperativeHandleMethods(definition.node), + definition && findImperativeHandleMethods(file, definition), ).toHaveLength(2); }); diff --git a/packages/typescript/tests/integration/integration-test.ts b/packages/typescript/tests/integration/integration-test.ts index bb8d5a8d87a..3c1b8b4be23 100644 --- a/packages/typescript/tests/integration/integration-test.ts +++ b/packages/typescript/tests/integration/integration-test.ts @@ -41,6 +41,8 @@ const supportedCases = [ 'js/methods/jsdoc-variants', 'js/methods/parameter-shapes', 'js/methods/imperative-handle', + 'js/methods/imperative-handle-callbacks', + 'js/methods/imperative-handle-callback-guards', 'js/regressions/class-static-getters', 'js/imports/export-star-chain', 'js/imports/imported-defaults-and-enums', @@ -62,6 +64,7 @@ const supportedCases = [ 'typescript/types/generic-interface-extension', 'typescript/methods/class-methods', 'typescript/methods/modifiers-and-types', + 'typescript/methods/imperative-handle-callbacks', 'typescript/regressions/circular-interface-inheritance', 'typescript/regressions/circular-type-aliases', 'typescript/regressions/polymorphic-forward-ref', From 4cca9e26c869f02213b26f23d6fdd6011fb1734d Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 11:57:34 +0100 Subject: [PATCH 11/22] test: discover all JavaScript and TypeScript fixtures --- .../tests/integration/integration-test.ts | 76 ++----------------- 1 file changed, 6 insertions(+), 70 deletions(-) diff --git a/packages/typescript/tests/integration/integration-test.ts b/packages/typescript/tests/integration/integration-test.ts index 3c1b8b4be23..87141a04855 100644 --- a/packages/typescript/tests/integration/integration-test.ts +++ b/packages/typescript/tests/integration/integration-test.ts @@ -4,79 +4,15 @@ import path from 'node:path'; import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; import { parse } from '../../src/index.js'; -const supportedCases = [ - 'js/definitions/function-declaration', - 'js/definitions/annotated-function', - 'js/definitions/custom-base-class-render', - 'js/definitions/configured-nested-hoc', - 'js/definitions/hoc-wrapped-component', - 'js/definitions/class-expression-static-assignments', - 'js/definitions/assigned-class-invalid-display-name', - 'js/definitions/numeric-display-name', - 'js/definitions/display-name-resolution', - 'js/definitions/react-create-class-assignment', - 'js/definitions/react-create-class-variable', - 'js/exports/commonjs-named', - 'js/exports/commonjs-module', - 'js/exports/computed-commonjs', - 'js/errors/missing-definition', - 'js/errors/multiple-definitions', - 'js/defaults/memo-forward-ref', - 'js/defaults/destructured-bindings', - 'js/defaults/function-default-props', - 'js/defaults/value-serialization', - 'js/defaults/computed-property', - 'js/defaults/spreads-and-parameters', - 'js/defaults/unresolved-enum', - 'js/props/all-proptypes', - 'js/props/package-proptypes-context', - 'js/props/react-proptypes-context', - 'js/props/shape-exact-and-union', - 'js/props/composed-and-custom-validators', - 'js/props/literal-computed-keys', - 'js/props/nested-shape-inheritance', - 'js/props/object-key-and-value-enums', - 'js/methods/class-methods', - 'js/methods/class-method-documentation', - 'js/methods/jsdoc-variants', - 'js/methods/parameter-shapes', - 'js/methods/imperative-handle', - 'js/methods/imperative-handle-callbacks', - 'js/methods/imperative-handle-callback-guards', - 'js/regressions/class-static-getters', - 'js/imports/export-star-chain', - 'js/imports/imported-defaults-and-enums', - 'js/imports/member-proptypes', - 'js/imports/namespace-reexport', - 'js/imports/reexported-proptypes', - 'js/imports/spread-proptypes', - 'typescript/defaults/function-default-parameters', - 'typescript/defaults/forward-ref-parameter-default', - 'typescript/definitions/anonymous-default-class', - 'typescript/exports/namespace-reexport', - 'typescript/types/comprehensive-props', - 'typescript/types/nested-object-and-union', - 'typescript/types/type-alias-intersection', - 'typescript/types/interface-composition', - 'typescript/types/react-prop-wrappers', - 'typescript/types/advanced-props', - 'typescript/types/indexed-access-constant', - 'typescript/types/generic-interface-extension', - 'typescript/methods/class-methods', - 'typescript/methods/modifiers-and-types', - 'typescript/methods/imperative-handle-callbacks', - 'typescript/regressions/circular-interface-inheritance', - 'typescript/regressions/circular-type-aliases', - 'typescript/regressions/polymorphic-forward-ref', - 'typescript/imports/extended-props', - 'typescript/imports/imported-props', -]; - describe('integration', () => { for (const integrationCase of loadIntegrationCases({ - ids: supportedCases, + languages: ['js', 'typescript'], })) { - test(integrationCase.id, () => { + // Its support file uses Babel-only `export defaultFrom` syntax (PLAN.md). + const babelOnly = + integrationCase.id === 'typescript/imports/reexported-default-values'; + + test.skipIf(babelOnly)(integrationCase.id, () => { const run = () => parse(integrationCase.source, { filename: integrationCase.filename, From 97bcba327641ef6b83be1ac3a48f7eb2e122841b Mon Sep 17 00:00:00 2001 From: sean0407 Date: Sat, 31 Oct 2026 19:12:38 +0800 Subject: [PATCH 12/22] fix: parse parenthesized TypeScript function types (#1142) * fix: parse parenthesized TypeScript function types * style: remove blank line between test imports --------- Co-authored-by: sean0407 <22557931+sean0407@users.noreply.github.com> Co-authored-by: Daniel Tschinder (cherry picked from commit 065e7c14ab8131f06b57ce70dea40b958dc925c6) --- .changeset/calm-types-travel.md | 5 +++ packages/react-docgen/src/utils/getTSType.ts | 9 ++++++ .../parenthesized-function-type-test.ts | 31 +++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 .changeset/calm-types-travel.md create mode 100644 packages/react-docgen/tests/integration/parenthesized-function-type-test.ts diff --git a/.changeset/calm-types-travel.md b/.changeset/calm-types-travel.md new file mode 100644 index 00000000000..44b74e46d7b --- /dev/null +++ b/.changeset/calm-types-travel.md @@ -0,0 +1,5 @@ +--- +'react-docgen': patch +--- + +Preserve function types wrapped in parentheses when parsing TypeScript unions. diff --git a/packages/react-docgen/src/utils/getTSType.ts b/packages/react-docgen/src/utils/getTSType.ts index 91346f11915..74c30ec2da1 100644 --- a/packages/react-docgen/src/utils/getTSType.ts +++ b/packages/react-docgen/src/utils/getTSType.ts @@ -33,6 +33,7 @@ import type { TSTypeOperator, Identifier, TSTypeParameterDeclaration, + TSParenthesizedType, TypeScript, TSQualifiedName, TSLiteralType, @@ -68,6 +69,7 @@ const namedTypes: Record< TSInterfaceDeclaration: handleTSInterfaceDeclaration, TSUnionType: handleTSUnionType, TSFunctionType: handleTSFunctionType, + TSParenthesizedType: handleTSParenthesizedType, TSIntersectionType: handleTSIntersectionType, TSMappedType: handleTSMappedType, TSTupleType: handleTSTupleType, @@ -373,6 +375,13 @@ function handleTSFunctionType( return type; } +function handleTSParenthesizedType( + path: NodePath, + typeParams: TypeParameters | null, +): TypeDescriptor { + return getTSTypeWithResolvedTypes(path.get('typeAnnotation'), typeParams); +} + function handleTSTupleType( path: NodePath, typeParams: TypeParameters | null, diff --git a/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts b/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts new file mode 100644 index 00000000000..6e337ef54ec --- /dev/null +++ b/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts @@ -0,0 +1,31 @@ +import { describe, expect, test } from 'vitest'; +import { parse } from '../../src/main'; + +describe('TypeScript parenthesized function types', () => { + test('preserves a function type inside a union', () => { + const [component] = parse( + ` + interface Props { + name: (() => string) | undefined; + } + + export const MyComponent = ({ name }: Props) =>
; + `, + { + babelOptions: { filename: 'component.tsx' }, + }, + ); + + expect(component.props?.name?.tsType).toMatchObject({ + name: 'union', + elements: [ + { + name: 'signature', + type: 'function', + signature: { arguments: [], return: { name: 'string' } }, + }, + { name: 'undefined' }, + ], + }); + }); +}); From e3758b87b0368476b934a264875e6508bd3e7d92 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 12:23:52 +0100 Subject: [PATCH 13/22] test: share parenthesized function type regression across parsers Move the #1142 regression into the portable fixture corpus so legacy and TypeScript extraction both verify the complete documentation output. Co-authored-by: sean0407 <22557931+sean0407@users.noreply.github.com> --- .changeset/calm-types-travel.md | 3 ++ .../parenthesized-function-union/index.tsx | 5 +++ .../parenthesized-function-union/output.json | 33 +++++++++++++++++++ .../parenthesized-function-type-test.ts | 31 ----------------- 4 files changed, 41 insertions(+), 31 deletions(-) create mode 100644 packages/integration-tests/cases/typescript/types/parenthesized-function-union/index.tsx create mode 100644 packages/integration-tests/cases/typescript/types/parenthesized-function-union/output.json delete mode 100644 packages/react-docgen/tests/integration/parenthesized-function-type-test.ts diff --git a/.changeset/calm-types-travel.md b/.changeset/calm-types-travel.md index 44b74e46d7b..f27e1f81d8f 100644 --- a/.changeset/calm-types-travel.md +++ b/.changeset/calm-types-travel.md @@ -3,3 +3,6 @@ --- Preserve function types wrapped in parentheses when parsing TypeScript unions. + +Thanks [@sean0407](https://github.com/sean0407) for +[#1142](https://github.com/reactjs/react-docgen/pull/1142). diff --git a/packages/integration-tests/cases/typescript/types/parenthesized-function-union/index.tsx b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/index.tsx new file mode 100644 index 00000000000..83059f49adf --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/index.tsx @@ -0,0 +1,5 @@ +interface Props { + name: (() => string) | undefined; +} + +export const MyComponent = ({ name }: Props) =>
; diff --git a/packages/integration-tests/cases/typescript/types/parenthesized-function-union/output.json b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/output.json new file mode 100644 index 00000000000..9d4b416a18c --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/output.json @@ -0,0 +1,33 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "name": { + "required": true, + "tsType": { + "name": "union", + "raw": "(() => string) | undefined", + "elements": [ + { + "name": "signature", + "type": "function", + "raw": "() => string", + "signature": { + "arguments": [], + "return": { + "name": "string" + } + } + }, + { + "name": "undefined" + } + ] + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts b/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts deleted file mode 100644 index 6e337ef54ec..00000000000 --- a/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { parse } from '../../src/main'; - -describe('TypeScript parenthesized function types', () => { - test('preserves a function type inside a union', () => { - const [component] = parse( - ` - interface Props { - name: (() => string) | undefined; - } - - export const MyComponent = ({ name }: Props) =>
; - `, - { - babelOptions: { filename: 'component.tsx' }, - }, - ); - - expect(component.props?.name?.tsType).toMatchObject({ - name: 'union', - elements: [ - { - name: 'signature', - type: 'function', - signature: { arguments: [], return: { name: 'string' } }, - }, - { name: 'undefined' }, - ], - }); - }); -}); From 6d5e108ef70fd6a740c3308031ec81137589e778 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 12:42:32 +0100 Subject: [PATCH 14/22] fix: inspect AST for PropTypes imports Replace the source-text regex flagged by CodeQL with one AST traversal per component. Recognize real imports and require calls without treating comments or string literals as imports. --- .changeset/ast-proptypes-imports.md | 7 + .../src/__tests__/propTypesImports-test.ts | 140 ++++++++++++++++++ .../core/src/handlers/propTypesHandler.ts | 60 +++++++- 3 files changed, 203 insertions(+), 4 deletions(-) create mode 100644 .changeset/ast-proptypes-imports.md create mode 100644 packages/core/src/__tests__/propTypesImports-test.ts diff --git a/.changeset/ast-proptypes-imports.md b/.changeset/ast-proptypes-imports.md new file mode 100644 index 00000000000..db86a15371a --- /dev/null +++ b/.changeset/ast-proptypes-imports.md @@ -0,0 +1,7 @@ +--- +'@react-docgen/core': patch +--- + +Recognize PropTypes imports from the parsed AST instead of scanning source text +with a potentially slow regular expression. Comments and string literals no +longer count as module imports. diff --git a/packages/core/src/__tests__/propTypesImports-test.ts b/packages/core/src/__tests__/propTypesImports-test.ts new file mode 100644 index 00000000000..204bf46ba3e --- /dev/null +++ b/packages/core/src/__tests__/propTypesImports-test.ts @@ -0,0 +1,140 @@ +import { expect, test } from 'vitest'; +import { createDocgen, propTypesHandler, type AstNode } from '../index.js'; + +const id = (name: string): AstNode => ({ type: 'Identifier', name }); +const literal = (value: string): AstNode => ({ type: 'Literal', value }); +const imported = (source: string, named = false): AstNode => ({ + type: 'ImportDeclaration', + source: literal(source), + specifiers: [ + { + type: named ? 'ImportSpecifier' : 'ImportDefaultSpecifier', + local: id('PropTypes'), + ...(named ? { imported: id('PropTypes') } : {}), + }, + ], +}); + +function propType(imports: AstNode[], prefix = '') { + const raw = 'PropTypes.string'; + const code = `${prefix}\n${raw}`; + const component: AstNode = { + type: 'FunctionDeclaration', + id: id('Button'), + params: [], + }; + const ast: AstNode = { + type: 'Program', + body: [ + ...imports, + component, + { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'MemberExpression', + computed: false, + object: id('Button'), + property: id('propTypes'), + }, + right: { + type: 'ObjectExpression', + properties: [ + { + type: 'Property', + key: id('value'), + value: { + type: 'MemberExpression', + computed: false, + object: id('PropTypes'), + property: id('string'), + range: [code.length - raw.length, code.length], + }, + }, + ], + }, + }, + }, + ], + }; + const parse = createDocgen({ + parser: { + parse: () => ast, + visitorKeys: { + Program: ['body'], + ImportDeclaration: ['specifiers', 'source'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + CallExpression: ['callee', 'arguments'], + }, + }, + resolver(file) { + const body = file.path.get('body'); + + return Array.isArray(body) + ? body.filter((path) => path.node === component) + : []; + }, + handlers: [propTypesHandler], + }); + + return parse(code, { filename: 'button.js' })[0]?.props?.value?.type; +} + +test('recognizes a package import with long whitespace from its AST', () => { + expect( + propType( + [imported('prop-types')], + `import ${' '.repeat(20_000)}PropTypes from 'prop-types';`, + ), + ).toEqual({ name: 'string' }); +}); + +test('recognizes named React PropTypes imports', () => { + expect( + propType([imported('react', true)], "import { PropTypes } from 'react';"), + ).toEqual({ name: 'string' }); +}); + +test('recognizes require calls with whitespace and comments', () => { + const declaration: AstNode = { + type: 'VariableDeclaration', + declarations: [ + { + type: 'VariableDeclarator', + id: id('PropTypes'), + init: { + type: 'CallExpression', + callee: id('require'), + arguments: [literal('prop-types')], + }, + }, + ], + }; + + expect( + propType( + [declaration], + "const PropTypes = require( /* package */ 'prop-types' );", + ), + ).toEqual({ name: 'string' }); +}); + +test.each([ + { name: 'a comment', source: "// import { PropTypes } from 'react';" }, + { + name: 'a string literal', + source: `const example = "require('prop-types')";`, + }, + { + name: 'a long unrelated import', + source: `import ${' '.repeat(20_000)}PropTypes from 'custom-validators';`, + }, +])('does not infer imports from $name', ({ source }) => { + expect(propType([imported('custom-validators')], source)).toEqual({ + name: 'custom', + raw: 'PropTypes.string', + }); +}); diff --git a/packages/core/src/handlers/propTypesHandler.ts b/packages/core/src/handlers/propTypesHandler.ts index 1b7443d2702..0e7b1fe73e3 100644 --- a/packages/core/src/handlers/propTypesHandler.ts +++ b/packages/core/src/handlers/propTypesHandler.ts @@ -1,8 +1,11 @@ import { isAssignmentExpression, + isCallExpression, isExpressionStatement, isIdentifier, + isLiteral, isMemberExpression, + type FileState, type Handler, } from '../internal.js'; import getBody from '../utils/getBody.js'; @@ -17,6 +20,55 @@ import getClassStaticValue from '../utils/getClassStaticValue.js'; import getResolvedEnumValues from '../utils/getResolvedEnumValues.js'; import unwrapExpression from '../utils/unwrapExpression.js'; +function hasPropTypesImport(file: FileState): boolean { + let found = false; + + file.traverse( + { + ImportDeclaration(path) { + const source = path.get('source'); + + if (!source || Array.isArray(source) || !isLiteral(source.node)) return; + if (source.node.value === 'prop-types') { + found = true; + } else if (source.node.value === 'react') { + const specifiers = path.get('specifiers'); + + found = + Array.isArray(specifiers) && + specifiers.some((specifier) => { + if (specifier.node.type !== 'ImportSpecifier') return false; + const imported = specifier.get('imported'); + + return Boolean( + imported && + !Array.isArray(imported) && + isIdentifier(imported.node, { name: 'PropTypes' }), + ); + }); + } + if (found) path.stop(); + }, + CallExpression(path) { + if ( + !isCallExpression(path.node) || + !isIdentifier(path.node.callee, { name: 'require' }) + ) + return; + const [source] = path.node.arguments; + + if (source && isLiteral(source) && source.value === 'prop-types') { + found = true; + path.stop(); + } + }, + }, + undefined, + ); + + return found; +} + const propTypesHandler: Handler = (documentation, path, file) => { const componentName = getComponentName(path); @@ -50,6 +102,9 @@ const propTypesHandler: Handler = (documentation, path, file) => { propTypesObjects.push(assignment.right); } + if (propTypesObjects.length === 0) return; + const importedPropTypes = hasPropTypesImport(file); + for (const propTypesObject of propTypesObjects) { for (const property of getObjectProperties(file, propTypesObject)) { const keyName = getPropertyName(property.key); @@ -89,10 +144,7 @@ const propTypesHandler: Handler = (documentation, path, file) => { const enumValues = getResolvedEnumValues(file, property.value); const type = enumValues ? { name: 'enum', value: enumValues } - : memberName?.startsWith('PropTypes.') && - !/(?:\bfrom\s+['"]prop-types['"]|require\(['"]prop-types['"]\)|import\s+[^;]*\bPropTypes\b[^;]*\bfrom\s+['"]react['"])/.test( - file.source.code, - ) + : memberName?.startsWith('PropTypes.') && !importedPropTypes ? { name: 'custom', raw, From 2d64d4fac6481de708817ce68e4dd488a86583ea Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 12:44:03 +0100 Subject: [PATCH 15/22] perf: reuse the PropTypes import visitor --- .../core/src/handlers/propTypesHandler.ts | 96 ++++++++++--------- 1 file changed, 50 insertions(+), 46 deletions(-) diff --git a/packages/core/src/handlers/propTypesHandler.ts b/packages/core/src/handlers/propTypesHandler.ts index 0e7b1fe73e3..60f8a132bfa 100644 --- a/packages/core/src/handlers/propTypesHandler.ts +++ b/packages/core/src/handlers/propTypesHandler.ts @@ -19,54 +19,58 @@ import resolveValue from '../utils/resolveValue.js'; import getClassStaticValue from '../utils/getClassStaticValue.js'; import getResolvedEnumValues from '../utils/getResolvedEnumValues.js'; import unwrapExpression from '../utils/unwrapExpression.js'; +import type { Visitor } from '../traverse.js'; + +interface PropTypesImportState { + found: boolean; +} + +const propTypesImportVisitor: Visitor = { + ImportDeclaration(path, state) { + const source = path.get('source'); + + if (!source || Array.isArray(source) || !isLiteral(source.node)) return; + if (source.node.value === 'prop-types') { + state.found = true; + } else if (source.node.value === 'react') { + const specifiers = path.get('specifiers'); + + state.found = + Array.isArray(specifiers) && + specifiers.some((specifier) => { + if (specifier.node.type !== 'ImportSpecifier') return false; + const imported = specifier.get('imported'); + + return Boolean( + imported && + !Array.isArray(imported) && + isIdentifier(imported.node, { name: 'PropTypes' }), + ); + }); + } + if (state.found) path.stop(); + }, + CallExpression(path, state) { + if ( + !isCallExpression(path.node) || + !isIdentifier(path.node.callee, { name: 'require' }) + ) + return; + const [source] = path.node.arguments; + + if (source && isLiteral(source) && source.value === 'prop-types') { + state.found = true; + path.stop(); + } + }, +}; function hasPropTypesImport(file: FileState): boolean { - let found = false; - - file.traverse( - { - ImportDeclaration(path) { - const source = path.get('source'); - - if (!source || Array.isArray(source) || !isLiteral(source.node)) return; - if (source.node.value === 'prop-types') { - found = true; - } else if (source.node.value === 'react') { - const specifiers = path.get('specifiers'); - - found = - Array.isArray(specifiers) && - specifiers.some((specifier) => { - if (specifier.node.type !== 'ImportSpecifier') return false; - const imported = specifier.get('imported'); - - return Boolean( - imported && - !Array.isArray(imported) && - isIdentifier(imported.node, { name: 'PropTypes' }), - ); - }); - } - if (found) path.stop(); - }, - CallExpression(path) { - if ( - !isCallExpression(path.node) || - !isIdentifier(path.node.callee, { name: 'require' }) - ) - return; - const [source] = path.node.arguments; - - if (source && isLiteral(source) && source.value === 'prop-types') { - found = true; - path.stop(); - } - }, - }, - undefined, - ); - - return found; + const state: PropTypesImportState = { found: false }; + + file.traverse(propTypesImportVisitor, state); + + return state.found; } const propTypesHandler: Handler = (documentation, path, file) => { From c967779180287380458a82b6b8eac0170b1de9cb Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 12:51:16 +0100 Subject: [PATCH 16/22] perf: reuse imperative handle traversal callbacks Move the walker and visitors to module scope and pass extraction and return-object data through per-traversal state. Verify independent results across multiple handle factories and successive extractions. --- .../findImperativeHandleMethods-test.ts | 47 ++++- .../src/utils/findImperativeHandleMethods.ts | 161 ++++++++++-------- 2 files changed, 131 insertions(+), 77 deletions(-) diff --git a/packages/core/src/__tests__/findImperativeHandleMethods-test.ts b/packages/core/src/__tests__/findImperativeHandleMethods-test.ts index 8c0c9d337d5..6c9584729f2 100644 --- a/packages/core/src/__tests__/findImperativeHandleMethods-test.ts +++ b/packages/core/src/__tests__/findImperativeHandleMethods-test.ts @@ -23,11 +23,13 @@ function findMethods({ params = [], source = 'react', value = call('useCb', [fn()]), + factories, }: { declarations?: AstNode[]; params?: AstNode[]; source?: string; value?: AstNode; + factories?: AstNode[]; } = {}) { const property = { type: 'Property', key: id('focus'), value: id('method') }; const ast: AstNode = { @@ -53,17 +55,18 @@ function findMethods({ body: [ ...declarations, variable('method', value), - { - type: 'ExpressionStatement', - expression: call('useImperativeHandle', [ - id('ref'), + ...( + factories ?? [ { type: 'ArrowFunctionExpression', params: [], body: { type: 'ObjectExpression', properties: [property] }, }, - ]), - }, + ] + ).map((factory) => ({ + type: 'ExpressionStatement', + expression: call('useImperativeHandle', [id('ref'), factory]), + })), ], }, }, @@ -122,3 +125,35 @@ test('stops resolving circular callback aliases', () => { }), ).toEqual([]); }); + +test('keeps visitor state separate across factories and extractions', () => { + const first = fn(); + const second = fn(); + const factories: AstNode[] = [first, second].map((callback) => ({ + type: 'ArrowFunctionExpression', + params: [], + body: { + type: 'BlockStatement', + body: [ + variable('handle', { + type: 'ObjectExpression', + properties: [ + { + type: 'Property', + key: id('focus'), + value: call('useCb', [callback]), + }, + ], + }), + { type: 'ReturnStatement', argument: id('handle') }, + ], + }, + })); + + expect(findMethods({ factories }).map((method) => method.fn)).toEqual([ + first, + second, + ]); + expect(findMethods({ source: 'other-library' })).toEqual([]); + expect(findMethods()).toHaveLength(1); +}); diff --git a/packages/core/src/utils/findImperativeHandleMethods.ts b/packages/core/src/utils/findImperativeHandleMethods.ts index bf5fbe99637..f5c0bc038f5 100644 --- a/packages/core/src/utils/findImperativeHandleMethods.ts +++ b/packages/core/src/utils/findImperativeHandleMethods.ts @@ -153,86 +153,105 @@ export interface ImperativeHandleMethod { fn: AstNode; } -export default function findImperativeHandleMethods( - file: FileState, - component: AstPath, -): ImperativeHandleMethod[] { - const methods: ImperativeHandleMethod[] = []; - - function visit(path: AstPath, visitor: (path: AstPath) => boolean): void { - if ( - visitor(path) || - isFunction(path.node) || - path.node.type === 'ClassDeclaration' || - path.node.type === 'ClassExpression' - ) - return; - for (const key of file.visitorKeys[path.node.type] ?? []) { - const value = path.get(key); - - for (const nested of Array.isArray(value) - ? value - : value - ? [value] - : []) { - visit(nested, visitor); - } +interface MethodState { + file: FileState; + methods: ImperativeHandleMethod[]; +} + +interface ReturnState { + file: FileState; + object: AstPath; +} + +function visit( + path: AstPath, + visitor: (path: AstPath, state: State) => boolean, + state: State, +): void { + if ( + visitor(path, state) || + isFunction(path.node) || + path.node.type === 'ClassDeclaration' || + path.node.type === 'ClassExpression' + ) + return; + for (const key of state.file.visitorKeys[path.node.type] ?? []) { + const value = path.get(key); + + for (const nested of Array.isArray(value) ? value : value ? [value] : []) { + visit(nested, visitor, state); } } +} - const body = child(component, 'body'); +function returnVisitor(path: AstPath, state: ReturnState): boolean { + if (path.node.type !== 'ReturnStatement') return false; + const argument = child(path, 'argument'); - if (!body) return methods; - visit(body, (path) => { - if (!isCallExpression(path.node)) return false; - const callee = child(path, 'callee'); - const factory = children(path, 'arguments')[1]; - - if ( - !callee || - !isReactHook(callee, 'useImperativeHandle') || - !factory || - !isFunction(factory.node) - ) - return true; - const factoryBody = child(factory, 'body'); - - if (!factoryBody) return true; - let object = resolve(factoryBody); - - if (!isObjectExpression(object.node)) { - visit(factoryBody, (returned) => { - if (returned.node.type !== 'ReturnStatement') return false; - const argument = child(returned, 'argument'); - - if (argument && isObjectExpression(resolve(argument).node)) - object = resolve(argument); - - return true; - }); - } - if (!isObjectExpression(object.node)) return true; + if (argument) { + const object = resolve(argument); + + if (isObjectExpression(object.node)) state.object = object; + } - for (const property of children(object, 'properties')) { - if (!isProperty(property.node)) continue; - const value = child(property, 'value'); + return true; +} - if (!value) continue; - let fn = resolve(value); +function methodVisitor(path: AstPath, state: MethodState): boolean { + if (!isCallExpression(path.node)) return false; + const callee = child(path, 'callee'); + const factory = children(path, 'arguments')[1]; + + if ( + !callee || + !isReactHook(callee, 'useImperativeHandle') || + !factory || + !isFunction(factory.node) + ) + return true; + const factoryBody = child(factory, 'body'); - if (isCallExpression(fn.node)) { - const hook = child(fn, 'callee'); - const callback = children(fn, 'arguments')[0]; + if (!factoryBody) return true; + let object = resolve(factoryBody); - if (!hook || !isReactHook(hook, 'useCallback') || !callback) continue; - fn = resolve(callback); - } - if (isFunction(fn.node)) - methods.push({ property: property.node, fn: fn.node }); + if (!isObjectExpression(object.node)) { + const returnState: ReturnState = { file: state.file, object }; + + visit(factoryBody, returnVisitor, returnState); + object = returnState.object; + } + if (!isObjectExpression(object.node)) return true; + + for (const property of children(object, 'properties')) { + if (!isProperty(property.node)) continue; + const value = child(property, 'value'); + + if (!value) continue; + let fn = resolve(value); + + if (isCallExpression(fn.node)) { + const hook = child(fn, 'callee'); + const callback = children(fn, 'arguments')[0]; + + if (!hook || !isReactHook(hook, 'useCallback') || !callback) continue; + fn = resolve(callback); + } + if (isFunction(fn.node)) { + state.methods.push({ property: property.node, fn: fn.node }); } + } - return true; - }); + return true; +} + +export default function findImperativeHandleMethods( + file: FileState, + component: AstPath, +): ImperativeHandleMethod[] { + const state: MethodState = { file, methods: [] }; + const body = child(component, 'body'); + + if (body) visit(body, methodVisitor, state); - return methods; + return state.methods; } From c96cc79c45591f1e53b38f2f82a1ccce61e26c6c Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 20:46:08 +0100 Subject: [PATCH 17/22] fix: port mixin class props to parser adapters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Miklós Fazekas --- .changeset/mixin-class-props.md | 14 +++ PLAN.md | 11 +- .../mixin-component-alias/index.tsx | 12 ++ .../mixin-component-alias/output.json | 16 +++ .../definitions/mixin-component/index.tsx | 20 +++ .../definitions/mixin-component/output.json | 16 +++ .../mixin-declared-props/index.tsx | 13 ++ .../mixin-declared-props/output.json | 16 +++ .../mixin-pure-component-alias/index.tsx | 13 ++ .../mixin-pure-component-alias/output.json | 23 ++++ .../mixin-unrelated-component/index.tsx | 19 +++ .../mixin-unrelated-component/output.json | 16 +++ .../mixin-unrelated-generic/index.tsx | 23 ++++ .../mixin-unrelated-generic/output.json | 16 +++ .../definitions/mixin-wrapped-props/index.tsx | 17 +++ .../mixin-wrapped-props/output.json | 16 +++ .../src/utils/getTypeArguments.ts | 30 +++++ .../src/utils/getTypeFromReactComponent.ts | 57 +++++++-- .../src/handlers/typescriptPropsHandler.ts | 3 +- .../typescript/src/utils/getClassPropsType.ts | 114 ++++++++++++++++++ .../integration/babel-differential-test.ts | 30 ++++- 21 files changed, 485 insertions(+), 10 deletions(-) create mode 100644 .changeset/mixin-class-props.md create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-component-alias/index.tsx create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-component-alias/output.json create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-component/index.tsx create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-component/output.json create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-declared-props/index.tsx create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-declared-props/output.json create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/index.tsx create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/output.json create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/index.tsx create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/output.json create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/index.tsx create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/output.json create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/index.tsx create mode 100644 packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/output.json create mode 100644 packages/react-docgen/src/utils/getTypeArguments.ts create mode 100644 packages/typescript/src/utils/getClassPropsType.ts diff --git a/.changeset/mixin-class-props.md b/.changeset/mixin-class-props.md new file mode 100644 index 00000000000..b87defee716 --- /dev/null +++ b/.changeset/mixin-class-props.md @@ -0,0 +1,14 @@ +--- +'react-docgen': patch +'@react-docgen/typescript': patch +--- + +Extract TypeScript props from React class components extending mixin calls, +including aliased component bases and wrapped props. Preserve declared props +when a mixin receives unrelated generic arguments. + +Ported from [#1145](https://github.com/reactjs/react-docgen/pull/1145) by +[@mfazekas](https://github.com/mfazekas), merged with follow-up fixes in +[#1157](https://github.com/reactjs/react-docgen/pull/1157). Shared regression +fixtures cover the legacy parser, TypeScript adapter, and TypeScript handlers +composed with the normalized Babel adapter. diff --git a/PLAN.md b/PLAN.md index 2ea3568d6d6..975f6582b17 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,7 +5,7 @@ - Current milestone: 6 — Stable release and migration - Overall status: Default extraction parity complete; public API and release hardening remain -- Last updated: 2026-09-21 +- Last updated: 2026-10-31 ## Release-readiness summary @@ -232,6 +232,15 @@ import { parse } from '@react-docgen/typescript'; Record every material plan change here before or with implementation. +### 2026-10-31 — Ported mixin class props from the maintained legacy line + +- Carried #1145/#1157 into the legacy reference and TypeScript adapter, + preserving React base validation, wrapped props, aliased imports, and + declared-props fallback. +- Added portable golden cases and composed the TypeScript handler with the Babel + adapter to check the same output across parser representations. +- Credited the original contribution by @mfazekas in the changeset. + ### 2026-09-21 — Audited release readiness after mixed-parser implementation - Confirmed default JavaScript, TypeScript, and Flow extraction parity across diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/index.tsx new file mode 100644 index 00000000000..27665394034 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/index.tsx @@ -0,0 +1,12 @@ +import { Component as Base } from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +export default class MyComponent extends withFoo(Base) { + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-component/index.tsx new file mode 100644 index 00000000000..b526beb4e46 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component/index.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +interface Props { + /** + * description of value + */ + value: string; +} + +function withFoo React.Component>( + Base: T, +) { + return class extends Base {}; +} + +export default class MyComponent extends withFoo(React.Component) { + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-component/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/index.tsx new file mode 100644 index 00000000000..06c7929eb7b --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/index.tsx @@ -0,0 +1,13 @@ +import React from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +export default class MyComponent extends withFoo(React.Component) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/index.tsx new file mode 100644 index 00000000000..d7cf4e81851 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/index.tsx @@ -0,0 +1,13 @@ +import { PureComponent as Base } from 'react'; + +interface Props { + /** description of value */ + value: string; + enabled?: boolean; +} + +export default class MyComponent extends withFoo(Base) { + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/output.json new file mode 100644 index 00000000000..e48b3c08c69 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + }, + "enabled": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/index.tsx new file mode 100644 index 00000000000..623dc1e76f7 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/index.tsx @@ -0,0 +1,19 @@ +import Other from 'other'; + +interface Props { + /** description of value */ + value: string; +} + +interface Options { + unrelated: number; +} + +export default class MyComponent extends makeComponent( + Other.Component, +) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/index.tsx new file mode 100644 index 00000000000..dabe2b661d3 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +interface Options { + unrelated: number; +} +function configure() { + return {}; +} +function makeComponent(_configuration: unknown) { + return React.Component; +} + +export default class MyComponent extends makeComponent(configure) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/index.tsx new file mode 100644 index 00000000000..ceef9c4a54f --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/index.tsx @@ -0,0 +1,17 @@ +import React from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +export default class MyComponent extends withFoo( + React.Component< + React.PropsWithChildren>> + >, +) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/react-docgen/src/utils/getTypeArguments.ts b/packages/react-docgen/src/utils/getTypeArguments.ts new file mode 100644 index 00000000000..07517da57cf --- /dev/null +++ b/packages/react-docgen/src/utils/getTypeArguments.ts @@ -0,0 +1,30 @@ +import type { NodePath } from '@babel/traverse'; +import type { + TSTypeParameterInstantiation, + TypeParameterInstantiation, +} from '@babel/types'; + +/** Reads type arguments from both Babel 7 and Babel 8 ASTs. */ +export default function getTypeArguments( + path: NodePath, +): NodePath< + InstanceType['node'] & + ( + | TSTypeParameterInstantiation + | TypeParameterInstantiation + | null + | undefined + ) +> { + return path.get( + 'typeArguments' in path.node ? 'typeArguments' : 'typeParameters', + ) as NodePath< + InstanceType['node'] & + ( + | TSTypeParameterInstantiation + | TypeParameterInstantiation + | null + | undefined + ) + >; +} diff --git a/packages/react-docgen/src/utils/getTypeFromReactComponent.ts b/packages/react-docgen/src/utils/getTypeFromReactComponent.ts index 028be7e28f7..5874488f9e9 100644 --- a/packages/react-docgen/src/utils/getTypeFromReactComponent.ts +++ b/packages/react-docgen/src/utils/getTypeFromReactComponent.ts @@ -3,6 +3,7 @@ import type Documentation from '../Documentation.js'; import getMemberValuePath from './getMemberValuePath.js'; import getTypeAnnotation from './getTypeAnnotation.js'; import getTypeParameters from './getTypeParameters.js'; +import getTypeArguments from './getTypeArguments.js'; import isReactComponentClass from './isReactComponentClass.js'; import isReactForwardRefCall from './isReactForwardRefCall.js'; import resolveGenericTypeAnnotation from './resolveGenericTypeAnnotation.js'; @@ -18,6 +19,8 @@ import type { TSTypeParameterDeclaration, TSTypeParameterInstantiation, TypeParameterDeclaration, + ClassDeclaration, + ClassExpression, TypeParameterInstantiation, VariableDeclarator, } from '@babel/types'; @@ -82,6 +85,37 @@ function findAssignedVariableType( return null; } +/** + * Finds the props type of a class extending a mixin call, e.g. + * `class X extends withFoo(React.Component) {}`. + */ +function getMixinSuperClassPropsPath( + classDefinition: NodePath, +): NodePath | null { + const superClass = classDefinition.get('superClass'); + + if (!superClass.isCallExpression()) return null; + + const [baseClass] = superClass.get('arguments'); + + if (!baseClass?.isTSInstantiationExpression()) return null; + + const expression = baseClass.get('expression'); + + if ( + !isReactBuiltinReference(expression, 'Component') && + !isReactBuiltinReference(expression, 'PureComponent') + ) { + return null; + } + + const typeParameters = getTypeArguments(baseClass); + + if (!typeParameters.hasNode()) return null; + + return typeParameters.get('params')[0] ?? null; +} + /** * Given an React component (stateless or class) tries to find * flow or TS types for the props. It may find multiple types. @@ -105,16 +139,25 @@ export default (componentDefinition: NodePath): NodePath[] => { } } } else { - const propsMemberPath = getMemberValuePath(componentDefinition, 'props'); + const mixinPropsPath = getMixinSuperClassPropsPath(componentDefinition); - if (!propsMemberPath) { - return []; - } + if (mixinPropsPath) { + typePaths.push(mixinPropsPath); + } else { + const propsMemberPath = getMemberValuePath( + componentDefinition, + 'props', + ); - const typeAnnotation = getTypeAnnotation(propsMemberPath.parentPath); + if (!propsMemberPath) { + return []; + } - if (typeAnnotation) { - typePaths.push(typeAnnotation); + const typeAnnotation = getTypeAnnotation(propsMemberPath.parentPath); + + if (typeAnnotation) { + typePaths.push(typeAnnotation); + } } } } else { diff --git a/packages/typescript/src/handlers/typescriptPropsHandler.ts b/packages/typescript/src/handlers/typescriptPropsHandler.ts index 3d1cef4627f..e041d303f7c 100644 --- a/packages/typescript/src/handlers/typescriptPropsHandler.ts +++ b/packages/typescript/src/handlers/typescriptPropsHandler.ts @@ -14,6 +14,7 @@ import { type Handler, } from '@react-docgen/core'; import getComposedTypeNames from '../utils/getComposedTypeNames.js'; +import getClassPropsType from '../utils/getClassPropsType.js'; import getPropsMembers from '../utils/getPropsMembers.js'; import getTSType from '../utils/getTSType.js'; @@ -31,7 +32,7 @@ const typescriptPropsHandler: Handler = (documentation, path, file) => { ? parameter.typeAnnotation.typeAnnotation : null : isClassDeclaration(path.node) || isClassExpression(path.node) - ? (path.node.superTypeArguments?.params[0] ?? null) + ? getClassPropsType(file, path.node) : null; const propsMembers = getPropsMembers(file, annotation); const composes = getComposedTypeNames(file, annotation); diff --git a/packages/typescript/src/utils/getClassPropsType.ts b/packages/typescript/src/utils/getClassPropsType.ts new file mode 100644 index 00000000000..808823ecdf7 --- /dev/null +++ b/packages/typescript/src/utils/getClassPropsType.ts @@ -0,0 +1,114 @@ +import { + getBody, + getPropertyName, + getValueFile, + isAstNode, + isCallExpression, + isIdentifier, + isLiteral, + isMemberExpression, + isPropertyDefinition, + isTSTypeAnnotation, + resolveValue, + type AstNode, + type ClassDeclaration, + type ClassExpression, + type FileState, +} from '@react-docgen/core'; + +function isReactComponentBase(file: FileState, node: AstNode): boolean { + const expression = resolveValue(file, node); + const member = isMemberExpression(expression) ? expression : null; + + if ( + member && + (member.computed || + (!isIdentifier(member.property, { name: 'Component' }) && + !isIdentifier(member.property, { name: 'PureComponent' }))) + ) { + return false; + } + const local = member?.object ?? expression; + + if (!isIdentifier(local)) return false; + + for (const { node: declaration } of getBody(getValueFile(file, expression))) { + if ( + declaration.type !== 'ImportDeclaration' || + !isAstNode(declaration.source) || + !isLiteral(declaration.source) || + declaration.source.value !== 'react' || + !Array.isArray(declaration.specifiers) + ) { + continue; + } + + for (const specifier of declaration.specifiers) { + if ( + !isAstNode(specifier) || + !isAstNode(specifier.local) || + !isIdentifier(specifier.local, { name: local.name }) + ) { + continue; + } + if (member) { + return ( + specifier.type === 'ImportDefaultSpecifier' || + specifier.type === 'ImportNamespaceSpecifier' + ); + } + + return ( + specifier.type === 'ImportSpecifier' && + isAstNode(specifier.imported) && + (isIdentifier(specifier.imported, { name: 'Component' }) || + isIdentifier(specifier.imported, { name: 'PureComponent' })) + ); + } + } + + return false; +} + +export default function getClassPropsType( + file: FileState, + definition: ClassDeclaration | ClassExpression, +): AstNode | null { + const [propsType] = definition.superTypeArguments?.params ?? []; + + if (propsType) return propsType; + const superClass = definition.superClass; + + if (isAstNode(superClass) && isCallExpression(superClass)) { + const [base] = superClass.arguments; + + if ( + base?.type === 'TSInstantiationExpression' && + isAstNode(base.expression) && + isReactComponentBase(file, base.expression) + ) { + const argumentsNode = base.typeArguments ?? base.typeParameters; + + if ( + isAstNode(argumentsNode) && + Array.isArray(argumentsNode.params) && + isAstNode(argumentsNode.params[0]) + ) { + return argumentsNode.params[0]; + } + } + } + + const props = definition.body.body.find( + (member) => + isPropertyDefinition(member) && + !member.static && + !member.computed && + getPropertyName(member.key) === 'props', + ); + const annotation = props?.typeAnnotation; + + return isAstNode(annotation) && isTSTypeAnnotation(annotation) + ? annotation.typeAnnotation + : null; +} diff --git a/packages/typescript/tests/integration/babel-differential-test.ts b/packages/typescript/tests/integration/babel-differential-test.ts index 3516c5b753d..2ae0a58fe79 100644 --- a/packages/typescript/tests/integration/babel-differential-test.ts +++ b/packages/typescript/tests/integration/babel-differential-test.ts @@ -1,7 +1,13 @@ import fs from 'node:fs'; import path from 'node:path'; import { describe, expect, test } from 'vitest'; -import { parse as parseBabel } from '@react-docgen/babel'; +import babelParser, { parse as parseBabel } from '@react-docgen/babel'; +import { + componentHandler, + createDocgen, + resolveComponentDefinitions, +} from '@react-docgen/core'; +import typescriptPropsHandler from '../../src/handlers/typescriptPropsHandler.js'; import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; import { parse as parseTypeScript } from '../../src/index.js'; @@ -35,3 +41,25 @@ describe('Babel differential', () => { }); } }); + +describe('Babel mixin differential', () => { + const parse = createDocgen({ + handlers: [componentHandler, typescriptPropsHandler], + parser: babelParser, + resolver: resolveComponentDefinitions, + }); + + for (const integrationCase of loadIntegrationCases({ + languages: ['typescript'], + })) { + if (!integrationCase.id.startsWith('typescript/definitions/mixin-')) { + continue; + } + + test(integrationCase.id, () => { + expect( + parse(integrationCase.source, { filename: integrationCase.filename }), + ).toEqual(integrationCase.output); + }); + } +}); From 8756388780e6130b4013abbb730106dd19c6bd06 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 21:41:40 +0100 Subject: [PATCH 18/22] test: fix Windows fixture and path portability --- .gitattributes | 2 ++ .github/workflows/build.yml | 1 + packages/react-docgen-cli/tests/integration/cli-test.ts | 3 ++- 3 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..2a6d1be741a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Portable fixtures have one canonical source representation on every platform. +packages/integration-tests/cases/** text eol=lf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3eb1e83e7ef..66abcc5a013 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,6 +15,7 @@ env: jobs: tests: strategy: + fail-fast: false matrix: node: ["22.13.0", "24.11.0", "26.0.0"] os: ["ubuntu"] diff --git a/packages/react-docgen-cli/tests/integration/cli-test.ts b/packages/react-docgen-cli/tests/integration/cli-test.ts index c0a34c72b20..a587ef8ca45 100644 --- a/packages/react-docgen-cli/tests/integration/cli-test.ts +++ b/packages/react-docgen-cli/tests/integration/cli-test.ts @@ -3,6 +3,7 @@ import { join } from 'path'; import { temporaryFile } from 'tempy'; import { describe, expect, test } from 'vitest'; import withFixture from './utils/withFixture'; +import slash from '../../src/utils/slash.js'; describe('cli', () => { test('loads a single-parser or mixed-parser config module', async () => { @@ -15,7 +16,7 @@ describe('cli', () => { expect(stderr).toBe(''); expect(JSON.parse(stdout)).toEqual({ - [join(dir, 'Component.js')]: [{ displayName: 'Configured' }], + [slash(join(dir, 'Component.js'))]: [{ displayName: 'Configured' }], }); }); }); From 4aec99cb5d08c8d61d47607250cac5f35037b7ea Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 21:46:04 +0100 Subject: [PATCH 19/22] test: collect shared workspace coverage once Count adapter integration tests against shared source modules while retaining the existing legacy coverage thresholds. --- .github/workflows/build.yml | 3 ++- CONTRIBUTING.md | 8 +++++++ PLAN.md | 9 ++++++++ package.json | 3 ++- vitest.config.ts | 42 +++++++++++++++++++++++++++++++++++++ 5 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 vitest.config.ts diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 66abcc5a013..a52f3081b7c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -46,7 +46,7 @@ jobs: - name: Tests with coverage if: "${{ matrix.node == env.NODE_VERSION }}" - run: pnpm test -- --coverage + run: pnpm test:coverage - name: Tests if: "${{ matrix.node != env.NODE_VERSION }}" @@ -58,6 +58,7 @@ jobs: uses: coverallsapp/github-action@8d6379e14d29928660c4ba802d8e85393440b329 # v2 with: parallel: true + file: coverage/lcov.info flag-name: test-${{ matrix.os }} finish: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7b34655b005..6c3a72fc471 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,6 +14,14 @@ We actively welcome your pull requests. 4. Ensure the test suite passes. 5. Make sure your code lints and typechecks. +## Tests and coverage + +Run `pnpm test` for the package suites. Run `pnpm test:coverage` for the CI +coverage report at `coverage/lcov.info`. Coverage runs all package projects in +one Vitest process and resolves parser packages to their sources, so shared core +code exercised by adapter tests is included. The legacy coverage thresholds +remain enforced. + ## Issues We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. diff --git a/PLAN.md b/PLAN.md index 975f6582b17..9b45d12ca9f 100644 --- a/PLAN.md +++ b/PLAN.md @@ -232,6 +232,15 @@ import { parse } from '@react-docgen/typescript'; Record every material plan change here before or with implementation. +### 2026-10-31 — Made CI fixtures portable and unified coverage reporting + +- Pin shared fixture line endings to LF and compare CLI paths in their existing + slash-normalized form on Windows. +- Collect one source-based coverage report across all package projects, so + adapter integration tests contribute to shared core coverage. +- Keep the existing legacy coverage thresholds and let every CI platform finish + even when another matrix job fails. + ### 2026-10-31 — Ported mixin class props from the maintained legacy line - Carried #1145/#1157 into the legacy reference and TypeScript adapter, diff --git a/package.json b/package.json index 0489af5987b..23d4005b447 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,8 @@ "copy:changelog:react-docgen": "cp ./packages/react-docgen/CHANGELOG.md ./packages/website/src/app/docs/release-notes/react-docgen/page.mdx", "copy:changelog:cli": "cp ./packages/react-docgen-cli/CHANGELOG.md ./packages/website/src/app/docs/release-notes/cli/page.mdx", "changesets-release": "pnpm build && changeset publish", - "changesets-version": "changeset version && pnpm install --lockfile-only && pnpm copy:changelog:react-docgen && pnpm copy:changelog:cli" + "changesets-version": "changeset version && pnpm install --lockfile-only && pnpm copy:changelog:react-docgen && pnpm copy:changelog:cli", + "test:coverage": "pnpm build && vitest run --coverage" }, "license": "MIT", "devDependencies": { diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 00000000000..5f2d83a46f9 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url'; +import { defineConfig } from 'vitest/config'; + +const packages = [ + 'babel', + 'core', + 'hermes', + 'react-docgen', + 'react-docgen-cli', + 'typescript', +]; +const alias = Object.fromEntries( + ['babel', 'core', 'hermes', 'typescript'].map((name) => [ + `@react-docgen/${name}`, + fileURLToPath(new URL(`./packages/${name}/src/index.ts`, import.meta.url)), + ]), +); + +export default defineConfig({ + test: { + projects: packages.map((name) => ({ + extends: `./packages/${name}/vitest.config.ts`, + root: `./packages/${name}`, + resolve: { alias }, + test: { name }, + })), + coverage: { + provider: 'v8', + include: packages.map((name) => `packages/${name}/src/**`), + exclude: ['**/__tests__/**', '**/__mocks__/**', '**/__fixtures__/**'], + reporter: ['text', 'lcov', 'json-summary'], + thresholds: { + 'packages/react-docgen/src/**': { + statements: 84, + branches: 74, + functions: 94, + lines: 84, + }, + }, + }, + }, +}); From 7fbc1177d7103f1870e9d52274c8f70abe63d9fb Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 22:03:24 +0100 Subject: [PATCH 20/22] build: require Node 26 LTS and test Node 27 Drop pre-LTS Node 26 support by requiring 26.13.0 or newer. Keep the existing Node 22 and 24 minimums and exercise Node 27 alpha in CI. --- .changeset/giant-worlds-swim.md | 8 ++++++-- .github/workflows/build.yml | 2 +- package.json | 2 +- packages/babel/package.json | 2 +- packages/core/package.json | 2 +- packages/hermes/package.json | 2 +- packages/react-docgen-cli/package.json | 2 +- packages/react-docgen/package.json | 2 +- packages/typescript/package.json | 2 +- 9 files changed, 14 insertions(+), 10 deletions(-) diff --git a/.changeset/giant-worlds-swim.md b/.changeset/giant-worlds-swim.md index 7c25cfff22b..3978a273ba7 100644 --- a/.changeset/giant-worlds-swim.md +++ b/.changeset/giant-worlds-swim.md @@ -3,6 +3,10 @@ 'react-docgen': major --- -Drop support for Node.js 20, 21 and 23 +Drop support for Node.js 20, 21, 23, 25 and pre-LTS Node.js 26 releases. -Minimum Supported Node.js version is now 22.13.0 +Supported Node.js versions are now: + +- Node.js 22.13.0 or newer 22.x releases +- Node.js 24.11.0 or newer 24.x releases +- Node.js 26.13.0 (the first Node.js 26 LTS release) or newer stable releases diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a52f3081b7c..bae2134b1ee 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - node: ["22.13.0", "24.11.0", "26.0.0"] + node: ["22.13.0", "24.11.0", "26.13.0", "27.0.0-alpha.0.0.0"] os: ["ubuntu"] include: - os: macos diff --git a/package.json b/package.json index 23d4005b447..ab9e13f38ae 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "engines": { - "node": "^22.13.0 || ^24.11.0 || >=26", + "node": "^22.13.0 || ^24.11.0 || >=26.13.0", "pnpm": ">=10.6.2" }, "type": "module", diff --git a/packages/babel/package.json b/packages/babel/package.json index 505263ede73..5ed8b2abd81 100644 --- a/packages/babel/package.json +++ b/packages/babel/package.json @@ -14,7 +14,7 @@ "type": "module", "files": ["dist"], "engines": { - "node": "^22.13.0 || ^24.11.0 || >=26" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/core/package.json b/packages/core/package.json index 5387acbf412..32cd968974a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -16,7 +16,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || ^24.11.0 || >=26" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/hermes/package.json b/packages/hermes/package.json index f907004b653..36b7c1f3930 100644 --- a/packages/hermes/package.json +++ b/packages/hermes/package.json @@ -16,7 +16,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || ^24.11.0 || >=26" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/react-docgen-cli/package.json b/packages/react-docgen-cli/package.json index 835b75d3829..8d6e55067ac 100644 --- a/packages/react-docgen-cli/package.json +++ b/packages/react-docgen-cli/package.json @@ -19,7 +19,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || ^24.11.0 || >=26" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "scripts": { "build": "rimraf dist/ && tsc", diff --git a/packages/react-docgen/package.json b/packages/react-docgen/package.json index 7301b2ec8b7..4cb2c051363 100644 --- a/packages/react-docgen/package.json +++ b/packages/react-docgen/package.json @@ -22,7 +22,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || ^24.11.0 || >=26" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "main": "dist/main.js", "typings": "dist/main.d.ts", diff --git a/packages/typescript/package.json b/packages/typescript/package.json index 0b9913641da..9709189b7a6 100644 --- a/packages/typescript/package.json +++ b/packages/typescript/package.json @@ -16,7 +16,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || ^24.11.0 || >=26" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "main": "dist/index.js", "types": "dist/index.d.ts", From 412010e75659910a21c825532f3aacf5d464f7fd Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 22:05:29 +0100 Subject: [PATCH 21/22] ci: track Node 27 prereleases automatically --- .github/workflows/build.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bae2134b1ee..f882b0b28a6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - node: ["22.13.0", "24.11.0", "26.13.0", "27.0.0-alpha.0.0.0"] + node: ["22.13.0", "24.11.0", "26.13.0", "^27.0.0-0"] os: ["ubuntu"] include: - os: macos @@ -39,6 +39,7 @@ jobs: uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: ${{ matrix.node }} + check-latest: ${{ startsWith(matrix.node, '^') }} cache: "pnpm" - name: Install dependencies From bfc5960618c73850222ac3753ee5fd9b0c1f0fe3 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Sat, 31 Oct 2026 22:11:59 +0100 Subject: [PATCH 22/22] chore: enter alpha prerelease mode --- .changeset/pre.json | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .changeset/pre.json diff --git a/.changeset/pre.json b/.changeset/pre.json new file mode 100644 index 00000000000..9a89b8a38fa --- /dev/null +++ b/.changeset/pre.json @@ -0,0 +1,4 @@ +{ + "mode": "pre", + "tag": "alpha" +}