MUI Docs Infra

Warning

This is an internal project, and is not intended for public use. No support or stability guarantees are provided.

Load Server Types Meta

The core server-side function for loading and formatting TypeScript type metadata. This function extracts types from your source files and returns formatted data ready for documentation generation or rendering.


Overview

loadServerTypesMeta handles the TypeScript → formatted types pipeline:

  • Loads TypeScript configuration
  • Resolves library source files and variants
  • Finds meta files (DataAttributes, CssVars)
  • Processes types via worker thread
  • Formats component, hook, function, class, and raw types
  • Collects external types referenced in props/params
  • Groups types by component when applicable

This function is separated from syncTypes to allow direct access to formatted types without markdown generation. Use this when you need type metadata but don't need to write a types.md file.

Note: Type highlighting is handled separately by loadServerTypes, which calls syncTypes (which uses this function) and then applies highlightTypes and highlightTypesMeta to convert plain text types to syntax-highlighted HAST.


Usage

Basic Usage

import { loadServerTypesMeta } from '@mui/internal-docs-infra/pipeline/loadServerTypesMeta';

// Load and format types (no file writing)
const result = await loadServerTypesMeta({
  typesMarkdownPath: '/absolute/path/to/types.md',
  rootContext: '/absolute/path/to/project',
  variants: { Default: '@base-ui/react/checkbox' },
  formattingOptions: {
    shortTypeUnionPrintWidth: 40,
    defaultValueUnionPrintWidth: 40,
  },
});

// Use the results
console.log(result.allTypes); // TypesMeta[] - all formatted types
console.log(result.variantData); // Record<string, { types: TypesMeta[]; typeNameMap?: Record<string, string> }>
console.log(result.allDependencies); // string[] - files to watch
console.log(result.externalTypes); // Record<string, string> - external type definitions
console.log(result.resourceName); // string - derived name for display

With Custom Socket Directory

const result = await loadServerTypesMeta({
  typesMarkdownPath: '/absolute/path/to/types.md',
  rootContext: '/absolute/path/to/project',
  variants: { Default: '@base-ui/react/checkbox' },
  socketDir: '/tmp/my-custom-socket-dir', // For Windows compatibility
});

With External Types Pattern

const result = await loadServerTypesMeta({
  typesMarkdownPath: '/absolute/path/to/types.md',
  rootContext: '/absolute/path/to/project',
  variants: { Default: '@base-ui/react/checkbox' },
  // Only include specific external types
  externalTypesPattern: '^(Orientation|Alignment|Side)$',
});

Processing Pipeline

1. Load TypeScript Configuration

Loads and caches tsconfig.json from the root context:

const config = await loadTypescriptConfig(path.join(rootContext, 'tsconfig.json'));

2. Resolve Library Source Files

Resolves variant paths through tsconfig paths, handling:

  • Relative paths
  • Path aliases (e.g., @base-ui/react/*)
  • External libraries with source maps

3. Find Meta Files

Automatically discovers DataAttributes.ts and CssVars.ts files from:

  • Entrypoint directories
  • Re-exported directories (from relative exports like ../menu/)
const metaFiles = await findMetaFiles(componentDirectory);
// Returns: ['CheckboxDataAttributes.ts', 'CheckboxCssVars.ts']

4. Process Types in Worker

Sends type extraction work to a dedicated worker thread:

const workerResult = await workerManager.processTypes({
  projectPath: config.projectPath,
  compilerOptions: config.options,
  allEntrypoints,
  metaFiles,
  resolvedVariantMap,
  dependencies: config.dependencies,
  rootContextDir,
  relativePath,
});

5. Format Types

Converts raw TypeScript exports to formatted structures based on type:

  • Components: formatComponentData - extracts props, data attributes, CSS variables
  • Hooks: formatHookData - extracts parameters, return value
  • Functions: formatFunctionData - extracts parameters, return value
  • Classes: formatClassData - extracts properties, methods
  • Raw types: formatRawData - formats type declaration

6. Group by Component (when applicable)

For single-variant exports with sub-components (e.g., Accordion.Root, Accordion.Trigger), groups types by component:

// Before: { Default: { types: [Accordion.Root, Accordion.Trigger, ...] } }
// After: { "Accordion.Root": { types: [...] }, "Accordion.Trigger": { types: [...] } }

7. Detect Re-exports

Identifies when type exports (like ButtonProps) are just re-exports of component props:

// ButtonProps → marks as re-export of Button#props
// CheckboxDataAttributes → marks as re-export of Checkbox#data-attributes

8. Collect External Types

Gathers types referenced in props/params that aren't publicly exported:

// e.g., Orientation = 'horizontal' | 'vertical'
// These are collected and returned in externalTypes

Worker Architecture

The function uses a worker-based architecture for efficient TypeScript processing:

Main Thread Responsibilities

  • Loading TypeScript configuration
  • Path resolution
  • Formatting types
  • Coordinating worker communication

Worker Thread Responsibilities

  • Creating/caching TypeScript program
  • Parsing exports with typescript-api-extractor
  • Managing file cache
  • Tracking dependencies

Socket-Based IPC

For multi-process environments (Next.js with multiple workers):

  • First worker becomes the "server" and holds the TypeScript language service
  • Other workers connect as "clients" via Unix socket
  • All workers share a single TypeScript program instance

Performance

First Request

~500-1200ms to create TypeScript program and parse types

Subsequent Requests

~100-140ms using cached program and file data

Multi-Process Improvement

87-92% performance improvement vs. creating separate language services per process


Comparison with Related Functions

FunctionPurposeWrites FilesReturns
loadServerTypesMetaLoad & format typesPlain text types
syncTypesSync types.md file✅ types.mdPlain text types + exports structure
loadServerTypesFull pipeline with highlighting✅ types.mdHAST-highlighted types

Types

loadServerTypesMeta

loadServerTypesMeta

Loads and formats TypeScript types from source files.

This function handles:

  • Loading TypeScript configuration
  • Resolving library source files and variants
  • Finding meta files (DataAttributes, CssVars)
  • Processing types via worker thread
  • Formatting component, hook, function, and raw types
  • Collecting external types referenced in props/params

The result can be used by syncTypes for markdown generation or by other consumers.

ParameterTypeDescription
options{ typesMarkdownPath: string; rootContext: string; variants?: Record<string, string>; watchSourceDirectly?: boolean; formattingOptions?: FormatInlineTypeOptions; socketDir?: string; externalTypesPattern?: string }
Return Type

prettyFormat

prettyFormat
ParameterTypeDescription
typestring
typeNamestring | null | undefined
printWidthnumber | undefined
Return Type
Promise<string>

prettyFormatMarkdown

prettyFormatMarkdown

Formats a markdown string with Prettier’s markdown parser. Used for non-code sections of generated markdown to ensure consistent formatting.

ParameterTypeDescription
markdownstring

The markdown string to format

printWidthnumber | undefined

Optional maximum line width for Prettier formatting (default: 100)

Return Type
Promise<string>

The formatted markdown string

Additional Types

ClassFormattedProperty

Formatted property metadata for class properties.

type ClassFormattedProperty = {
  name: string;
  typeText: string;
  description?: HastRoot;
  descriptionText?: string;
  optional: boolean;
  readonly: boolean;
  isStatic: boolean;
};
ClassTypeMeta
type ClassTypeMeta = {
  name: string;
  description?: HastRoot;
  descriptionText?: string;
  constructorParameters: Record<string, FormattedParameter>;
  properties: Record<string, FormattedProperty>;
  methods: Record<string, FormattedMethod>;
  typeParameters?: string[];
};
ComponentTypeMeta
type ComponentTypeMeta = {
  name: string;
  description?: HastRoot;
  descriptionText?: string;
  props: Record<string, FormattedProperty>;
  dataAttributes: Record<string, FormattedEnumMember>;
  cssVariables: Record<string, FormattedEnumMember>;
};
EnumMemberMeta

Enum member metadata for raw type enum rendering.

type EnumMemberMeta = {
  name: string;
  value?: string | number;
  description?: HastRoot;
  descriptionText?: string;
};
FormatInlineTypeOptions

Options for formatting inline types as HAST.

type FormatInlineTypeOptions = {
  shortTypeUnionPrintWidth?: number;
  defaultValueUnionPrintWidth?: number;
  detailedTypePrintWidth?: number;
};
FormattedEnumMember
type FormattedEnumMember = { description?: Root; descriptionText?: string; type?: string };
FormattedMethod

Formatted method metadata for class methods.

type FormattedMethod = {
  name: string;
  description?: HastRoot;
  descriptionText?: string;
  parameters: Record<string, FormattedParameter>;
  returnValue: string;
  returnValueDescription?: HastRoot;
  returnValueDescriptionText?: string;
  isStatic: boolean;
};
FormattedParameter
type FormattedParameter = {
  typeText: string;
  defaultText?: string;
  optional?: true;
  description?: Root;
  descriptionText?: string;
  example?: Root;
  exampleText?: string;
  see?: Root;
  seeText?: string;
};
FormattedProperty
type FormattedProperty = {
  typeText: string;
  defaultText?: string;
  required?: true;
  description?: Root;
  descriptionText?: string;
  example?: Root;
  exampleText?: string;
  see?: Root;
  seeText?: string;
};
FunctionTypeMeta
type FunctionTypeMeta = {
  name: string;
  description?: HastRoot;
  descriptionText?: string;
  parameters: Record<string, FormattedParameter>;
  returnValue: Record<string, FormattedProperty> | string;
  returnValueText?: string;
  returnValueDescription?: HastRoot;
  returnValueDescriptionText?: string;
};
HookTypeMeta
type HookTypeMeta = {
  name: string;
  description?: HastRoot;
  descriptionText?: string;
  parameters: Record<string, FormattedParameter | FormattedProperty>;
  returnValue: Record<string, FormattedProperty> | string;
  returnValueText?: string;
  returnValueDescription?: HastRoot;
  returnValueDescriptionText?: string;
};
LoadServerTypesMetaOptions
type LoadServerTypesMetaOptions = {
  typesMarkdownPath: string;
  rootContext: string;
  variants?: Record<string, string>;
  watchSourceDirectly?: boolean;
  formattingOptions?: FormatInlineTypeOptions;
  socketDir?: string;
  externalTypesPattern?: string;
};
LoadServerTypesMetaResult
type LoadServerTypesMetaResult = {
  allDependencies: string[];
  typeNameMap?: Record<string, string>;
  externalTypes: Record<string, string>;
  resourceName: string;
  exports: Record<string, { type: TypesMeta; additionalTypes: TypesMeta[] }>;
  additionalTypes: TypesMeta[];
  variantTypeNames: Record<string, string[]>;
  variantTypeNameMaps: Record<string, Record<string, string>>;
};
namespaceParts
type namespaceParts = string[];
RawTypeMeta
type RawTypeMeta = {
  name: string;
  description?: HastRoot;
  descriptionText?: string;
  formattedCode: string;
  enumMembers?: EnumMemberMeta[];
  reExportOf?: ReExportInfo;
  dataAttributesOf?: string;
  cssVarsOf?: string;
};
ReExportInfo
type ReExportInfo = {
  name: string;
  slug: string;
  suffix: 'props' | 'css-variables' | 'data-attributes';
};
TypesMeta
type TypesMeta =
  | { type: 'class'; name: string; slug?: string; data: ClassTypeMeta }
  | { type: 'component'; name: string; slug?: string; data: ComponentTypeMeta }
  | { type: 'hook'; name: string; slug?: string; data: HookTypeMeta }
  | { type: 'function'; name: string; slug?: string; data: FunctionTypeMeta }
  | { type: 'raw'; name: string; slug?: string; data: RawTypeMeta };
typeSuffixes
type typeSuffixes = string[];

Related