Skip to content

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

TypeScript

feat(docsite): surface prop type definitions in the props table (#3880)

Jiun Shin64a36bc180a3
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index ed83fbd889..e6fc8b5278 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -24,6 +24,10 @@ import * as path from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
import {resolveContentRoot} from './resolve-content-root.mjs';
import {expandWorkspaceDirs} from '../../../scripts/lib/workspace-globs.mjs';
+import {
+ buildTypeDefinitionIndex,
+ collectPropTypeRefs,
+} from '../src/lib/typeDefinitions.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DOCSITE_ROOT = path.resolve(__dirname, '..');
@@ -657,6 +661,31 @@ async function generateComponentRegistry() {
}
}
+ // Surface the shape of non-primitive prop types (issue #2682): when a
+ // documented prop type references a named type exported from this
+ // package's source (e.g. `SearchSource<T>`), record the reference on the
+ // prop and attach the extracted declaration to the entry so the props
+ // table can render it on demand.
+ const typeIndex = buildTypeDefinitionIndex(
+ pkg.srcDir,
+ path.relative(CONTENT_ROOT, pkg.srcDir),
+ );
+ for (const comp of components) {
+ const referenced = new Map();
+ for (const prop of comp.props) {
+ const typeRefs = collectPropTypeRefs(prop.type, typeIndex);
+ if (typeRefs.length > 0) {
+ prop.typeRefs = typeRefs;
+ for (const name of typeRefs) {
+ referenced.set(name, typeIndex.get(name));
+ }
+ }
+ }
+ comp.typeDefs = [...referenced.values()].sort((a, b) =>
+ a.name.localeCompare(b.name),
+ );
+ }
+
components.sort((a, b) => a.name.localeCompare(b.name));
if (components.length > 0) {
allComponents[pkg.name] = components;
@@ -673,6 +702,18 @@ export interface PropDoc {
default?: string;
required?: boolean;
slotElements?: ElementDescriptor[];
+ /** Names of package-exported types referenced by \`type\`, resolvable
+ * against the owning entry's \`typeDefs\`. */
+ typeRefs?: string[];
+}
+
+export interface TypeDefinition {
+ /** Exported type name, e.g. \`SearchSource\`. */
+ name: string;
+ /** Extracted TypeScript declaration source, including member JSDoc. */
+ definition: string;
+ /** Repo-relative source file, e.g. \`packages/core/src/Typeahead/types.ts\`. */
+ sourcePath: string;
}
export interface BestPractice {
guidance: boolean;
@@ -761,6 +802,8 @@ export interface ComponentEntry {
hidden: boolean;
parentDoc: string | null;
props: PropDoc[];
+ /** Declarations for every type referenced from \`props[].typeRefs\`. */
+ typeDefs: TypeDefinition[];
usage: UsageDoc | null;
theming: ThemingDoc | null;
params: HookParamDoc[] | null;
diff --git a/apps/docsite/src/__tests__/type-definitions.test.ts b/apps/docsite/src/__tests__/type-definitions.test.ts
new file mode 100644
index 0000000000..fd2b241706
--- /dev/null
+++ b/apps/docsite/src/__tests__/type-definitions.test.ts
@@ -0,0 +1,231 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Prop type definition extraction tests for the docsite.
+ *
+ * Covers the pipeline that lets the props table surface the shape of
+ * non-primitive prop types (issue #2682): lexical extraction of exported
+ * `interface` / `type` declarations, the package-wide definition index, and
+ * reference resolution from documented prop type strings. The logic lives in
+ * src/lib/typeDefinitions.mjs (shared with scripts/generate-data.mjs), so
+ * these tests exercise the same code path the build-time generator uses.
+ *
+ * Run: pnpm -F @astryxdesign/docsite test
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {describe, it, expect} from 'vitest';
+import {
+ extractTypeDeclarations,
+ buildTypeDefinitionIndex,
+ collectPropTypeRefs,
+} from '../lib/typeDefinitions.mjs';
+import {splitTypeRefSegments} from '../components/component-detail/parsePropType';
+import {components} from '../generated/componentRegistry';
+
+const CORE_SRC_DIR = path.resolve(__dirname, '../../../../packages/core/src');
+
+describe('extractTypeDeclarations', () => {
+ it('extracts an exported interface with generics and member JSDoc', () => {
+ const source = [
+ "import type {ReactNode} from 'react';",
+ '',
+ '/** Leading JSDoc is not part of the declaration. */',
+ 'export interface SearchSource<',
+ ' T extends SearchableItem = SearchableItem,',
+ '> {',
+ ' /** Called on query change. Handles {braces} in comments. */',
+ ' search(query: string): Promise<T[]> | T[];',
+ ' cancel?(): void;',
+ '}',
+ ].join('\n');
+
+ const decls = extractTypeDeclarations(source);
+ expect(decls).toHaveLength(1);
+ expect(decls[0].name).toBe('SearchSource');
+ expect(decls[0].kind).toBe('interface');
+ expect(
+ decls[0].definition.startsWith('export interface SearchSource<'),
+ ).toBe(true);
+ expect(decls[0].definition.endsWith('}')).toBe(true);
+ expect(decls[0].definition).toContain('cancel?(): void;');
+ expect(decls[0].definition).not.toContain('Leading JSDoc');
+ });
+
+ it('extracts interfaces with nested object members', () => {
+ const source = [
+ 'export interface TableColumn<T> {',
+ ' key: string;',
+ ' render?: (item: T) => {node: ReactNode; span: number};',
+ '}',
+ 'const after = 1;',
+ ].join('\n');
+
+ const [decl] = extractTypeDeclarations(source);
+ expect(decl.definition.endsWith('}')).toBe(true);
+ expect(decl.definition).not.toContain('const after');
+ });
+
+ it('extracts a type alias ending at the first top-level semicolon', () => {
+ const source = [
+ 'export type SpacingStep = 0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10;',
+ 'export type Handler = (event: {type: string}) => void;',
+ "export type Status = {type: 'error' | 'warning'; message: string};",
+ ].join('\n');
+
+ const decls = extractTypeDeclarations(source);
+ expect(decls.map(d => d.name)).toEqual([
+ 'SpacingStep',
+ 'Handler',
+ 'Status',
+ ]);
+ expect(decls[1].definition).toBe(
+ 'export type Handler = (event: {type: string}) => void;',
+ );
+ expect(decls[2].definition.endsWith('};')).toBe(true);
+ });
+
+ it('ignores non-exported declarations', () => {
+ const source = [
+ 'interface Internal {a: string}',
+ 'type Local = string;',
+ 'export type Public = number;',
+ ].join('\n');
+
+ expect(extractTypeDeclarations(source).map(d => d.name)).toEqual([
+ 'Public',
+ ]);
+ });
+});
+
+describe('buildTypeDefinitionIndex', () => {
+ const index = buildTypeDefinitionIndex(CORE_SRC_DIR, 'packages/core/src');
+
+ it('indexes exported core types with repo-relative source paths', () => {
+ const searchSource = index.get('SearchSource');
+ expect(searchSource).toBeDefined();
+ expect(searchSource!.sourcePath).toBe(
+ 'packages/core/src/Typeahead/types.ts',
+ );
+ expect(searchSource!.definition).toContain(
+ 'export interface SearchSource<',
+ );
+ expect(searchSource!.definition).toContain('bootstrap()');
+ });
+
+ it('skips shape-less compat aliases like `StyleXStyles = any`', () => {
+ expect(index.has('StyleXStyles')).toBe(false);
+ });
+});
+
+describe('collectPropTypeRefs', () => {
+ const index = new Map(
+ ['SearchSource', 'TableColumn', 'XDSButtonProps'].map(name => [
+ name,
+ {name, definition: `export interface ${name} {}`, sourcePath: 'x.ts'},
+ ]),
+ );
+
+ it('resolves referenced names against the index, deduplicated', () => {
+ expect(
+ collectPropTypeRefs('SearchSource<T> | SearchSource<U>', index),
+ ).toEqual(['SearchSource']);
+ expect(collectPropTypeRefs('TableColumn<T>[]', index)).toEqual([
+ 'TableColumn',
+ ]);
+ });
+
+ it('ignores unknown names and generic parameters', () => {
+ expect(collectPropTypeRefs('RefObject<HTMLElement | null>', index)).toEqual(
+ [],
+ );
+ expect(collectPropTypeRefs('T | null', index)).toEqual([]);
+ });
+
+ it('excludes *Props interfaces — they are documented on their own pages', () => {
+ expect(collectPropTypeRefs('ReactElement<XDSButtonProps>', index)).toEqual(
+ [],
+ );
+ });
+});
+
+describe('splitTypeRefSegments', () => {
+ it('turns each resolved name into a ref segment, keeping syntax as text', () => {
+ expect(
+ splitTypeRefSegments('SearchSource<T> | null', ['SearchSource']),
+ ).toEqual([
+ {text: 'SearchSource', isRef: true},
+ {text: '<T> | null', isRef: false},
+ ]);
+ });
+
+ it('marks every occurrence of every resolved name independently', () => {
+ expect(
+ splitTypeRefSegments('TableColumn<T>[] | SearchSource<T>', [
+ 'TableColumn',
+ 'SearchSource',
+ ]),
+ ).toEqual([
+ {text: 'TableColumn', isRef: true},
+ {text: '<T>[] | ', isRef: false},
+ {text: 'SearchSource', isRef: true},
+ {text: '<T>', isRef: false},
+ ]);
+ });
+
+ it('matches on word boundaries so longer names are not split', () => {
+ expect(splitTypeRefSegments('TableColumnGroup', ['TableColumn'])).toEqual([
+ {text: 'TableColumnGroup', isRef: false},
+ ]);
+ });
+
+ it('returns the whole string as plain text when nothing resolves', () => {
+ expect(splitTypeRefSegments('string | number', [])).toEqual([
+ {text: 'string | number', isRef: false},
+ ]);
+ });
+});
+
+describe('props table trigger', () => {
+ const source = fs.readFileSync(
+ path.resolve(
+ __dirname,
+ '../components/component-detail/PlaygroundPropsTable.tsx',
+ ),
+ 'utf8',
+ );
+
+ it('renders the type name itself as the definition trigger', () => {
+ expect(source).toContain('splitTypeRefSegments');
+ expect(source).toMatch(/<button type="button"[^>]*>\s*\{def\.name\}/);
+ });
+
+ it('no longer renders a separate "View {Type}" button', () => {
+ expect(source).not.toContain('View ${def.name}');
+ });
+});
+
+describe('generated registry', () => {
+ const allEntries = Object.values(components).flat();
+
+ it('attaches typeRefs and matching typeDefs to BaseTypeahead', () => {
+ const entry = allEntries.find(e => e.name === 'BaseTypeahead');
+ expect(entry).toBeDefined();
+ const searchSource = entry!.props.find(p => p.name === 'searchSource');
+ expect(searchSource?.typeRefs).toEqual(['SearchSource']);
+ const def = entry!.typeDefs.find(d => d.name === 'SearchSource');
+ expect(def?.definition).toContain('export interface SearchSource<');
+ });
+
+ it('only records typeDefs that some prop references', () => {
+ for (const entry of allEntries) {
+ const referenced = new Set(
+ entry.props.flatMap(prop => prop.typeRefs ?? []),
+ );
+ expect(entry.typeDefs.map(d => d.name).sort()).toEqual(
+ [...referenced].sort(),
+ );
+ }
+ });
+});
diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
index 028cadb42a..e25ab6a23d 100644
--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
@@ -227,6 +227,7 @@ function ComponentDetailInner({
<Heading level={3}>Props</Heading>
<PlaygroundPropsTable
props={comp.props}
+ typeDefs={comp.typeDefs}
knobs={knobs}
state={state}
onPropChange={setProp}
diff --git a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
index 35a246b26e..0837aada9b 100644
--- a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
+++ b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
@@ -10,9 +10,12 @@
'use client';
import {createElement, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {Heading, Text} from '@astryxdesign/core/Text';
import {HStack, VStack} from '@astryxdesign/core/Layout';
import {Divider} from '@astryxdesign/core';
+import {Card} from '@astryxdesign/core/Card';
+import {Popover} from '@astryxdesign/core/Popover';
import {Switch} from '@astryxdesign/core/Switch';
import {TextInput} from '@astryxdesign/core/TextInput';
import {NumberInput} from '@astryxdesign/core/NumberInput';
@@ -24,15 +27,52 @@ import {Minus, Plus} from 'lucide-react';
import {useMediaQuery} from '@astryxdesign/core/hooks';
import {allSyntaxPresets} from '@astryxdesign/core/theme/syntax';
import {themeObjectsFull} from '../../generated/themeRegistry';
-import {coerceEnumOption, type PropControlDescriptor} from './parsePropType';
+import {
+ coerceEnumOption,
+ splitTypeRefSegments,
+ type PropControlDescriptor,
+} from './parsePropType';
import type {KnobProp} from './InteractivePreview';
import {resolveElementDescriptor} from './resolveElements';
import type {
ElementDescriptor,
PropDoc,
+ TypeDefinition,
} from '../../generated/componentRegistry';
+import {CodeExampleBlock} from '../CodeExampleBlock';
import {MarkdownText} from '../MarkdownText';
+const styles = stylex.create({
+ // Inline link treatment for type-name definition triggers, mirroring the
+ // authored-docs link pattern (docs/inlineMarkdown.tsx) on a button element
+ // so the trigger stays keyboard-focusable with a visible focus ring.
+ typeRefTrigger: {
+ backgroundColor: 'transparent',
+ borderStyle: 'none',
+ padding: 0,
+ fontFamily: 'inherit',
+ fontSize: 'inherit',
+ lineHeight: 'inherit',
+ cursor: 'pointer',
+ color: 'var(--color-text-accent)',
+ textDecorationLine: 'underline',
+ textDecorationThickness: '1px',
+ textUnderlineOffset: '0.16em',
+ transition: 'color 120ms ease, text-decoration-color 120ms ease',
+ ':hover': {
+ '@media (hover: hover)': {
+ color: 'var(--color-accent)',
+ textDecorationThickness: '2px',
+ },
+ },
+ ':focus-visible': {
+ borderRadius: 'var(--radius-sm)',
+ outline: '2px solid var(--color-accent)',
+ outlineOffset: 2,
+ },
+ },
+});
+
function formatType(type: string, defaultValue?: string): React.ReactNode {
const parts = type.split(/\s*\|\s*/);
const isEnum = parts.length > 1 && parts.every(p => /^['"]/.test(p.trim()));
@@ -64,6 +104,86 @@ function formatType(type: string, defaultValue?: string): React.ReactNode {
return type;
}
+/**
+ * Inline definition trigger for a type name in the type column: the name
+ * itself renders as a link-styled button that opens the extracted declaration
+ * so readers can inspect the shape without leaving the props table (#2682).
+ * The popover mirrors the Popover + Card + CodeExampleBlock pattern used by
+ * PackageActions.
+ */
+function TypeDefinitionTrigger({def}: {def: TypeDefinition}) {
+ return (
+ <Popover
+ width="min(480px, calc(100vw - 32px))"
+ label={`${def.name} type definition`}
+ content={
+ <VStack gap={1}>
+ <Text type="supporting" color="secondary">
+ {def.sourcePath}
+ </Text>
+ <Card padding={0}>
+ <CodeExampleBlock
+ code={def.definition}
+ language="typescript"
+ size="sm"
+ hasCopyButton
+ maxHeight={320}
+ width="100%"
+ />
+ </Card>
+ </VStack>
+ }>
+ <button type="button" {...stylex.props(styles.typeRefTrigger)}>
+ {def.name}
+ </button>
+ </Popover>
+ );
+}
+
+/**
+ * Type-column text for a prop. When the documented type references named
+ * types exported from the component's package (e.g. `SearchSource<T>`), each
+ * referenced name becomes a {@link TypeDefinitionTrigger}; surrounding type
+ * syntax (generics punctuation, unions) stays plain text. Props with no
+ * resolved references keep the plain formatType rendering.
+ */
+function PropTypeText({
+ prop,
+ typeDefs,
+}: {
+ prop: PropDoc;
+ typeDefs: TypeDefinition[];
+}) {
+ const defs = (prop.typeRefs ?? [])
+ .map(name => typeDefs.find(def => def.name === name))
+ .filter(def => def != null);
+ if (defs.length === 0) {
+ return <>{formatType(prop.type, prop.default)}</>;
+ }
+
+ const segments = splitTypeRefSegments(
+ prop.type,
+ defs.map(def => def.name),
+ );
+ return (
+ <>
+ {segments.map((segment, i) => {
+ const def = segment.isRef
+ ? defs.find(d => d.name === segment.text)
+ : undefined;
+ return def ? (
+ <TypeDefinitionTrigger key={i} def={def} />
+ ) : (
+ <span key={i}>{segment.text}</span>
+ );
+ })}
+ {prop.default != null && (
+ <span style={{opacity: 0.6}}> (default: {prop.default})</span>
+ )}
+ </>
+ );
+}
+
function resolveSlotElement(
componentName: string,
slotElements?: Array<{
@@ -468,12 +588,14 @@ function InlineControl({
function PropRow({
prop,
+ typeDefs,
knob,
value,
onChange,
isMobile,
}: {
prop: PropDoc;
+ typeDefs: TypeDefinition[];
knob?: KnobProp;
value?: unknown;
onChange?: (next: unknown) => void;
@@ -486,7 +608,7 @@ function PropRow({
{prop.name}
</Text>
<Text type="code" display="block">
- {formatType(prop.type, prop.default)}
+ <PropTypeText prop={prop} typeDefs={typeDefs} />
</Text>
{prop.description != null && prop.description !== '' && (
<MarkdownText type="body" color="secondary">
@@ -514,7 +636,7 @@ function PropRow({
</div>
<div style={{flex: 1}}>
<Text type="code" display="block">
- {formatType(prop.type, prop.default)}
+ <PropTypeText prop={prop} typeDefs={typeDefs} />
</Text>
{prop.description != null && prop.description !== '' && (
<MarkdownText type="body" color="secondary" style={{marginTop: 6}}>
@@ -538,6 +660,7 @@ function PropRow({
interface PlaygroundPropsTableProps {
props: PropDoc[];
+ typeDefs: TypeDefinition[];
knobs: KnobProp[];
state: Record<string, unknown>;
onPropChange: (name: string, value: unknown) => void;
@@ -545,6 +668,7 @@ interface PlaygroundPropsTableProps {
export function PlaygroundPropsTable({
props,
+ typeDefs,
knobs,
state,
onPropChange,
@@ -569,6 +693,7 @@ export function PlaygroundPropsTable({
<Divider />
<PropRow
prop={prop}
+ typeDefs={typeDefs}
knob={knobMap.get(prop.name)}
value={state[prop.name]}
onChange={next => onPropChange(prop.name, next)}
@@ -590,6 +715,7 @@ export function PlaygroundPropsTable({
<Divider />
<PropRow
prop={prop}
+ typeDefs={typeDefs}
knob={knobMap.get(prop.name)}
value={state[prop.name]}
onChange={next => onPropChange(prop.name, next)}
diff --git a/apps/docsite/src/components/component-detail/parsePropType.ts b/apps/docsite/src/components/component-detail/parsePropType.ts
index d6642c538c..3a1a1b9f12 100644
--- a/apps/docsite/src/components/component-detail/parsePropType.ts
+++ b/apps/docsite/src/components/component-detail/parsePropType.ts
@@ -5,12 +5,15 @@ import {getIconRegistry} from '@astryxdesign/core/Icon';
/**
* @file parsePropType.ts
* @input Stringified TypeScript prop types from component docs
- * @output Control descriptors and typed default/option coercion helpers
+ * @output Control descriptors, typed default/option coercion helpers, and
+ * type-reference segments for inline definition triggers
* @position Component detail and playground prop-control generation.
*
* Parses a stringified TypeScript prop type into a control descriptor
* that the playground can render an input for. Literal unions become
- * enum controls, including mixed string-literal + boolean unions.
+ * enum controls, including mixed string-literal + boolean unions. Also
+ * splits type strings into type-reference segments so the props table can
+ * render each resolved type name as an inline definition trigger (#2682).
*/
export interface ElementOption {
@@ -298,6 +301,37 @@ export function parsePropType(
return {kind: 'unknown'};
}
+export interface TypeRefSegment {
+ text: string;
+ isRef: boolean;
+}
+
+/**
+ * Split a documented prop type string into plain-text and type-reference
+ * segments, e.g. `SearchSource<T> | null` with refs `['SearchSource']` →
+ * `[{SearchSource, isRef}, {<T> | null}]`. The props table renders each
+ * reference segment as an inline trigger that opens the type's definition
+ * (see `PropDoc.typeRefs` / `ComponentEntry.typeDefs`); surrounding type
+ * syntax stays plain text. Names are matched on word boundaries,
+ * longest-first, so overlapping names resolve to the longer one.
+ */
+export function splitTypeRefSegments(
+ typeStr: string,
+ names: readonly string[],
+): TypeRefSegment[] {
+ if (names.length === 0) {
+ return [{text: typeStr, isRef: false}];
+ }
+ const pattern = new RegExp(
+ `\\b(${[...names].sort((a, b) => b.length - a.length).join('|')})\\b`,
+ 'g',
+ );
+ return typeStr
+ .split(pattern)
+ .filter(segment => segment !== '')
+ .map(segment => ({text: segment, isRef: names.includes(segment)}));
+}
+
export function coerceEnumOption(
control: EnumPropControlDescriptor,
option: string,
diff --git a/apps/docsite/src/lib/typeDefinitions.mjs b/apps/docsite/src/lib/typeDefinitions.mjs
new file mode 100644
index 0000000000..27a37b57bf
--- /dev/null
+++ b/apps/docsite/src/lib/typeDefinitions.mjs
@@ -0,0 +1,239 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file typeDefinitions.mjs
+ *
+ * Build-time extraction of exported TypeScript type declarations.
+ *
+ * Component `.doc.mjs` prop tables document types as plain strings (e.g.
+ * `SearchSource<T>`), which leaves readers no way to inspect what a
+ * non-primitive type actually contains (issue #2682). This module scans a
+ * package's `src/` for `export interface` / `export type` declarations and
+ * extracts their source text, so the data generator can attach the resolved
+ * shape of every referenced type to the component registry and the props
+ * table can surface it.
+ *
+ * The parser is intentionally lexical (brace/angle matching that skips
+ * strings and comments) rather than a full TypeScript AST: it runs against
+ * both the live workspace and published-release snapshots without adding a
+ * compiler dependency to the data pipeline, matching the regex-based
+ * extraction style of scripts/generate-data.mjs.
+ *
+ * @input TypeScript source files under a package's src/ directory
+ * @output Map of exported type name → {name, definition, sourcePath}
+ * @position Imported by scripts/generate-data.mjs and
+ * src/__tests__/type-definitions.test.ts. Node-only (reads the filesystem)
+ * — the browser-side rendering helper lives in
+ * components/component-detail/parsePropType.ts.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+const EXPORTED_DECL_RE = /^export (?:declare )?(interface|type) ([A-Za-z_$][\w$]*)/gm;
+
+/**
+ * Advance past a string literal starting at `i` (the opening quote).
+ * Returns the index just past the closing quote.
+ */
+function skipString(source, i) {
+ const quote = source[i];
+ i++;
+ while (i < source.length) {
+ if (source[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ if (source[i] === quote) {
+ return i + 1;
+ }
+ i++;
+ }
+ return i;
+}
+
+/**
+ * Advance past a `//` or `/*` comment starting at `i`.
+ * Returns the index just past the comment, or `source.length` if unterminated.
+ */
+function skipComment(source, i) {
+ if (source[i + 1] === '/') {
+ const end = source.indexOf('\n', i + 2);
+ return end === -1 ? source.length : end + 1;
+ }
+ const end = source.indexOf('*/', i + 2);
+ return end === -1 ? source.length : end + 2;
+}
+
+/**
+ * Find the end (exclusive) of an `interface` body: scans from `from` to the
+ * body's opening `{` (skipping any braces inside generic parameter defaults),
+ * then to its matching `}`. Strings and comments are skipped so JSDoc braces
+ * inside the body don't unbalance the count. Returns null when unterminated.
+ */
+function findInterfaceEnd(source, from) {
+ let angleDepth = 0;
+ let braceDepth = 0;
+ let inBody = false;
+ let i = from;
+ while (i < source.length) {
+ const c = source[i];
+ if (c === "'" || c === '"' || c === '`') {
+ i = skipString(source, i);
+ continue;
+ }
+ if (c === '/' && (source[i + 1] === '/' || source[i + 1] === '*')) {
+ i = skipComment(source, i);
+ continue;
+ }
+ if (!inBody) {
+ if (c === '<') angleDepth++;
+ else if (c === '>' && source[i - 1] !== '=') angleDepth--;
+ else if (c === '{' && angleDepth === 0) inBody = true;
+ if (inBody) braceDepth = 1;
+ } else if (c === '{') {
+ braceDepth++;
+ } else if (c === '}') {
+ braceDepth--;
+ if (braceDepth === 0) {
+ return i + 1;
+ }
+ }
+ i++;
+ }
+ return null;
+}
+
+/**
+ * Find the end (exclusive) of a `type` alias: the first `;` at bracket depth
+ * zero. `=>` is treated as a unit so arrow return types don't unbalance the
+ * angle-bracket count. Returns null when unterminated.
+ */
+function findTypeAliasEnd(source, from) {
+ let depth = 0;
+ let i = from;
+ while (i < source.length) {
+ const c = source[i];
+ if (c === "'" || c === '"' || c === '`') {
+ i = skipString(source, i);
+ continue;
+ }
+ if (c === '/' && (source[i + 1] === '/' || source[i + 1] === '*')) {
+ i = skipComment(source, i);
+ continue;
+ }
+ if (c === '{' || c === '(' || c === '[' || c === '<') {
+ depth++;
+ } else if (c === '}' || c === ')' || c === ']') {
+ depth--;
+ } else if (c === '>' && source[i - 1] !== '=') {
+ depth--;
+ } else if (c === ';' && depth === 0) {
+ return i + 1;
+ }
+ i++;
+ }
+ return null;
+}
+
+/**
+ * Extract every exported `interface` / `type` declaration from a TypeScript
+ * source string. The declaration text starts at `export` (leading JSDoc is
+ * excluded — field-level comments inside interface bodies are kept, which is
+ * where the useful documentation lives) and includes the full body.
+ *
+ * @param {string} source TypeScript source text
+ * @returns {Array<{name: string, kind: 'interface' | 'type', definition: string}>}
+ */
+export function extractTypeDeclarations(source) {
+ const declarations = [];
+ EXPORTED_DECL_RE.lastIndex = 0;
+ let m;
+ while ((m = EXPORTED_DECL_RE.exec(source)) !== null) {
+ const kind = m[1];
+ const end =
+ kind === 'interface'
+ ? findInterfaceEnd(source, EXPORTED_DECL_RE.lastIndex)
+ : findTypeAliasEnd(source, EXPORTED_DECL_RE.lastIndex);
+ if (end == null) continue;
+ declarations.push({
+ name: m[2],
+ kind,
+ definition: source.slice(m.index, end).trim(),
+ });
+ }
+ return declarations;
+}
+
+function findSourceFilesRecursive(dir) {
+ const results = [];
+ if (!fs.existsSync(dir)) return results;
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === '__tests__' || entry.name === 'node_modules') continue;
+ results.push(...findSourceFilesRecursive(full));
+ } else if (
+ /\.tsx?$/.test(entry.name) &&
+ !entry.name.endsWith('.d.ts') &&
+ !/\.test\.tsx?$/.test(entry.name)
+ ) {
+ results.push(full);
+ }
+ }
+ return results;
+}
+
+/**
+ * Build an index of every exported type declaration in a package's src/
+ * directory. Files are visited in sorted order and the first declaration of
+ * a name wins, so the output is deterministic.
+ *
+ * @param {string} srcDir Absolute path to the package's src/ directory
+ * @param {string} srcDirLabel Repo-relative label for srcDir, used as the
+ * sourcePath prefix (e.g. `packages/core/src`)
+ * @returns {Map<string, {name: string, definition: string, sourcePath: string}>}
+ */
+export function buildTypeDefinitionIndex(srcDir, srcDirLabel) {
+ const index = new Map();
+ const files = findSourceFilesRecursive(srcDir).sort();
+ for (const file of files) {
+ const source = fs.readFileSync(file, 'utf-8');
+ for (const decl of extractTypeDeclarations(source)) {
+ if (index.has(decl.name)) continue;
+ // Aliases like `export type StyleXStyles = any;` are compat shims with
+ // no shape to surface — inspecting them would only show `any`.
+ if (/=\s*(?:any|unknown)\s*;$/.test(decl.definition)) continue;
+ index.set(decl.name, {
+ name: decl.name,
+ definition: decl.definition,
+ sourcePath: path.posix.join(
+ srcDirLabel.split(path.sep).join('/'),
+ path.relative(srcDir, file).split(path.sep).join('/'),
+ ),
+ });
+ }
+ }
+ return index;
+}
+
+/**
+ * Resolve the named types a documented prop type string references against
+ * an index built by {@link buildTypeDefinitionIndex}. `*Props` interfaces
+ * are excluded — component prop surfaces are documented by their own pages,
+ * not inlined into another component's props table.
+ *
+ * @param {string} typeStr Documented prop type, e.g. `SearchSource<T>`
+ * @param {Map<string, {name: string, definition: string, sourcePath: string}>} index
+ * @returns {string[]} Referenced type names present in the index
+ */
+export function collectPropTypeRefs(typeStr, index) {
+ const refs = [];
+ for (const m of typeStr.matchAll(/\b[A-Z][\w$]*\b/g)) {
+ const name = m[0];
+ if (name.endsWith('Props')) continue;
+ if (!index.has(name)) continue;
+ if (!refs.includes(name)) refs.push(name);
+ }
+ return refs;
+}