#!/usr/bin/env node import * as babel from '@babel/parser'; import {fileURLToPath} from 'url'; import fs from 'fs'; import glob from 'fast-glob'; import {mdxToMarkdown} from 'mdast-util-mdx'; import path from 'path'; import {Project} from 'ts-morph'; import remarkMdx from 'remark-mdx'; import remarkParse from 'remark-parse'; import {toMarkdown} from 'mdast-util-to-markdown'; import {unified} from 'unified'; import {visit} from 'unist-util-visit'; const BASE_URL = { dev: { 'react-aria': 'http://localhost:1234', s2: 'http://localhost:4321' }, stage: { 'react-aria': 'https://d5iwopk28bdhl.cloudfront.net', s2: 'https://d1pzu54gtk2aed.cloudfront.net' }, prod: { 'react-aria': 'https://react-aria.adobe.com', s2: 'https://react-spectrum.adobe.com' } }; function getBaseUrl(library) { let env = process.env.DOCS_ENV; let base = env ? BASE_URL[env][library] : `http://localhost:1234/${library}`; let publicUrl = process.env.PUBLIC_URL; if (publicUrl) { base += publicUrl.replace(/\/$/, ''); } return base; } const __dirname = path.dirname(fileURLToPath(import.meta.url)); const REPO_ROOT = path.resolve(__dirname, '../../../../'); const S2_SRC_ROOT = path.join(REPO_ROOT, 'packages/@react-spectrum/s2/src'); const S2_STYLE_ROOT = path.join(REPO_ROOT, 'packages/@react-spectrum/s2/style'); const RAC_SRC_ROOT = path.join(REPO_ROOT, 'packages/react-aria-components/src'); const INTL_SRC_ROOT = path.join(REPO_ROOT, 'packages/@internationalized'); const COMPONENT_SRC_ROOTS = [S2_SRC_ROOT, RAC_SRC_ROOT, INTL_SRC_ROOT]; const S2_DOCS_PAGES_ROOT = path.join(REPO_ROOT, 'packages/dev/s2-docs/pages'); const DIST_ROOT = path.join(REPO_ROOT, 'packages/dev/s2-docs/dist'); const LICENSE_COMMENT_REGEX = /^\s*\{\/\*[\s\S]*?Copyright\s+20\d{2}\s+Adobe[\s\S]*?\*\/\}\s*/; const ROUTERS_MDX_PATH = path.join(REPO_ROOT, 'packages/dev/s2-docs/src/routers-s2.mdx'); const ROUTERS_PLACEHOLDER_REGEX = //g; let routersMdxCache = null; function getRoutersMdxContent() { if (routersMdxCache == null) { let contents = fs.readFileSync(ROUTERS_MDX_PATH, 'utf8').replace(LICENSE_COMMENT_REGEX, ''); contents = contents.replace(/^\s*(?:import|export)\s[^\n]*(?:\n|$)/gm, ''); routersMdxCache = contents.trim(); } return routersMdxCache; } const S2_ICON_ROOT = path.join(REPO_ROOT, 'packages/@react-spectrum/s2/s2wf-icons'); const S2_ILLUSTRATION_ROOT = path.join( REPO_ROOT, 'packages/@react-spectrum/s2/spectrum-illustrations' ); let iconNamesCache = null; let illustrationNamesCache = null; // Pre-load a ts-morph project so we can query type information. const project = new Project({ tsConfigFilePath: path.join(REPO_ROOT, 'tsconfig.json'), skipAddingFilesFromTsConfig: true }); const interfacePathCache = new Map(); const interfaceTableCache = new Map(); const classTableCache = new Map(); const propTableCache = new Map(); const descriptionCache = new Map(); const functionExamplesCache = new Map(); let tsFileIndex = null; let styleMacroDataCache = null; const styleMacroTableCache = new Map(); const styleMacroValueSetsInjected = new WeakSet(); // Values to render without surrounding string quotes const BARE_VALUE_TOKENS = new Set([ 'number', 'string', 'string[]', 'boolean', 'LinearGradient', 'true', 'false' ]); function getTsFileIndex() { if (tsFileIndex) { return tsFileIndex; } console.log('Building TypeScript file index...'); const startTime = Date.now(); // Index files from component roots and packages directory const patterns = [ ...COMPONENT_SRC_ROOTS.map(r => path.posix.join(r, '**/*.{ts,tsx,d.ts}')), path.posix.join(REPO_ROOT, 'packages/**/*.{ts,tsx,d.ts}') ]; const files = glob .sync(patterns, { absolute: true, suppressErrors: true, deep: 5, ignore: ['**/node_modules/**', '**/*.test.*', '**/*.stories.*', '**/dist/**'] }) .sort((a, b) => a.localeCompare(b)); // Build index: for each file, extract exported names for quick lookup tsFileIndex = new Map(); for (const filePath of files) { try { const content = fs.readFileSync(filePath, 'utf8'); // Extract interface/type/class/function/const names const interfaceMatches = content.matchAll(/(?:export\s+)?interface\s+(\w+)/g); const typeMatches = content.matchAll(/(?:export\s+)?type\s+(\w+)\s*[=<]/g); const classMatches = content.matchAll(/(?:export\s+)?class\s+(\w+)/g); const functionMatches = content.matchAll(/(?:export\s+)?function\s+(\w+)/g); const constMatches = content.matchAll(/(?:export\s+)?const\s+(\w+)\s*[=:]/g); for (const match of [ ...interfaceMatches, ...typeMatches, ...classMatches, ...functionMatches, ...constMatches ]) { const name = match[1]; if (!tsFileIndex.has(name)) { tsFileIndex.set(name, []); } // Avoid duplicates for the same file const existing = tsFileIndex.get(name); if (!existing.includes(filePath)) { existing.push(filePath); } } } catch { // Ignore files that can't be read } } console.log(`Built index with ${tsFileIndex.size} symbols in ${Date.now() - startTime}ms`); for (const candidates of tsFileIndex.values()) { candidates.sort((a, b) => a.localeCompare(b)); } return tsFileIndex; } /** * Clean type text by removing import statements and duplicate type parameters. */ function cleanTypeText(t) { // Remove import statements from type strings. let cleaned = t.replace(/import\(["'][^)]*["']\)\./g, ''); // Remove duplicate type parameters. cleaned = cleaned.replace(/<\s*([A-Za-z0-9_$.]+)\s*,\s*\1\s*>/g, '<$1>'); return normalizeTypeText(cleaned); } // TypeScript can emit union members in different orders across fresh projects. // Canonicalize unions while avoiding parameter lists and object type bodies. function findTopLevelArrow(text) { let depth = 0; let quote = null; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (quote) { if (ch === '\\') { i++; } else if (ch === quote) { quote = null; } continue; } if (ch === '"' || ch === "'" || ch === '`') { quote = ch; continue; } if (ch === '(' || ch === '[' || ch === '{' || ch === '<') { depth++; } else if (ch === ')' || ch === ']' || ch === '}' || ch === '>') { depth = Math.max(0, depth - 1); } else if (ch === '=' && text[i + 1] === '>' && depth === 0) { return i; } } return -1; } function findMatchingDelimiter(text, start) { const pairs = { '(': ')', '[': ']', '{': '}', '<': '>' }; const open = text[start]; const close = pairs[open]; if (!close) { return -1; } let depth = 0; let quote = null; for (let i = start; i < text.length; i++) { const ch = text[i]; if (quote) { if (ch === '\\') { i++; } else if (ch === quote) { quote = null; } continue; } if (ch === '"' || ch === "'" || ch === '`') { quote = ch; continue; } if (ch === open) { depth++; } else if (ch === close) { depth--; if (depth === 0) { return i; } } } return -1; } function normalizeNestedTypeText(text) { let out = ''; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (ch === '"' || ch === "'" || ch === '`') { const start = i; i++; while (i < text.length) { if (text[i] === '\\') { i += 2; continue; } if (text[i] === ch) { break; } i++; } out += text.slice(start, Math.min(i + 1, text.length)); continue; } if (ch === '(' || ch === '[' || ch === '{' || ch === '<') { const end = findMatchingDelimiter(text, i); if (end !== -1) { const nextText = text.slice(end + 1); const isFunctionParams = ch === '(' && /^\s*=>/.test(nextText); const inner = text.slice(i + 1, end); const normalizedInner = ch === '{' || isFunctionParams ? normalizeNestedTypeText(inner) : normalizeTypeText(inner); out += ch + normalizedInner + text[end]; i = end; continue; } } out += ch; } return out; } function splitTopLevelUnion(text) { const parts = []; let depth = 0; let quote = null; let start = 0; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (quote) { if (ch === '\\') { i++; } else if (ch === quote) { quote = null; } continue; } if (ch === '"' || ch === "'" || ch === '`') { quote = ch; continue; } if (ch === '(' || ch === '[' || ch === '{' || ch === '<') { depth++; } else if (ch === ')' || ch === ']' || ch === '}' || ch === '>') { depth = Math.max(0, depth - 1); } else if (ch === '|' && depth === 0) { parts.push(text.slice(start, i).trim()); start = i + 1; } } if (parts.length > 0) { parts.push(text.slice(start).trim()); } return parts; } function stringLiteralValue(text) { const match = text.match(/^(['"])(.*)\1$/); return match ? match[2] : null; } function unionSortKey(part) { const text = part.trim(); const primitiveOrder = new Map([ ['any', 0], ['unknown', 1], ['never', 2], ['void', 3], ['boolean', 4], ['number', 5], ['string', 6], ['symbol', 7], ['bigint', 8] ]); if (primitiveOrder.has(text)) { return [0, primitiveOrder.get(text), '']; } if (/^-?\d+(?:\.\d+)?$/.test(text)) { return [1, Number(text), '']; } const literal = stringLiteralValue(text); if (literal != null) { const booleanLiteralOrder = new Map([ ['true', 0], ['false', 1] ]); if (booleanLiteralOrder.has(literal)) { return [2, booleanLiteralOrder.get(literal), literal]; } return [2, 2, literal.toLowerCase()]; } if (text === 'null') { return [8, 0, '']; } if (text === 'undefined') { return [9, 0, '']; } return [3, 0, text.toLowerCase()]; } function compareUnionParts(a, b) { const aKey = unionSortKey(a); const bKey = unionSortKey(b); for (let i = 0; i < Math.max(aKey.length, bKey.length); i++) { if (aKey[i] < bKey[i]) { return -1; } if (aKey[i] > bKey[i]) { return 1; } } return a.localeCompare(b); } function sortUnionMembers(text) { const parts = splitTopLevelUnion(text); if (parts.length <= 1) { return text; } return parts.sort(compareUnionParts).join(' | '); } function normalizeTypeText(t) { const text = t.trim(); if (!text) { return text; } const normalized = normalizeNestedTypeText(text); const arrowIndex = findTopLevelArrow(normalized); if (arrowIndex >= 0) { const before = normalized.slice(0, arrowIndex + 2); const after = normalized.slice(arrowIndex + 2).trim(); return `${before} ${normalizeTypeText(after)}`; } return sortUnionMembers(normalized); } /** * Recursively evaluates a Babel AST node to extract its runtime value. * This function statically evaluates TS/JS expressions from the AST. * * Example: Given the AST for `const colors = ['red', ...baseColors]`, * this function would return ['red', 'green', 'blue'] if `baseColors` was * defined in scope as ['green', 'blue']. * * @param {object} node - A Babel AST node (StringLiteral, ArrayExpression, etc.) * @param {Map} scope - A Map of variable names to their evaluated values. * @returns {any} The evaluated value (string, number, array, object, Set, etc.) or undefined */ function evaluateStylePropertiesNode(node, scope) { if (!node) { return undefined; } switch (node.type) { // Primitive literals - return their direct values case 'StringLiteral': return node.value; case 'NumericLiteral': return node.value; case 'BooleanLiteral': return node.value; case 'NullLiteral': return null; // Variable references - look up the value in our scope Map // Example: if scope has {baseColors: ['green', 'blue']}, evaluating `baseColors` returns ['green', 'blue'] case 'Identifier': return scope.get(node.name); // Unary expressions like -5 or +10 case 'UnaryExpression': { const value = evaluateStylePropertiesNode(node.argument, scope); if (typeof value === 'number') { return node.operator === '-' ? -value : value; } return undefined; } // Array expressions like ['red', 'blue', ...otherColors] // Handles both regular elements and spread elements case 'ArrayExpression': { const values = []; for (const element of node.elements || []) { if (!element) { continue; } // Handle spread syntax: ...otherArray if (element.type === 'SpreadElement') { const spreadValue = evaluateStylePropertiesNode(element.argument, scope); if (Array.isArray(spreadValue)) { values.push(...spreadValue); } continue; } const value = evaluateStylePropertiesNode(element, scope); if (value !== undefined) { values.push(value); } } return values; } // Object expressions like {margin: ['0', '4', '8'], ...otherProps} // Handles both regular properties and spread properties case 'ObjectExpression': { const obj = {}; for (const prop of node.properties || []) { if (!prop) { continue; } // Handle spread syntax: ...otherObject if (prop.type === 'SpreadElement') { const spreadValue = evaluateStylePropertiesNode(prop.argument, scope); if (spreadValue && typeof spreadValue === 'object') { Object.assign(obj, spreadValue); } continue; } if (prop.type !== 'ObjectProperty') { continue; } const key = prop.key.type === 'Identifier' ? prop.key.name : prop.key.value; const value = evaluateStylePropertiesNode(prop.value, scope); if (key !== undefined) { obj[key] = value; } } return obj; } // Template literals like `color-${name}` // Preserves ${identifier} syntax for identifiers, evaluates other expressions case 'TemplateLiteral': { let output = ''; node.quasis.forEach((quasi, idx) => { output += quasi.value.cooked || ''; const expr = node.expressions?.[idx]; if (expr) { // Keep identifier placeholders as-is: ${varName} if (expr.type === 'Identifier') { output += `\${${expr.name}}`; } else { // Evaluate other expressions inline const exprValue = evaluateStylePropertiesNode(expr, scope); if (exprValue !== undefined) { output += String(exprValue); } } } }); return output; } // Constructor calls like `new Set(['a', 'b', 'c'])` // Currently only handles Set constructor case 'NewExpression': { const calleeName = node.callee?.type === 'Identifier' ? node.callee.name : ''; if (calleeName === 'Set') { const argValue = evaluateStylePropertiesNode(node.arguments?.[0], scope); return new Set(Array.isArray(argValue) ? argValue : []); } return undefined; } // TypeScript type assertions - unwrap and evaluate the inner expression // Examples: `value as string`, `value`, `value!` case 'TSAsExpression': case 'TSTypeAssertion': case 'TSNonNullExpression': return evaluateStylePropertiesNode(node.expression, scope); // Parenthesized expressions - unwrap and evaluate case 'ParenthesizedExpression': return evaluateStylePropertiesNode(node.expression, scope); default: return undefined; } } /** * Loads and parses the style macro configuration from styleProperties.ts. * This function reads the TypeScript source file, parses it into an AST using Babel, * and evaluates all variable declarations to extract style property metadata. * * The styleProperties.ts file contains definitions like: * const properties = { * spacing: { margin: ['0', '4', '8', '12'], padding: [...] }, * layout: { display: ['flex', 'grid', 'block'] } * } * * This function evaluates these declarations and returns a structured object with: * - properties: categorized style properties and their allowed values * - shorthandMapping: mappings from shorthand names to full property names * - mdnTypeLinks/mdnPropertyLinks: documentation URLs * - various Sets for property categorization (spacing, sizing, etc.) * * @returns {object | null} Parsed style macro data or null if file doesn't exist/parse fails */ function loadStyleMacroData() { if (styleMacroDataCache !== null) { return styleMacroDataCache; } const stylePropertiesPath = path.join(REPO_ROOT, 'packages/dev/s2-docs/src/styleProperties.ts'); if (!fs.existsSync(stylePropertiesPath)) { styleMacroDataCache = null; return null; } try { // Parse the TypeScript file into a Babel AST const content = fs.readFileSync(stylePropertiesPath, 'utf8'); const ast = babel.parse(content, { sourceType: 'module', plugins: ['typescript'] }); // Build a scope Map to store evaluated variable values // This allows later declarations to reference earlier ones const scope = new Map(); // Helper to evaluate and register a variable declaration // Example: const colors = ['red', 'blue'] => scope.set('colors', ['red', 'blue']) const registerDeclaration = decl => { if (!decl || decl.type !== 'VariableDeclarator') { return; } const id = decl.id; if (!id || id.type !== 'Identifier' || !decl.init) { return; } const value = evaluateStylePropertiesNode(decl.init, scope); scope.set(id.name, value); }; // Walk through all top-level declarations and evaluate them // Handles both: const x = ... and export const x = ... for (const node of ast.program.body || []) { if (node.type === 'VariableDeclaration') { node.declarations.forEach(registerDeclaration); continue; } if ( node.type === 'ExportNamedDeclaration' && node.declaration?.type === 'VariableDeclaration' ) { node.declaration.declarations.forEach(registerDeclaration); } } // Extract the specific variables we need for style macro documentation styleMacroDataCache = { properties: scope.get('properties') || {}, shorthandMapping: scope.get('shorthandMapping') || {}, mdnTypeLinks: scope.get('mdnTypeLinks') || {}, mdnPropertyLinks: scope.get('mdnPropertyLinks') || {}, propertyDescriptions: scope.get('propertyDescriptions') || {}, baseSpacingProperties: scope.get('baseSpacingProperties'), negativeSpacingProperties: scope.get('negativeSpacingProperties'), sizingProperties: scope.get('sizingProperties'), percentageProperties: scope.get('percentageProperties'), spacingTypeValues: scope.get('spacingTypeValues') || {}, propertyValueAlias: scope.get('propertyValueAlias') || {}, sharedValueSets: scope.get('sharedValueSets') || {} }; } catch { styleMacroDataCache = null; } return styleMacroDataCache; } /** * Extracts property definitions for a specific category from the loaded style macro data. * * Example: For category 'spacing', this returns an object like: * * { * margin: { * values: ['0', '4', '8', '12', '16'], * additionalTypes: ['baseSpacing', 'number'], * links: { '0': {href: 'https://...'} }, * description: 'Sets the margin on all sides' * }, * marginX: { * values: [...], * additionalTypes: [...], * links: {...}, * mapping: ['marginLeft', 'marginRight'], // for shorthands * description: 'Sets horizontal margins' * } * } * * @param {string} category - The property category (e.g., 'spacing', 'layout', 'colors') * @returns {object | null} Property definitions or null if category doesn't exist */ function getStyleMacroPropertyDefinitions(category) { const data = loadStyleMacroData(); if (!data?.properties?.[category]) { return null; } // Determine what additional type values a property accepts based on its classification // Example: spacing properties accept baseSpacing values like 0, 4, 8, 12, 16, etc. const getAdditionalTypes = propertyName => { const types = []; if (data.baseSpacingProperties?.has?.(propertyName)) { types.push('baseSpacing'); } if (data.negativeSpacingProperties?.has?.(propertyName)) { types.push('negativeSpacing'); } if (data.sizingProperties?.has?.(propertyName)) { types.push('number', 'lengthPercentage'); } if (data.percentageProperties?.has?.(propertyName)) { types.push('lengthPercentage'); } return Array.from(new Set(types)); }; const result = {}; const valueAliases = data.propertyValueAlias || {}; // Process regular properties (e.g., margin, padding, display) for (const [name, rawValues] of Object.entries(data.properties[category])) { let values = Array.isArray(rawValues) ? [...rawValues] : []; const links = {}; // If this property's values are a known shared set, collapse them to a // single alias and skip the rest of the per-value link processing. if (valueAliases[name]) { result[name] = { values: [], additionalTypes: [valueAliases[name], ...getAdditionalTypes(name)], links: {}, description: data.propertyDescriptions?.[name] }; continue; } // Add MDN documentation links for specific property values if (data.mdnPropertyLinks?.[name]) { for (const [key, href] of Object.entries(data.mdnPropertyLinks[name])) { links[key] = {href}; } } // If no explicit values but we have links, use link keys as values if (values.length === 0 && Object.keys(links).length > 0) { values = Object.keys(links); } // Add MDN type documentation links for generic type values (e.g., 'length', 'color') for (const value of values) { if (links[value]) { continue; // Already has a link } // Skip 'number' for sizing properties and 'pill' for non-dimension categories if ( (value === 'number' && data.sizingProperties?.has?.(name)) || (value === 'pill' && category !== 'dimensions') ) { continue; } if (data.mdnTypeLinks?.[value]) { links[value] = {href: data.mdnTypeLinks[value]}; } } result[name] = { values, additionalTypes: getAdditionalTypes(name), links, description: data.propertyDescriptions?.[name] }; } // Process shorthand properties (e.g., marginX, marginY) // Shorthands map to multiple full properties: marginX -> [marginLeft, marginRight] for (const [shorthandName, shorthandDef] of Object.entries(data.shorthandMapping || {})) { if (shorthandDef.category !== category) { continue; } let values = Array.isArray(shorthandDef.values) ? [...shorthandDef.values] : []; const links = {}; // Add MDN links for shorthand values for (const value of values) { if (value === 'pill' && shorthandName.includes('border')) { continue; } if (data.mdnTypeLinks?.[value]) { links[value] = {href: data.mdnTypeLinks[value]}; } } result[shorthandName] = { values, additionalTypes: getAdditionalTypes(shorthandDef.mapping?.[0]), links, mapping: shorthandDef.mapping, // Which full properties this shorthand controls description: data.propertyDescriptions?.[`${shorthandName}Shorthand`] }; } return result; } /** * Generates a markdown table documenting style macro properties and their allowed values. * * Rows with identical value sets are collapsed into a single row listing all matching * property names. Type categories (baseSpacing, negativeSpacing, etc.) are emitted as * aliases and defined once in the Value Sets section at the top of the page. * * The values column includes: * * - Explicit allowed values (e.g., '0', '4', '8') * - Type categories with their full value sets (e.g., 'baseSpacing (0, 4, 8, ...)') * - Generic types (e.g., 'number', 'lengthPercentage') * * Example output for a spacing-like category: * * | Property | Values | * | --------------------------------------------------------------------------------------- | ------------------------------------------------------------ | * | `margin`, `marginTop`, `marginBottom`, `marginStart`, `marginEnd`, `marginX`, `marginY` | `auto`, `baseSpacing`, `negativeSpacing`, `lengthPercentage` | * | `padding`, `paddingTop`, `paddingBottom`, ... | `text-to-control`, ..., `baseSpacing`, `lengthPercentage` | * * @param {string} category - Property category to generate table for (e.g., 'spacing', 'layout', * 'colors') * @param {object} options - Configuration options (e.g., {sort: true}) * @param {boolean} options.sort - Whether to sort properties alphabetically (default: true) * @returns {string | null} Markdown table string or null if no properties found */ function generateStyleMacroTable(category, {sort = true} = {}) { const cacheKey = `${category}:${sort ? 'sorted' : 'original'}`; if (styleMacroTableCache.has(cacheKey)) { return styleMacroTableCache.get(cacheKey); } const definitions = getStyleMacroPropertyDefinitions(category); if (!definitions) { styleMacroTableCache.set(cacheKey, null); return null; } let propertyNames = Object.keys(definitions); if (sort) { propertyNames.sort((a, b) => a.localeCompare(b)); } // Build the token list for a single property, combining explicit values and type aliases. // Type categories like `baseSpacing` are emitted as aliases; their full value sets // are documented once in the Value Sets section at the top of the page. const buildTokens = propertyName => { const def = definitions[propertyName] || {}; const values = Array.isArray(def.values) ? def.values : []; const additionalTypes = Array.isArray(def.additionalTypes) ? def.additionalTypes : []; const tokens = []; const seen = new Set(); const addToken = token => { if (!token || seen.has(token)) { return; } seen.add(token); tokens.push(token); }; const formatValue = value => { if (typeof value === 'number') { return `\`${value}\``; } const str = String(value); if (BARE_VALUE_TOKENS.has(str) || str.includes('${')) { return `\`${str}\``; } return `\`'${str}'\``; }; values.forEach(value => { if (value === undefined || value === null) { return; } addToken(formatValue(value)); }); additionalTypes.forEach(typeName => { if (!typeName) { return; } addToken(`\`${String(typeName)}\``); }); return tokens; }; // Group properties by identical token signatures so shared value sets collapse into one row. // Example: margin/marginTop/marginBottom/... all share the same tokens and merge to one row. const groups = new Map(); for (const name of propertyNames) { const tokens = buildTokens(name); const signature = tokens.join('\x1f'); let group = groups.get(signature); if (!group) { group = {names: [], tokens}; groups.set(signature, group); } group.names.push(name); } const rows = [...groups.values()].map(group => { const nameCell = group.names.map(n => `\`${n}\``).join(', '); const valueText = (group.tokens.length ? group.tokens.join(', ') : '—').replace(/\|/g, '\\|'); return `| ${nameCell} | ${valueText} |`; }); if (!rows.length) { styleMacroTableCache.set(cacheKey, null); return null; } const header = '| Property | Values |'; const separator = '|---------|--------|'; const table = `${header}\n${separator}\n${rows.join('\n')}`; styleMacroTableCache.set(cacheKey, table); return table; } /** * Generates the "Value sets" markdown section that defines the named aliases * (baseSpacing, negativeSpacing, baseColors) and the generic type names * (lengthPercentage, number, LinearGradient) referenced throughout the property tables. * * Injected once on the page so the tables below can reference these names * by alias instead of repeating their full value lists on every row. * * @returns {string | null} Markdown section string. */ function generateValueSetsMarkdown() { const data = loadStyleMacroData(); if (!data) { return null; } const formatSetValue = v => (typeof v === 'number' ? `\`${v}\`` : `\`'${v}'\``); const baseSpacing = Array.isArray(data.spacingTypeValues?.baseSpacing) ? data.spacingTypeValues.baseSpacing.map(formatSetValue).join(', ') : ''; const negativeSpacing = Array.isArray(data.spacingTypeValues?.negativeSpacing) ? data.spacingTypeValues.negativeSpacing.map(formatSetValue).join(', ') : ''; const lines = [ '## Value sets', '', 'The named sets below are referenced throughout the property tables.', 'Aliases like `baseSpacing` stand in for their full value list rather than being repeated on every row.', '', `- **\`baseSpacing\`** — ${baseSpacing}`, `- **\`negativeSpacing\`** — negative counterparts of \`baseSpacing\` (${negativeSpacing})`, '- **`baseColors`** — every Spectrum 2 color token. Includes `transparent`, `black`, `white`; the numeric scales `gray-25`–`gray-1000` and `blue`/`red`/`orange`/`yellow`/`chartreuse`/`celery`/`green`/`seafoam`/`cyan`/`indigo`/`purple`/`fuchsia`/`magenta`/`pink`/`turquoise`/`brown`/`silver`/`cinnamon` at steps `100`–`1600`; the semantic scales `accent-100`–`accent-1600`, `informative-*`, `negative-*`, `notice-*`, `positive-*`; the `transparent-white-*` and `transparent-black-*` scales; overlay colors; and high-contrast-mode system colors (`ButtonFace`, `ButtonText`, `Field`, `Highlight`, `HighlightText`, `GrayText`, `Mark`, `LinkText`, `Background`, `ButtonBorder`).', "- **`lengthPercentage`** — a CSS `` string, e.g. `'100px'`, `'50%'`, `'1.25rem'`.", '- **`number`** — a unitless numeric value. Meaning is context-dependent: for sizing / inset / margin / padding properties it is a pixel count (scaled via the Spectrum size factor); for `opacity`, `flexGrow`, `flexShrink`, `order`, `zIndex`, `lineClamp`, etc. it is passed through as-is.', "- **`LinearGradient`** — the object produced by the `linearGradient` helper, e.g. `linearGradient('to bottom', ['gray-25', 0], ['gray-200', 100])`. Used by `backgroundImage`." ]; // Append shared value-set aliases (e.g. positionKeywords) used by more than one property. const sharedSets = data.sharedValueSets || {}; for (const [alias, values] of Object.entries(sharedSets)) { if (!Array.isArray(values) || !values.length) { continue; } const formatted = values.map(formatSetValue).join(', '); lines.push(`- **\`${alias}\`** — ${formatted}`); } return lines.join('\n'); } /** * Get type text from a declaration, preferring the type node (AST) over the resolved type. */ function getTypeText(decl, fallbackContext) { // Try to get the type node first (preserves declaration order) const typeNode = decl?.getTypeNode?.(); if (typeNode) { return cleanTypeText(typeNode.getText()); } // Fall back to resolved type with context const type = decl?.getType?.(); if (type && fallbackContext) { return cleanTypeText(type.getText(fallbackContext)); } if (type) { return cleanTypeText(type.getText()); } return 'unknown'; } /** * Resolve the `s2:` and `react-aria:` cross-library URL schemes (used to link from one * doc site to another, e.g. from an S2 component page to its React Aria counterpart) * into an absolute URL on the target site. Other URLs are returned unchanged. */ function resolveSchemeUrl(href) { if (href && (href.startsWith('s2:') || href.startsWith('react-aria:'))) { const url = new URL(href); return getBaseUrl(url.protocol.slice(0, -1)) + '/' + url.pathname; } return href; } const URI_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*:/; /** * Transform relative URLs to use .md extension instead of .html or no extension. * Preserves query params and hash fragments. */ function transformRelativeUrl(href) { if (!href || href.startsWith('#') || URI_SCHEME_PATTERN.test(href)) { return href; } // Split href into path and query/hash parts const match = href.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/); if (!match) { return href; } let [, pathPart, queryPart = '', hashPart = ''] = match; if (pathPart.endsWith('.html')) { // Replace .html with .md pathPart = pathPart.slice(0, -5) + '.md'; } else if (pathPart.endsWith('/')) { // A trailing slash refers to that directory's index page pathPart = pathPart + 'index.md'; } else if (pathPart && !pathPart.match(/\.[a-zA-Z0-9]+$/)) { // Add .md to paths without an extension pathPart = pathPart + '.md'; } return pathPart + queryPart + hashPart; } function getIconNames() { if (iconNamesCache) { return iconNamesCache; } try { const files = fs.readdirSync(S2_ICON_ROOT); const names = new Set(); for (const fileName of files) { if (!fileName.toLowerCase().endsWith('.svg')) { continue; } const normalized = fileName.replace(/^S2_Icon_(.*?)(Size\d+)?_2.*/, '$1'); const cleaned = normalized.trim(); if (cleaned) { names.add(cleaned); } } iconNamesCache = Array.from(names).sort((a, b) => a.localeCompare(b)); } catch { iconNamesCache = []; } return iconNamesCache; } function getIllustrationNames() { if (illustrationNamesCache) { return illustrationNamesCache; } try { const names = new Set(); const directories = ['linear', 'gradient/generic1', 'gradient/generic2']; for (const dir of directories) { const illustrationPath = path.join(S2_ILLUSTRATION_ROOT, dir); if (!fs.existsSync(illustrationPath)) { continue; } const files = fs.readdirSync(illustrationPath); for (const fileName of files) { if (fileName.endsWith('.tsx')) { // Extract name without extension const name = fileName.replace(/\.tsx$/, ''); names.add(name); } } } illustrationNamesCache = Array.from(names).sort((a, b) => a.localeCompare(b)); } catch { illustrationNamesCache = []; } return illustrationNamesCache; } function parseExpression(expr, file) { try { const ast = babel.parse(expr, { sourceType: 'module', plugins: ['jsx', 'typescript'] }); if (ast.program.body.length > 0 && ast.program.body[0].type === 'ExpressionStatement') { return evaluateNode(ast.program.body[0].expression, file); } return null; } catch { return null; } } function evaluateNode(node, file) { if (!node) { return null; } switch (node.type) { case 'StringLiteral': return node.value; case 'NumericLiteral': return node.value; case 'BooleanLiteral': return node.value; case 'NullLiteral': return null; case 'ArrayExpression': return node.elements.map(el => evaluateNode(el, file)).filter(v => v !== null); case 'ObjectExpression': { const obj = {}; for (const prop of node.properties) { if (prop.type === 'ObjectProperty') { const key = prop.key.type === 'Identifier' ? prop.key.name : evaluateNode(prop.key, file); obj[key] = evaluateNode(prop.value, file); } } return obj; } case 'Identifier': // For identifiers, return the name as a string return node.name; case 'JSXElement': case 'JSXFragment': { // For JSX elements, extract text content return extractJSXText(node, file); } case 'JSXText': return node.value; case 'MemberExpression': { // Handle member expressions like docs.exports.GregorianCalendar.description const object = evaluateNode(node.object, file); const property = node.computed ? evaluateNode(node.property, file) : node.property.name || node.property.value; return `${object}.${property}`; } default: return null; } } function extractTypeLinkName(node) { const typeAttr = node.openingElement?.attributes?.find( attr => attr.type === 'JSXAttribute' && attr.name?.name === 'type' ); if (!typeAttr || typeAttr.value?.type !== 'JSXExpressionContainer') { return ''; } const expr = typeAttr.value.expression; if (expr.type !== 'MemberExpression') { return ''; } // Extract the last property name (e.g., GregorianCalendar from docs.exports.GregorianCalendar) return expr.property?.name || ''; } function extractDescriptionFromExpression(node, file) { if (node.type !== 'MemberExpression') { return null; } // Check if the outermost property is "description" if (node.property?.name !== 'description') { return null; } // Now check if the object is a member expression with pattern: *.exports.ComponentName const obj = node.object; if (obj?.type !== 'MemberExpression') { return null; } // Get the component name (the rightmost property before .description) const componentName = obj.property?.name; // Check if the parent is .exports if ( obj.object?.type === 'MemberExpression' && obj.object.property?.name === 'exports' && componentName && file ) { const desc = getComponentDescription(componentName, file); return desc; } return null; } function extractJSXText(node, file) { if (!node) { return ''; } // Handle JSXElement if (node.type === 'JSXElement') { const elementName = node.openingElement?.name?.name; // For TypeLink, try to extract the type name if (elementName === 'TypeLink') { return extractTypeLinkName(node); } // For other elements like

, extract children text if (node.children) { return node.children .map(child => extractJSXText(child, file)) .filter(text => text && text.trim()) .join(''); } } // Handle JSXText if (node.type === 'JSXText') { return node.value.trim(); } // Handle JSXExpressionContainer if (node.type === 'JSXExpressionContainer') { const desc = extractDescriptionFromExpression(node.expression, file); if (desc) { return desc; } if (node.expression.type === 'MemberExpression') { return '[description]'; } return evaluateNode(node.expression, file) || ''; } // Handle JSXFragment if (node.type === 'JSXFragment') { if (node.children) { return node.children .map(child => extractJSXText(child, file)) .filter(text => text && text.trim()) .join(''); } } return ''; } function getCacheKey(name, file) { if (file?.path) { if (file.path.includes(path.join('pages', 'react-aria', 'internationalized'))) { return `intl:${name}`; } else if (file.path.includes(path.join('pages', 'react-aria'))) { return `rac:${name}`; } else if (file.path.includes(path.join('pages', 's2'))) { return `s2:${name}`; } } return `default:${name}`; } function getDocsImportSource(identifier, file) { return file?.data?.docsImports?.[identifier] || null; } function getExistingRoots(roots) { return [...new Set(roots.filter(root => root && fs.existsSync(root)))]; } function getRootsForDocsSource(docsSource, file) { if (!docsSource) { return null; } if (docsSource === '@react-spectrum/s2') { return getExistingRoots([S2_SRC_ROOT, S2_STYLE_ROOT]); } if (docsSource === '@react-spectrum/s2/style') { return getExistingRoots([S2_STYLE_ROOT]); } if (docsSource.startsWith('./') || docsSource.startsWith('../')) { if (!file?.path) { return null; } const resolved = path.resolve(path.dirname(file.path), docsSource); const candidates = [ resolved, `${resolved}.ts`, `${resolved}.tsx`, `${resolved}.d.ts`, path.join(resolved, 'index.ts'), path.join(resolved, 'index.tsx'), path.join(resolved, 'index.d.ts') ]; return getExistingRoots( candidates.map(candidate => { if (!fs.existsSync(candidate)) { return null; } return fs.statSync(candidate).isDirectory() ? candidate : path.dirname(candidate); }) ); } const packagePath = path.join(REPO_ROOT, 'packages', docsSource); if (fs.existsSync(packagePath)) { if (fs.statSync(packagePath).isDirectory()) { return getExistingRoots([path.join(packagePath, 'src'), packagePath]); } return getExistingRoots([path.dirname(packagePath)]); } return null; } function getRootsForFile(file, docsSource) { const docsRoots = getRootsForDocsSource(docsSource, file); if (docsRoots?.length) { return docsRoots; } if (file?.path) { if (file.path.includes(path.join('pages', 'react-aria', 'internationalized'))) { return [INTL_SRC_ROOT, S2_SRC_ROOT, RAC_SRC_ROOT]; } else if (file.path.includes(path.join('pages', 'react-aria'))) { return [RAC_SRC_ROOT, S2_SRC_ROOT, INTL_SRC_ROOT]; } } return COMPONENT_SRC_ROOTS; } function resolveComponentPath(componentName, file, docsSource) { // Check unified cache first const cacheKey = getCacheKey(`${docsSource || 'default'}:${componentName}:path`, file); if (interfacePathCache.has(cacheKey)) { return interfacePathCache.get(cacheKey); } let roots = getRootsForFile(file, docsSource); // Fast path: check direct file paths first for (let root of roots) { for (let ext of ['tsx', 'ts']) { const candidate = path.join(root, `${componentName}.${ext}`); if (fs.existsSync(candidate)) { interfacePathCache.set(cacheKey, candidate); return candidate; } } } // Use pre-built index for fast lookup const index = getTsFileIndex(); const candidates = index.get(componentName); if (candidates && candidates.length > 0) { // Prefer files in the priority roots for (const root of roots) { const match = candidates.find(p => p.startsWith(root)); if (match) { interfacePathCache.set(cacheKey, match); return match; } } // Prefer .d.ts files over implementation files const dtsMatch = candidates.find(p => p.endsWith('.d.ts')); if (dtsMatch) { interfacePathCache.set(cacheKey, dtsMatch); return dtsMatch; } // Prefer @react-types package for type lookups const typesMatch = candidates.find(p => p.includes('@react-types')); if (typesMatch) { interfacePathCache.set(cacheKey, typesMatch); return typesMatch; } // Fall back to first match interfacePathCache.set(cacheKey, candidates[0]); return candidates[0]; } interfacePathCache.set(cacheKey, null); return null; } /** * Extract the leading JSDoc description comment placed immediately above the export for a * component. */ function getComponentDescription(componentName, file, docsSource) { // Check cache first const cacheKey = getCacheKey(`${docsSource || 'default'}:${componentName}:description`, file); if (descriptionCache.has(cacheKey)) { return descriptionCache.get(cacheKey); } const componentPath = resolveComponentPath(componentName, file, docsSource); if (!componentPath) { descriptionCache.set(cacheKey, null); return null; } // Lazily add the source file to the ts-morph project. const source = project.addSourceFileAtPathIfExists(componentPath); if (!source) { descriptionCache.set(cacheKey, null); return null; } // Try to find an exported declaration named exactly like the component. const exportedDecl = source.getExportedDeclarations().get(componentName)?.[0]; const possibleNodes = [ exportedDecl, source.getVariableDeclaration(componentName), source.getFunction(componentName), source.getClass(componentName) ]; let firstNodeDesc = null; for (let node of possibleNodes.filter(Boolean)) { let current = node; let isDirectNode = true; while (current) { let docs = typeof current.getJsDocs === 'function' ? current.getJsDocs() : []; if (!docs?.length) { isDirectNode = false; current = current.getParent?.(); continue; } const desc = docs[0].getDescription().trim(); if (!desc) { isDirectNode = false; current = current.getParent?.(); continue; } // If this is the direct node (not a parent), return its description immediately if (isDirectNode) { descriptionCache.set(cacheKey, desc); return desc; } // Otherwise, check if the description mentions the component name const regex = new RegExp(`\\b${componentName}\\b`, 'i'); if (regex.test(desc)) { descriptionCache.set(cacheKey, desc); return desc; } firstNodeDesc = firstNodeDesc || desc; isDirectNode = false; current = current.getParent?.(); } } if (typeof firstNodeDesc === 'string') { descriptionCache.set(cacheKey, firstNodeDesc); return firstNodeDesc; } const allJsDocs = source.getDescendants().flatMap(d => d.getJsDocs?.() || []); for (let doc of allJsDocs.reverse()) { const desc = doc.getDescription().trim(); if (desc && desc.toLowerCase().includes(componentName.toLowerCase())) { descriptionCache.set(cacheKey, desc); return desc; } } descriptionCache.set(cacheKey, null); return null; } function getJsDocData(node) { const docs = typeof node?.getJsDocs === 'function' ? node.getJsDocs() : []; const tags = docs.flatMap(doc => doc.getTags()); return { description: docs.map(doc => doc.getDescription().replace(/\n+/g, ' ').trim()).find(Boolean) || '', defaultValue: tags.find(tag => tag.getTagName() === 'default')?.getCommentText() || '', selector: tags.find(tag => tag.getTagName() === 'selector')?.getCommentText() || '', deprecated: tags.some(tag => tag.getTagName() === 'deprecated'), private: tags.some(tag => tag.getTagName() === 'private') }; } function shouldOmitSymbol(sym) { return (sym.getDeclarations?.() || []).some(decl => { const docData = getJsDocData(decl); return docData.deprecated || docData.private; }); } /** * Extracts one or more `@example` tag contents from JSDoc comments. * * @param {string} text - The text to extract examples from. * @returns {string[]} An array of examples. */ function extractExamplesFromText(text) { if (!text || typeof text !== 'string') { return []; } let lines = text.split('\n').map(line => line.replace(/^\s*\*?\s?/, '')); let examples = []; let current = null; for (let line of lines) { if (/^@example\b/.test(line)) { if (current) { let prev = current.join('\n').trim(); if (prev) { examples.push(prev); } } current = []; let inlineExample = line.replace(/^@example\b\s*/, ''); if (inlineExample) { current.push(inlineExample); } continue; } if (current) { if (/^@\w+/.test(line)) { let example = current.join('\n').trim(); if (example) { examples.push(example); } current = null; continue; } current.push(line); } } if (current) { let example = current.join('\n').trim(); if (example) { examples.push(example); } } return examples; } function parseFencedCodeBlock(example) { if (!example || typeof example !== 'string') { return null; } let trimmed = example.trim(); let match = trimmed.match(/^```([^\n`]*)\n([\s\S]*?)\n```$/); if (!match) { return null; } let [, lang, code] = match; return { lang: lang?.trim() || undefined, code }; } function getFunctionExamples(functionName, file, docsSource) { const cacheKey = getCacheKey(`${docsSource || 'default'}:${functionName}:examples`, file); if (functionExamplesCache.has(cacheKey)) { return functionExamplesCache.get(cacheKey); } const functionPath = resolveComponentPath(functionName, file, docsSource); if (!functionPath) { functionExamplesCache.set(cacheKey, []); return []; } const source = project.addSourceFileAtPathIfExists(functionPath); if (!source) { functionExamplesCache.set(cacheKey, []); return []; } const exportedDecl = source.getExportedDeclarations().get(functionName)?.[0]; const possibleNodes = [ exportedDecl, source.getVariableDeclaration(functionName), source.getFunction(functionName) ]; let firstNodeExamples = []; for (let node of possibleNodes.filter(Boolean)) { let current = node; let isDirectNode = true; while (current) { let docs = typeof current.getJsDocs === 'function' ? current.getJsDocs() : []; if (!docs?.length) { isDirectNode = false; current = current.getParent?.(); continue; } let directExamples = []; for (let doc of docs) { let tags = doc.getTags?.() || []; let tagExamples = tags .filter(tag => tag.getTagName?.() === 'example') .map(tag => tag.getCommentText?.()) .filter(Boolean) .map(value => value.trim()); directExamples.push(...tagExamples); if (tagExamples.length === 0) { let docText = doc.getInnerText?.() || doc.getText?.() || ''; directExamples.push(...extractExamplesFromText(docText)); } } directExamples = [...new Set(directExamples.filter(Boolean))]; if (!directExamples.length) { isDirectNode = false; current = current.getParent?.(); continue; } if (isDirectNode) { functionExamplesCache.set(cacheKey, directExamples); return directExamples; } if (!firstNodeExamples.length) { firstNodeExamples = directExamples; } isDirectNode = false; current = current.getParent?.(); } } functionExamplesCache.set(cacheKey, firstNodeExamples); return firstNodeExamples; } /** * Build a markdown table of props for the given component by analyzing its interface. */ function generatePropTable(componentName, file) { // Check cache first const cacheKey = getCacheKey(componentName, file); if (propTableCache.has(cacheKey)) { return propTableCache.get(cacheKey); } const interfaceName = `${componentName}Props`; // Try to resolve via component path first, then interface path let componentPath = resolveComponentPath(componentName, file); if (!componentPath) { componentPath = resolveComponentPath(interfaceName, file); } if (!componentPath) { propTableCache.set(cacheKey, null); return null; } const source = project.addSourceFileAtPathIfExists(componentPath); if (!source) { propTableCache.set(cacheKey, null); return null; } const iface = source.getInterface(interfaceName); if (!iface) { propTableCache.set(cacheKey, null); return null; } const propSymbols = iface.getType().getProperties(); const rows = propSymbols.flatMap(sym => { if (shouldOmitSymbol(sym)) { return []; } const name = sym.getName(); const decl = sym.getDeclarations()?.[0]; const type = cleanTypeText(sym.getTypeAtLocation(iface).getText(iface)); const docData = getJsDocData(decl); return [{name, type, defVal: docData.defaultValue, description: docData.description}]; }); if (!rows.length) { propTableCache.set(cacheKey, null); return null; } const header = '| Name | Type | Default | Description |\n|------|------|---------|-------------|'; const body = rows .sort((a, b) => a.name.localeCompare(b.name)) .map(r => { const typeStr = `\`${r.type}\``; return `| \`${r.name}\` | ${typeStr} | ${r.defVal || '—'} | ${r.description} |`; }) .join('\n'); const result = `${header}\n${body}`; propTableCache.set(cacheKey, result); return result; } function generateInterfaceTable(interfaceName, file) { // Check cache first const cacheKey = getCacheKey(interfaceName, file); if (interfaceTableCache.has(cacheKey)) { return interfaceTableCache.get(cacheKey); } // Use the unified path resolver which uses the pre-built index let ifacePath = resolveComponentPath(interfaceName, file); if (!ifacePath) { interfaceTableCache.set(cacheKey, null); return null; } const source = project.addSourceFileAtPathIfExists(ifacePath); if (!source) { interfaceTableCache.set(cacheKey, null); return null; } const ifaceDecl = source.getInterface(interfaceName); if (!ifaceDecl) { interfaceTableCache.set(cacheKey, null); return null; } const propSymbols = ifaceDecl.getType().getProperties(); if (!propSymbols.length) { interfaceTableCache.set(cacheKey, null); return null; } // Separate properties and methods const properties = []; const methods = []; for (const sym of propSymbols) { if (shouldOmitSymbol(sym)) { continue; } const name = sym.getName(); const decl = sym.getDeclarations()?.[0]; // Skip private and protected members if (decl) { const modifiers = decl.getModifiers?.() || []; const isPrivate = modifiers.some(m => m.getText() === 'private'); const isProtected = modifiers.some(m => m.getText() === 'protected'); if (isPrivate || isProtected) { continue; } } const type = sym.getTypeAtLocation(ifaceDecl); const callSignatures = type.getCallSignatures(); let description = ''; let defVal = ''; let optional = false; if (decl) { const docData = getJsDocData(decl); description = docData.description; defVal = docData.defaultValue; } if (decl && decl.hasQuestionToken?.()) { optional = true; } // Check if this is a method (has call signatures) if (callSignatures.length > 0) { const sig = callSignatures[0]; const params = sig.getParameters(); const returnType = cleanTypeText(sig.getReturnType().getText(ifaceDecl)); const paramStrs = params.map(p => { const pDecl = p.getDeclarations()?.[0]; const pName = p.getName(); const pType = getTypeText(pDecl, ifaceDecl); const pOptional = pDecl?.hasQuestionToken?.() ? '?' : ''; return `${pName}${pOptional}: ${pType}`; }); const signature = `${name}(${paramStrs.join(', ')}): ${returnType}`; methods.push({name, signature, description}); } else { const typeText = cleanTypeText(type.getText(ifaceDecl)); properties.push({name, type: typeText, description, defVal, optional}); } } if (!properties.length && !methods.length) { return null; } const sections = []; // Render properties section if (properties.length > 0) { if (methods.length > 0) { sections.push('### Properties\n'); } // Check if we need a Default column const hasDefaults = properties.some(p => !!p.defVal); // Sort properties so required ones are shown first, then alphabetically. const sortedProps = properties.sort((a, b) => { if (!a.optional && b.optional) { return -1; } if (a.optional && !b.optional) { return 1; } return a.name.localeCompare(b.name); }); if (hasDefaults) { sections.push('| Name | Type | Default | Description |'); sections.push('|------|------|---------|-------------|'); sortedProps.forEach(r => { const nameStr = r.optional ? `\`${r.name}\`` : `\`${r.name}\` *`; const typeStr = `\`${r.type}\``; const defStr = r.defVal || '—'; sections.push(`| ${nameStr} | ${typeStr} | ${defStr} | ${r.description || '—'} |`); }); } else { sections.push('| Name | Type | Description |'); sections.push('|------|------|-------------|'); sortedProps.forEach(r => { const nameStr = r.optional ? `\`${r.name}\`` : `\`${r.name}\` *`; const typeStr = `\`${r.type}\``; sections.push(`| ${nameStr} | ${typeStr} | ${r.description || '—'} |`); }); } sections.push(''); } // Render methods section if (methods.length > 0) { if (properties.length > 0) { sections.push('### Methods\n'); } methods .sort((a, b) => a.name.localeCompare(b.name)) .forEach(m => { sections.push(`#### \`${m.signature}\`\n`); if (m.description) { sections.push(`${m.description}\n`); } }); } const result = sections.join('\n'); interfaceTableCache.set(cacheKey, result); return result; } /** * Custom remark plugin that removes MDX import/export statements. */ function remarkRemoveImportsExports() { return (tree, file) => { let docsImports = {}; visit(tree, 'mdxjsEsm', (node, index, parent) => { if (node.value) { try { const ast = babel.parse(node.value, { sourceType: 'module', plugins: ['jsx', 'typescript'] }); for (const statement of ast.program.body) { if ( statement.type !== 'ImportDeclaration' || typeof statement.source.value !== 'string' || !statement.source.value.startsWith('docs:') ) { continue; } const docsSource = statement.source.value.slice(5); for (const specifier of statement.specifiers) { // eslint-disable-next-line max-depth if (specifier.local?.name) { docsImports[specifier.local.name] = docsSource; } } } } catch { // Ignore non-import ESM blocks. } } parent.children.splice(index, 1); return index; }); file.data.docsImports = docsImports; }; } /** * Custom remark plugin that converts specific MDX JSX elements to plain markdown. */ function remarkDocsComponentsToMarkdown() { return (tree, file) => { const relatedTypes = new Set(); // For the Style Macro page, inject the shared "Value sets" section above the first H2 // so aliases (baseSpacing, baseColors, etc.) are defined before any table references them. const filePath = file?.path || ''; if (filePath.endsWith('style-macro.mdx') && !styleMacroValueSetsInjected.has(file)) { styleMacroValueSetsInjected.add(file); const valueSets = generateValueSetsMarkdown(); if (valueSets) { const firstH2Index = tree.children.findIndex( child => child.type === 'heading' && child.depth === 2 ); if (firstH2Index !== -1) { const valueSetsTree = unified().use(remarkParse).parse(valueSets); tree.children.splice(firstH2Index, 0, ...valueSetsTree.children); } } } visit(tree, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node, index, parent) => { const name = node.name; if (name === 'InstallCommand') { const pkgAttr = node.attributes?.find(a => a.name === 'pkg'); if (!pkgAttr) { parent.children.splice(index, 1); return index; } let pkg = ''; if (pkgAttr.value?.type === 'mdxJsxAttributeValueExpression') { pkg = pkgAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof pkgAttr.value === 'string') { pkg = pkgAttr.value.trim(); } if (!pkg) { parent.children.splice(index, 1); return index; } const flagsAttr = node.attributes?.find(a => a.name === 'flags'); let flags = ''; if (flagsAttr) { if (flagsAttr.value?.type === 'mdxJsxAttributeValueExpression') { flags = flagsAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof flagsAttr.value === 'string') { flags = flagsAttr.value.trim(); } } const commandText = `npm install ${pkg}${flags ? ' ' + flags : ''}`.trim(); const codeNode = { type: 'code', lang: 'bash', meta: '', value: commandText }; parent.children.splice(index, 1, codeNode); return index; } // Render a simple command snippet. if (name === 'Command') { const commandAttr = node.attributes?.find(a => a.name === 'command'); if (!commandAttr) { parent.children.splice(index, 1); return index; } let command = ''; if (commandAttr.value?.type === 'mdxJsxAttributeValueExpression') { command = commandAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof commandAttr.value === 'string') { command = commandAttr.value.trim(); } if (!command) { parent.children.splice(index, 1); return index; } const codeNode = { type: 'code', lang: 'bash', meta: '', value: command }; parent.children.splice(index, 1, codeNode); return index; } // Render an unordered list of icon names. if (name === 'IconsPageSearch') { const iconList = getIconNames(); const listMarkdown = iconList.length ? iconList.map(iconName => `- ${iconName}`).join('\n') : '> Icon list could not be generated.'; const iconListNode = unified().use(remarkParse).parse(listMarkdown); parent.children.splice(index, 1, ...iconListNode.children); return index; } // Render an unordered list of illustration names. if (name === 'IllustrationCards') { const illustrationList = getIllustrationNames(); const listMarkdown = illustrationList.length ? illustrationList.map(illustrationName => `- ${illustrationName}`).join('\n') : '> Illustration list could not be generated.'; const illustrationCardsNode = unified().use(remarkParse).parse(listMarkdown); parent.children.splice(index, 1, ...illustrationCardsNode.children); return index; } // Render a table of icon colors. if (name === 'IconColors') { const colorsAttr = node.attributes?.find(a => a.name === 'colors'); let colorList = []; if (colorsAttr && colorsAttr.value?.type === 'mdxJsxAttributeValueExpression') { const expr = colorsAttr.value.value; const parsed = parseExpression(expr, file); if (Array.isArray(parsed)) { colorList = parsed.filter(c => typeof c === 'string'); } } if (colorList.length > 0) { const header = ['| Color |', '|-------|']; const rows = colorList.map(color => `| ${color} |`); const tableMarkdown = `${header.join('\n')}\n${rows.join('\n')}`; const iconColorsNode = unified().use(remarkParse).parse(tableMarkdown); parent.children.splice(index, 1, ...iconColorsNode.children); } else { // If no colors found, remove the node parent.children.splice(index, 1); } return index; } // Render a table of icon sizes. if (name === 'IconSizes') { const sizesAttr = node.attributes?.find(a => a.name === 'sizes'); let sizeList = []; if (sizesAttr && sizesAttr.value?.type === 'mdxJsxAttributeValueExpression') { const expr = sizesAttr.value.value; const parsed = parseExpression(expr, file); if (Array.isArray(parsed)) { sizeList = parsed .filter(item => typeof item === 'object' && item.size && item.pixels) .map(item => ({ size: String(item.size), pixels: String(item.pixels) })); } } if (sizeList.length > 0) { const header = ['| Size | Pixels |', '|------|--------|']; const rows = sizeList.map(({size, pixels}) => `| ${size} | ${pixels} |`); const tableMarkdown = `${header.join('\n')}\n${rows.join('\n')}`; const iconSizesNode = unified().use(remarkParse).parse(tableMarkdown); parent.children.splice(index, 1, ...iconSizesNode.children); } else { // If no sizes found, remove the node parent.children.splice(index, 1); } return index; } // Render a text node with the component description. if (name === 'PageDescription') { // Assume first child is expression "docs.exports.Component.description". const exprNode = node.children?.find( c => c.type === 'mdxFlowExpression' || c.type === 'mdxTextExpression' ); if (exprNode) { const m = exprNode.value.match(/docs\.exports\.([\w$]+)\.description/); if (m) { const desc = getComponentDescription(m[1], file); if (desc) { // Replace with normal paragraph node. // oxlint-disable-next-line max-depth if (node.type === 'mdxJsxFlowElement') { parent.children[index] = { type: 'paragraph', children: [{type: 'text', value: desc}] }; } else { parent.children[index] = {type: 'text', value: desc}; } return; } } } // Use children inside if present. const descChildren = (node.children || []).filter(c => c.type !== 'mdxjsEsm'); if (descChildren.length > 0) { if (node.type === 'mdxJsxFlowElement') { parent.children[index] = { type: 'paragraph', children: descChildren }; } else { parent.children.splice(index, 1, ...descChildren); } return; } // If failed, wipe element. parent.children.splice(index, 1); return index; } // Render function description + examples from JSDoc. if (name === 'FunctionJSDoc') { const functionAttr = node.attributes?.find(a => a.name === 'function'); let functionName = null; let docsSource = null; if (functionAttr && functionAttr.value?.type === 'mdxJsxAttributeValueExpression') { const m = functionAttr.value.value.match(/^([\w$]+)\.exports\.([\w$]+)$/); if (m) { docsSource = getDocsImportSource(m[1], file); functionName = m[2]; } else { const fallback = functionAttr.value.value.match(/\.exports\.([\w$]+)/); if (fallback) { functionName = fallback[1]; } } } if (!functionName) { parent.children.splice(index, 1); return index; } const newNodes = []; const description = getComponentDescription(functionName, file, docsSource); if (description) { const descTree = unified().use(remarkParse).parse(description); newNodes.push(...descTree.children); } const examples = getFunctionExamples(functionName, file, docsSource); for (let [exampleIndex, example] of examples.entries()) { if (examples.length > 1) { newNodes.push({ type: 'paragraph', children: [ {type: 'strong', children: [{type: 'text', value: `Example ${exampleIndex + 1}:`}]} ] }); } const fenced = parseFencedCodeBlock(example); if (fenced) { newNodes.push({ type: 'code', lang: fenced.lang || 'tsx', meta: '', value: fenced.code }); } else { const exampleTree = unified().use(remarkParse).parse(example); newNodes.push(...exampleTree.children); } } parent.children.splice(index, 1, ...newNodes); return index + newNodes.length; } // Render a table of props. if (name === 'PropTable') { const compAttr = node.attributes?.find(a => a.name === 'component'); if (compAttr && compAttr.value?.type === 'mdxJsxAttributeValueExpression') { const m = compAttr.value.value.match(/docs\.exports\.([\w$]+)/); if (m) { const table = generatePropTable(m[1], file); if (table) { const tableTree = unified().use(remarkParse).parse(table); parent.children.splice(index, 1, ...tableTree.children); return index + tableTree.children.length; } } } parent.children.splice(index, 1); return index; } // Render a table of props. if (name === 'GroupedPropTable') { // GroupedPropTable uses spread attributes like {...docs.exports.TypeName} const spreadAttr = node.attributes?.find(a => a.type === 'mdxJsxExpressionAttribute'); let typeName = null; if (spreadAttr && spreadAttr.value) { const m = spreadAttr.value.match(/\.\.\.docs\.exports\.([\w$]+)/); if (m) { typeName = m[1]; } } if (!typeName) { // Could not determine type, remove node parent.children.splice(index, 1); return index; } // Generate interface table (GroupedPropTable typically displays interfaces) const table = generateInterfaceTable(typeName, file); if (table) { const tableTree = unified().use(remarkParse).parse(table); parent.children.splice(index, 1, ...tableTree.children); return index + tableTree.children.length; } // Fallback: remove node parent.children.splice(index, 1); return index; } // Render all code examples. if (name === 'ExampleSwitcher') { const examplesAttr = node.attributes?.find(a => a.name === 'examples'); let exampleTitles = []; if (examplesAttr && examplesAttr.value?.type === 'mdxJsxAttributeValueExpression') { const parsed = parseExpression(examplesAttr.value.value, file); exampleTitles = Array.isArray(parsed) ? parsed : []; } const visualChildren = (node.children || []).filter( c => c.type === 'mdxJsxFlowElement' && c.name === 'VisualExample' ); const codeChildren = (node.children || []).filter(c => c.type === 'code'); // Build replacement markdown nodes. const newNodes = []; if (visualChildren.length > 0) { if (exampleTitles.length === 0) { exampleTitles = ['Vanilla CSS', 'Tailwind']; } visualChildren.forEach((vChild, i) => { const title = exampleTitles[i] || `Example ${i + 1}`; // ## {title} example newNodes.push({ type: 'heading', depth: 2, children: [{type: 'text', value: `${title} example`}] }); // Extract files attribute from VisualExample const filesAttr = vChild.attributes?.find(a => a.name === 'files'); let fileList = []; if (filesAttr) { if (filesAttr.value?.type === 'mdxJsxAttributeValueExpression') { const parsed = parseExpression(filesAttr.value.value, file); fileList = Array.isArray(parsed) ? parsed : []; } else if (Array.isArray(filesAttr.value)) { fileList = filesAttr.value; } } fileList.forEach(fp => { const absPath = path.join(REPO_ROOT, fp); if (!fs.existsSync(absPath)) { return; } const contents = fs.readFileSync(absPath, 'utf8'); const ext = path.extname(fp).slice(1); // ### {filename} newNodes.push({ type: 'heading', depth: 3, children: [{type: 'text', value: path.basename(fp)}] }); // ```{lang}\n{contents}\n``` newNodes.push({ type: 'code', lang: ext || undefined, meta: '', value: contents }); }); }); } // Handle code block children (type="vanilla"|"tailwind" and files=[...]) if (codeChildren.length > 0) { // Parse metadata from code blocks to extract type and files const parseCodeMeta = meta => { if (!meta) { return {}; } const result = {}; // Extract type const typeMatch = meta.match(/type=["']([^"']+)["']/); if (typeMatch) { result.type = typeMatch[1]; } // Extract files={[...]} const filesMatch = meta.match(/files=\{(\[[^\]]+\])\}/); if (filesMatch) { try { result.files = JSON.parse(filesMatch[1]); } catch { const parsed = parseExpression(filesMatch[1], file); if (Array.isArray(parsed)) { result.files = parsed; } } } return result; }; const typeToTitle = { vanilla: 'Vanilla CSS', tailwind: 'Tailwind' }; // Check if this is a "component" type ExampleSwitcher (each code block gets its own example title) const typeAttr = node.attributes?.find(a => a.name === 'type'); let switcherType = null; if (typeAttr) { if (typeAttr.value?.type === 'mdxJsxAttributeValueExpression') { switcherType = typeAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof typeAttr.value === 'string') { switcherType = typeAttr.value.trim(); } } if (switcherType && switcherType !== 'css' && exampleTitles.length > 0) { // For any explicit switcher type (e.g. "component", "router"), each code block // represents a distinct example and gets its own heading from the examples array. codeChildren.forEach((codeChild, i) => { const title = exampleTitles[i] || `Example ${i + 1}`; const meta = parseCodeMeta(codeChild.meta); // ## {title} example newNodes.push({ type: 'heading', depth: 2, children: [{type: 'text', value: `${title} example`}] }); // Clean up the code value let codeValue = codeChild.value; if (codeValue.startsWith('"use client";\n')) { codeValue = codeValue.slice(14); } // Remove docs rendering-specific comments codeValue = codeValue .split('\n') .filter(l => !/^\s*\/\/\/-\s*(begin|end)/i.test(l)) .map(l => l.replace(/\/\*\s*PROPS\s*\*\//gi, '')) .join('\n'); newNodes.push({ type: 'code', lang: codeChild.lang || 'tsx', meta: '', value: codeValue }); // Add referenced files for this specific example if (meta.files && Array.isArray(meta.files)) { meta.files.forEach(fp => { const absPath = path.join(REPO_ROOT, fp); if (!fs.existsSync(absPath)) { return; } const contents = fs.readFileSync(absPath, 'utf8'); const ext = path.extname(fp).slice(1); // ### {filename} newNodes.push({ type: 'heading', depth: 3, children: [{type: 'text', value: path.basename(fp)}] }); // ```{lang}\n{contents}\n``` newNodes.push({ type: 'code', lang: ext || undefined, meta: '', value: contents }); }); } }); } else { // Group code blocks by type (vanilla, tailwind, etc.) const codeBlocksByType = new Map(); codeChildren.forEach(codeChild => { const meta = parseCodeMeta(codeChild.meta); const type = meta.type || 'vanilla'; if (!codeBlocksByType.has(type)) { codeBlocksByType.set(type, []); } codeBlocksByType.get(type).push({code: codeChild, meta}); }); // Process each type group for (const [type, codeBlocks] of codeBlocksByType) { const title = typeToTitle[type] || type.charAt(0).toUpperCase() + type.slice(1); // ## {title} example newNodes.push({ type: 'heading', depth: 2, children: [{type: 'text', value: `${title} example`}] }); // Collect all unique files from all code blocks of this type const allFiles = new Set(); codeBlocks.forEach(({meta}) => { if (meta.files && Array.isArray(meta.files)) { meta.files.forEach(f => allFiles.add(f)); } }); // Add the inline example code first codeBlocks.forEach(({code}) => { // Clean up the code value let codeValue = code.value; if (codeValue.startsWith('"use client";\n')) { codeValue = codeValue.slice(14); } // Remove docs rendering-specific comments codeValue = codeValue .split('\n') .filter(l => !/^\s*\/\/\/-\s*(begin|end)/i.test(l)) .map(l => l.replace(/\/\*\s*PROPS\s*\*\//gi, '')) .join('\n'); newNodes.push({ type: 'code', lang: code.lang || 'tsx', meta: '', value: codeValue }); }); // Add referenced files allFiles.forEach(fp => { const absPath = path.join(REPO_ROOT, fp); if (!fs.existsSync(absPath)) { return; } const contents = fs.readFileSync(absPath, 'utf8'); const ext = path.extname(fp).slice(1); // ### {filename} newNodes.push({ type: 'heading', depth: 3, children: [{type: 'text', value: path.basename(fp)}] }); // ```{lang}\n{contents}\n``` newNodes.push({ type: 'code', lang: ext || undefined, meta: '', value: contents }); }); } } } // Replace ExampleSwitcher node with generated markdown. parent.children.splice(index, 1, ...newNodes); return index + newNodes.length; } // Render code for each bundler. if (name === 'BundlerSwitcher') { const bundlerItems = (node.children || []).filter( c => c.type === 'mdxJsxFlowElement' && c.name === 'BundlerSwitcherItem' ); const newNodes = []; const extractLabel = itemNode => { const labelAttr = itemNode.attributes?.find(a => a.name === 'label'); if (!labelAttr) { return null; } if (labelAttr.value?.type === 'mdxJsxAttributeValueExpression') { return labelAttr.value.value.replace(/['"`]/g, '').trim(); } if (typeof labelAttr.value === 'string') { return labelAttr.value.trim(); } return null; }; bundlerItems.forEach(itemNode => { const label = extractLabel(itemNode) || 'Configuration'; newNodes.push({ type: 'heading', depth: 3, children: [{type: 'text', value: label}] }); const itemChildren = (itemNode.children || []).filter( child => child.type !== 'text' || child.value.trim() !== '' ); if (itemChildren.length) { newNodes.push(...itemChildren); } }); parent.children.splice(index, 1, ...newNodes); return index + newNodes.length; } // Render a simple code snippet. if (name === 'VisualExample') { const componentAttr = node.attributes?.find(a => a.name === 'component'); const importSourceAttr = node.attributes?.find(a => a.name === 'importSource'); const initialPropsAttr = node.attributes?.find(a => a.name === 'initialProps'); let componentName = 'Component'; if (componentAttr && componentAttr.value?.type === 'mdxJsxAttributeValueExpression') { componentName = componentAttr.value.value.trim(); } let importSource = '@react-spectrum/s2'; if (importSourceAttr) { if (importSourceAttr.value?.type === 'mdxJsxAttributeValueExpression') { importSource = importSourceAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof importSourceAttr.value === 'string') { importSource = importSourceAttr.value; } } let initialProps = {}; if (initialPropsAttr && initialPropsAttr.value?.type === 'mdxJsxAttributeValueExpression') { const parsed = parseExpression(initialPropsAttr.value.value, file); initialProps = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; } const {children: childrenProp, ...otherProps} = initialProps; const propsString = Object.entries(otherProps) .map(([k, v]) => { if (typeof v === 'string') { return `${k}="${v}"`; } if (typeof v === 'boolean') { return v ? k : ''; } return `${k}={${JSON.stringify(v)}}`; }) .filter(Boolean) .join(' '); let jsxSnippet; if (childrenProp === undefined) { // self-closing tag if no children provided jsxSnippet = `<${componentName}${propsString ? ' ' + propsString : ''} />`; } else { const opening = `<${componentName}${propsString ? ' ' + propsString : ''}>`; const closing = ``; jsxSnippet = `${opening}${childrenProp}${closing}`; } const snippetLines = [ `import {${componentName}} from '${importSource}';`, '', jsxSnippet ].join('\n'); const codeNode = { type: 'code', lang: 'tsx', meta: '', value: snippetLines }; parent.children.splice(index, 1, codeNode); return index + 1; } // Render the version. if (name === 'VersionBadge') { const versionAttr = node.attributes?.find(a => a.name === 'version'); let version = ''; if (versionAttr) { if (versionAttr.value?.type === 'mdxJsxAttributeValueExpression') { version = versionAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof versionAttr.value === 'string') { version = versionAttr.value.trim(); } } if (version) { parent.children[index] = {type: 'text', value: `(${version})`}; } else { // No version, just remove the badge parent.children.splice(index, 1); return index; } return; } // Render markdown links. if (name === 'Link' || name === 'LinkButton') { const hrefAttr = node.attributes?.find(a => a.name === 'href'); let href = ''; if (hrefAttr) { if (hrefAttr.value?.type === 'mdxJsxAttributeValueExpression') { href = hrefAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof hrefAttr.value === 'string') { href = hrefAttr.value.trim(); } } href = resolveSchemeUrl(href); // Convert .html links to .md for relative links if (href && !href.startsWith('http') && !href.startsWith('//') && href.endsWith('.html')) { href = href.replace(/\.html$/, '.md'); } // Check for aria-label attribute first const ariaLabelAttr = node.attributes?.find(a => a.name === 'aria-label'); let ariaLabel = ''; if (ariaLabelAttr) { if (ariaLabelAttr.value?.type === 'mdxJsxAttributeValueExpression') { ariaLabel = ariaLabelAttr.value.value.replace(/['"`]/g, '').trim(); } else if (typeof ariaLabelAttr.value === 'string') { ariaLabel = ariaLabelAttr.value.trim(); } } // Extract text content from children const extractText = children => { if (!children) { return ''; } return children .map(child => { if (child.type === 'text' || child.type === 'mdxText') { return child.value; } if (child.children) { return extractText(child.children); } return ''; }) .join(''); }; const childrenText = extractText(node.children); const linkText = ariaLabel || childrenText || href; // Transform relative links to use .md extension href = transformRelativeUrl(href); if (href) { const linkNode = { type: 'link', url: href, children: [{type: 'text', value: linkText}] }; // If this is a flow element (block-level), wrap in paragraph to preserve spacing if (node.type === 'mdxJsxFlowElement') { parent.children[index] = { type: 'paragraph', children: [linkNode] }; } else { parent.children[index] = linkNode; } } else { // No href, just convert to plain text if (node.type === 'mdxJsxFlowElement') { parent.children[index] = { type: 'paragraph', children: [{type: 'text', value: linkText}] }; } else { parent.children[index] = {type: 'text', value: linkText}; } } return; } // Remove components we can't render as markdown. if (['Anatomy'].includes(name)) { parent.children.splice(index, 1); return index; } if (name === 'TypeLink') { const typeAttr = node.attributes?.find(a => a.name === 'type'); if (typeAttr && typeAttr.value?.type === 'mdxJsxAttributeValueExpression') { const expr = typeAttr.value.value.trim(); // Match anyVar.exports.TypeName or docs.exports.TypeName let m = expr.match(/\.exports\.([\w$]+)/); let typeName = m ? m[1] : null; if (!typeName) { // Fall back to the last identifier segment e.g. "PressEvent" in typesDocs.exports.PressEvent or just PressEvent typeName = expr .split('.') ?.pop() ?.replace(/[^\w$]/g, '') || null; } if (typeName) { relatedTypes.add(typeName); parent.children[index] = {type: 'inlineCode', value: typeName}; return; } } // Fallback – replace with empty string to avoid unhandled component. parent.children[index] = {type: 'text', value: ''}; return index; } // Render an unordered list of style properties. if (name === 'S2StyleProperties') { const propertiesAttr = node.attributes?.find(a => a.name === 'properties'); let propertyList = []; if (propertiesAttr && propertiesAttr.value?.type === 'mdxJsxAttributeValueExpression') { const expr = propertiesAttr.value.value; const parsed = parseExpression(expr, file); if (Array.isArray(parsed)) { propertyList = parsed.filter(p => typeof p === 'string'); } } if (propertyList.length > 0) { // Generate markdown bullet list with inline code const listItems = propertyList.map(prop => `- \`${prop}\``).join('\n'); const listNode = unified().use(remarkParse).parse(listItems); parent.children.splice(index, 1, ...listNode.children); return index + listNode.children.length; } else { // If no properties found, remove the node parent.children.splice(index, 1); } return index; } // Render a table of style macro properties and values. // This handles MDX components from style-macro.mdx like: // // // And converts them to markdown tables documenting the available properties and values. if (name === 'StyleMacroProperties') { const propertiesAttr = node.attributes?.find(a => a.name === 'properties'); let category = null; // Extract the category name from expressions like getPropertyDefinitions('spacing') if (propertiesAttr && propertiesAttr.value?.type === 'mdxJsxAttributeValueExpression') { const expr = propertiesAttr.value.value.trim(); const match = expr.match(/getPropertyDefinitions\(\s*['"`]([^'"`]+)['"`]\s*\)/); if (match) { category = match[1]; // e.g., 'spacing', 'layout', 'colors' } } // Check if sorting should be disabled (default is true) let sort = true; const sortAttr = node.attributes?.find(a => a.name === 'sort'); if (sortAttr) { if (sortAttr.value?.type === 'mdxJsxAttributeValueExpression') { const sortValue = sortAttr.value.value.trim(); if (sortValue === 'false') { sort = false; } } else if (typeof sortAttr.value === 'string') { sort = sortAttr.value !== 'false'; } } if (!category) { parent.children.splice(index, 1); return index; } // Generate and insert the markdown table const table = generateStyleMacroTable(category, {sort}); if (table) { const tableTree = unified().use(remarkParse).parse(table); parent.children.splice(index, 1, ...tableTree.children); return index + tableTree.children.length; } parent.children.splice(index, 1); return index; } // Render a table of S2 colors. if (name === 'S2Colors') { const colorSections = [ { title: 'Background colors', description: 'The backgroundColor property supports the following values, in addition to the semantic and global colors shown below. These colors are specifically chosen to be used as backgrounds, so prefer them over global colors where possible.', colors: [ 'base', 'layer-1', 'layer-2', 'pasteboard', 'elevated', 'accent', 'accent-subtle', 'neutral', 'neutral-subdued', 'neutral-subtle', 'negative', 'negative-subtle', 'informative', 'informative-subtle', 'positive', 'positive-subtle', 'notice', 'notice-subtle', 'gray', 'gray-subtle', 'red', 'red-subtle', 'orange', 'orange-subtle', 'yellow', 'yellow-subtle', 'chartreuse', 'chartreuse-subtle', 'celery', 'celery-subtle', 'green', 'green-subtle', 'seafoam', 'seafoam-subtle', 'cyan', 'cyan-subtle', 'blue', 'blue-subtle', 'indigo', 'indigo-subtle', 'purple', 'purple-subtle', 'fuchsia', 'fuchsia-subtle', 'magenta', 'magenta-subtle', 'pink', 'pink-subtle', 'turquoise', 'turquoise-subtle', 'cinnamon', 'cinnamon-subtle', 'brown', 'brown-subtle', 'silver', 'silver-subtle', 'disabled' ] }, { title: 'Text colors', description: 'The color property supports the following values, in addition to the semantic and global colors shown below. These colors are specifically chosen to be used as text colors, so prefer them over global colors where possible.', colors: [ 'accent', 'neutral', 'neutral-subdued', 'negative', 'disabled', 'heading', 'title', 'body', 'detail', 'code' ] }, { title: 'Semantic colors', description: 'The following values are available across all color properties. Prefer to use semantic colors over global colors when they represent a specific meaning.', scales: [ 'accent-color', 'informative-color', 'negative-color', 'notice-color', 'positive-color' ] }, { title: 'Global colors', description: 'The following values are available across all color properties.', scales: [ 'gray', 'blue', 'red', 'orange', 'yellow', 'chartreuse', 'celery', 'green', 'seafoam', 'cyan', 'indigo', 'purple', 'fuchsia', 'magenta', 'pink', 'turquoise', 'brown', 'silver', 'cinnamon' ] } ]; const newNodes = []; for (const section of colorSections) { // Add heading newNodes.push({ type: 'heading', depth: 4, children: [{type: 'text', value: section.title}] }); // Add description newNodes.push({ type: 'paragraph', children: [{type: 'text', value: section.description}] }); // Add color list if (section.colors) { const listItems = section.colors.map(color => `- \`${color}\``).join('\n'); const listNode = unified().use(remarkParse).parse(listItems); newNodes.push(...listNode.children); } else if (section.scales) { // For scales, note that they include numbered variants (e.g., gray-100, gray-200, etc.) const scaleNote = section.scales .map(scale => { const baseName = scale.replace(/-color$/, ''); // Gray scale includes 25, 50, 75, while others start at 100 if (baseName === 'gray') { return `- \`${baseName}\` scale (e.g., \`${baseName}-25\`, \`${baseName}-50\`, \`${baseName}-75\`, \`${baseName}-100\`, ..., \`${baseName}-1600\`)`; } return `- \`${baseName}\` scale (e.g., \`${baseName}-100\`, \`${baseName}-200\`, ..., \`${baseName}-1600\`)`; }) .join('\n'); const scaleNode = unified().use(remarkParse).parse(scaleNote); newNodes.push(...scaleNode.children); } } parent.children.splice(index, 1, ...newNodes); return index + newNodes.length; } // Render a markdown table. if (name === 'StaticTable') { const headersAttr = node.attributes?.find(a => a.name === 'headers'); const rowsAttr = node.attributes?.find(a => a.name === 'rows'); const codeColumnsAttr = node.attributes?.find(a => a.name === 'codeColumns'); let headers = []; let rows = []; let codeColumns = []; if (headersAttr && headersAttr.value?.type === 'mdxJsxAttributeValueExpression') { const parsed = parseExpression(headersAttr.value.value, file); headers = Array.isArray(parsed) ? parsed : []; } if (rowsAttr && rowsAttr.value?.type === 'mdxJsxAttributeValueExpression') { const parsed = parseExpression(rowsAttr.value.value, file); rows = Array.isArray(parsed) ? parsed : []; } if (codeColumnsAttr && codeColumnsAttr.value?.type === 'mdxJsxAttributeValueExpression') { const parsed = parseExpression(codeColumnsAttr.value.value, file); codeColumns = Array.isArray(parsed) ? parsed : []; } // Helper to extract text content from cell values const extractCellText = cell => { if (cell === null || cell === undefined) { return ''; } if (typeof cell === 'string' || typeof cell === 'number' || typeof cell === 'boolean') { return String(cell); } // If it's an object (could be a parsed JSX element or other structure), try to get meaningful text if (typeof cell === 'object') { // Check if it has a 'children' property (common in parsed objects) if (cell.children) { return extractCellText(cell.children); } // If it's an array, join the elements if (Array.isArray(cell)) { return cell.map(extractCellText).join(''); } // Otherwise, try to get some representation return JSON.stringify(cell); } return String(cell); }; if (headers.length > 0 && rows.length > 0) { // Build markdown table const headerRow = headers.map(h => extractCellText(h)); const separator = headers.map(() => '------'); const bodyRows = rows.map(row => { if (!Array.isArray(row)) { return []; } return row.map((cell, colIdx) => { let text = extractCellText(cell); // Apply code formatting if this column is in codeColumns if (codeColumns.includes(colIdx)) { // If not already wrapped in backticks, wrap it if (!text.startsWith('`')) { text = `\`${text}\``; } } // Escape pipe characters in cells text = text.replace(/\|/g, '\\|'); return text; }); }); const tableMarkdown = [ `| ${headerRow.join(' | ')} |`, `| ${separator.join(' | ')} |`, ...bodyRows.map(row => `| ${row.join(' | ')} |`) ].join('\n'); const tableTree = unified().use(remarkParse).parse(tableMarkdown); parent.children.splice(index, 1, ...tableTree.children); return index + tableTree.children.length; } // If we couldn't build the table, remove the node parent.children.splice(index, 1); return index; } // Render a markdown table. if (name === 'StateTable') { // Extract interface name from properties attribute const propertiesAttr = node.attributes?.find(a => a.name === 'properties'); let ifaceName = null; if (propertiesAttr && propertiesAttr.value?.type === 'mdxJsxAttributeValueExpression') { const m = propertiesAttr.value.value.match(/docs\.exports\.([\w$]+)\.properties/); if (m) { ifaceName = m[1]; } } if (!ifaceName) { // Could not determine interface, remove node parent.children.splice(index, 1); return index; } // Parse other attributes const defaultClassAttr = node.attributes?.find(a => a.name === 'defaultClassName'); let defaultClassName = null; if (defaultClassAttr) { if (defaultClassAttr.value?.type === 'mdxJsxAttributeValueExpression') { // Expression like "'react-aria-ComboBox'" const m = defaultClassAttr.value.value.match(/['"]([\w-]+)['"]/); if (m) { defaultClassName = m[1]; } } else if (defaultClassAttr.value?.type === 'mdxJsxAttributeValueLiteral') { defaultClassName = defaultClassAttr.value.value; } else if (typeof defaultClassAttr.value === 'string') { defaultClassName = defaultClassAttr.value; } } const showOptionalAttr = node.attributes?.find(a => a.name === 'showOptional'); const hideSelectorAttr = node.attributes?.find(a => a.name === 'hideSelector'); const table = generateStateTable( ifaceName, { showOptional: !!showOptionalAttr, hideSelector: !!hideSelectorAttr }, file ); if (table) { const nodesToInsert = []; if (defaultClassName) { nodesToInsert.push({ type: 'paragraph', children: [ {type: 'text', value: 'Default className: '}, {type: 'inlineCode', value: defaultClassName} ] }); } const tableTree = unified().use(remarkParse).parse(table); nodesToInsert.push(...tableTree.children); parent.children.splice(index, 1, ...nodesToInsert); return index + nodesToInsert.length; } // Fallback: remove node parent.children.splice(index, 1); return index; } if (name === 'ClassAPI') { // Extract class name from class attribute const classAttr = node.attributes?.find(a => a.name === 'class'); let className = null; if (classAttr && classAttr.value?.type === 'mdxJsxAttributeValueExpression') { const m = classAttr.value.value.match(/docs\.exports\.([\w$]+)/); if (m) { className = m[1]; } } if (!className) { // Could not determine class, remove node parent.children.splice(index, 1); return index; } // Generate method table and property table for the class const table = generateClassAPITable(className, file); if (table) { const tableTree = unified().use(remarkParse).parse(table); parent.children.splice(index, 1, ...tableTree.children); return index + tableTree.children.length; } // Fallback: remove node parent.children.splice(index, 1); return index; } if (name === 'InterfaceType') { // InterfaceType uses spread attributes like {...docs.exports.TypeName} // We need to look for spread attributes const spreadAttr = node.attributes?.find(a => a.type === 'mdxJsxExpressionAttribute'); let typeName = null; if (spreadAttr && spreadAttr.value) { const m = spreadAttr.value.match(/\.\.\.docs\.exports\.([\w$]+)/); if (m) { typeName = m[1]; } } if (!typeName) { // Could not determine type, remove node parent.children.splice(index, 1); return index; } // Generate interface table const table = generateInterfaceTable(typeName, file); if (table) { const tableTree = unified().use(remarkParse).parse(table); parent.children.splice(index, 1, ...tableTree.children); return index + tableTree.children.length; } // Fallback: remove node parent.children.splice(index, 1); return index; } }); // Clean up code block language specifiers (e.g. "tsx render" -> "tsx"). visit(tree, 'code', node => { if (node.meta) { node.meta = ''; } if (node.value.startsWith('"use client";\n')) { node.value = node.value.slice(14); } // Remove docs rendering-specific comments. node.value = node.value .split('\n') .filter(l => !/^\s*\/\/\/-\s*(begin|end)/i.test(l)) .map(l => l.replace(/\/\*\s*PROPS\s*\*\//gi, '')) .join('\n'); }); // Transform relative links to use .md extension. visit(tree, 'link', node => { node.url = transformRelativeUrl(resolveSchemeUrl(node.url)); }); // Append "Related Types" section if we collected any. if (relatedTypes.size > 0) { const newNodes = [ {type: 'heading', depth: 2, children: [{type: 'text', value: 'Related Types'}]} ]; for (const typeName of Array.from(relatedTypes)) { // ### {typeName} newNodes.push({type: 'heading', depth: 3, children: [{type: 'text', value: typeName}]}); // Try to generate function signature const funcSig = generateFunctionSignature(typeName, file); if (funcSig) { const sigTree = unified().use(remarkParse).parse(funcSig); newNodes.push(...sigTree.children); } const desc = getComponentDescription(typeName, file); if (desc) { newNodes.push({type: 'paragraph', children: [{type: 'text', value: desc}]}); } // Try to generate a table with the interface definition first. let tableMd = generateInterfaceTable(typeName, file); // Fallback to prop table (e.g., when typeName is a component). if (!tableMd) { tableMd = generatePropTable(typeName, file); } // For functions like hooks, attempt to document their options interface. if (!tableMd) { tableMd = generateFunctionOptionsTable(typeName, file); } if (tableMd) { const tableTree = unified().use(remarkParse).parse(tableMd); newNodes.push(...tableTree.children); } } tree.children.push(...newNodes); } }; } /** * Generate markdown documentation for a class, including its methods and properties. */ function generateClassAPITable(className, file) { // Check cache first const cacheKey = getCacheKey(className, file); if (classTableCache.has(cacheKey)) { return classTableCache.get(cacheKey); } // Use unified path resolver which uses the pre-built index let classPath = resolveComponentPath(className, file); if (!classPath) { classTableCache.set(cacheKey, null); return null; } const source = project.addSourceFileAtPathIfExists(classPath); if (!source) { classTableCache.set(cacheKey, null); return null; } const classDecl = source.getClass(className); if (!classDecl) { classTableCache.set(cacheKey, null); return null; } const sections = []; // Generate constructor documentation if available const constructors = classDecl.getConstructors(); if (constructors.length > 0) { const ctor = constructors[0]; const params = ctor.getParameters(); if (params.length > 0) { sections.push('### Constructor\n'); const rows = params.map(param => { const name = param.getName(); const type = getTypeText(param, param); let description = ''; const ctorDocs = ctor.getJsDocs(); if (ctorDocs.length > 0) { const paramTag = ctorDocs[0] .getTags() .find(t => t.getTagName() === 'param' && t.getName?.() === name); if (paramTag) { description = paramTag.getCommentText() || ''; } } return {name, type, description}; }); sections.push('| Parameter | Type | Description |'); sections.push('|-----------|------|-------------|'); rows.forEach(r => { sections.push(`| \`${r.name}\` | \`${r.type}\` | ${r.description || '—'} |`); }); sections.push(''); } } // Generate methods documentation const methods = classDecl.getMethods().filter(m => { const scope = m.getScope(); return scope === undefined || scope === 1; // public methods only }); if (methods.length > 0) { sections.push('### Methods\n'); for (const method of methods) { const methodName = method.getName(); const params = method.getParameters(); const returnType = cleanTypeText(method.getReturnType().getText(method)); // Build method signature const paramStrs = params.map(p => { const pName = p.getName(); const pType = getTypeText(p, p); const optional = p.hasQuestionToken() ? '?' : ''; return `${pName}${optional}: ${pType}`; }); const signature = `${methodName}(${paramStrs.join(', ')}): ${returnType}`; sections.push(`#### \`${signature}\`\n`); // Get method description const methodDocs = method.getJsDocs(); if (methodDocs.length > 0) { const desc = methodDocs[0].getDescription().trim(); if (desc) { sections.push(`${desc}\n`); } // Document parameters const paramTags = methodDocs[0].getTags().filter(t => t.getTagName() === 'param'); if (paramTags.length > 0) { sections.push('**Parameters:**\n'); paramTags.forEach(tag => { const pName = tag.getName?.(); const pDesc = tag.getCommentText() || ''; if (pName) { sections.push(`- \`${pName}\`: ${pDesc}`); } }); sections.push(''); } // Document return value const returnTag = methodDocs[0] .getTags() .find(t => t.getTagName() === 'returns' || t.getTagName() === 'return'); if (returnTag) { const returnDesc = returnTag.getCommentText() || ''; // eslint-disable-next-line max-depth if (returnDesc) { sections.push(`**Returns:** ${returnDesc}\n`); } } } } } // Generate properties documentation const properties = classDecl.getProperties().filter(p => { const scope = p.getScope(); const docData = getJsDocData(p); return (scope === undefined || scope === 1) && !docData.deprecated && !docData.private; // public, non-deprecated, non-private properties only }); if (properties.length > 0) { sections.push('### Properties\n'); sections.push('| Property | Type | Description |'); sections.push('|----------|------|-------------|'); properties.forEach(prop => { const propName = prop.getName(); const propType = getTypeText(prop, prop); let description = ''; const propDocs = prop.getJsDocs(); if (propDocs.length > 0) { description = propDocs[0].getDescription().replace(/\n+/g, ' ').trim(); } sections.push(`| \`${propName}\` | \`${propType}\` | ${description || '—'} |`); }); } const result = sections.length > 0 ? sections.join('\n') : null; classTableCache.set(cacheKey, result); return result; } /** * Generate a markdown table for render props. */ function generateStateTable( renderPropsName, {showOptional = false, hideSelector = false} = {}, file ) { // Attempt to resolve source file by stripping trailing "RenderProps" to get component name. let componentName = renderPropsName.replace(/RenderProps$/, ''); // Try component path first, then render props interface path let componentPath = resolveComponentPath(componentName, file); if (!componentPath) { componentPath = resolveComponentPath(renderPropsName, file); } if (!componentPath) { return null; } const source = project.addSourceFileAtPathIfExists(componentPath); if (!source) { return null; } const iface = source.getInterface(renderPropsName); if (!iface) { return null; } const propSymbols = iface.getType().getProperties(); if (!propSymbols.length) { return null; } // Build rows const rows = propSymbols .map(sym => { if (shouldOmitSymbol(sym)) { return null; } const name = sym.getName(); const decl = sym.getDeclarations()?.[0]; let optional = false; if (decl) { optional = decl.hasQuestionToken?.() || false; } const docData = getJsDocData(decl); return {name, selector: docData.selector || '—', description: docData.description, optional}; }) .filter(Boolean); // Filter optional props if showOptional is false const filteredRows = showOptional ? rows : rows.filter(r => !r.optional); if (!filteredRows.length) { return null; } const hasSelectorColumn = !hideSelector && filteredRows.some(r => r.selector && r.selector !== '—'); const headerColumns = ['Render Prop']; if (hasSelectorColumn) { headerColumns.push('CSS Selector'); } headerColumns.push('Description'); const header = `| ${headerColumns.join(' | ')} |\n|${headerColumns.map(() => '------').join('|')}|`; const body = filteredRows .sort((a, b) => a.name.localeCompare(b.name)) .map(r => { const cols = [ `\`${r.name}\``, ...(hasSelectorColumn ? [r.selector ? `\`${r.selector}\`` : '—'] : []), r.description || '—' ]; return `| ${cols.join(' | ')} |`; }) .join('\n'); return `${header}\n${body}`; } /** * Generate a markdown table for the options interface of a function. * Looks at the first parameter type of the exported function with the given name. */ function generateFunctionOptionsTable(functionName, file) { // Use unified path resolver which uses the pre-built index let funcPath = resolveComponentPath(functionName, file); if (!funcPath) { return null; } const source = project.addSourceFileAtPathIfExists(funcPath); if (!source) { return null; } // Attempt to get an exported declaration for the function. const exportedDecl = source.getExportedDeclarations().get(functionName)?.[0]; const possibleDecls = [ exportedDecl, source.getFunction(functionName), source.getVariableDeclaration(functionName) ]; let funcDecl = possibleDecls.find(Boolean); if (!funcDecl) { return null; } // Retrieve call signature via type to support arrow functions. const type = funcDecl.getType?.() || funcDecl.getType?.(); const callSig = type?.getCallSignatures?.()[0]; if (!callSig) { return null; } const params = callSig.getParameters(); if (!params.length) { return null; } // Inspect the first parameter's declared type. for (const paramSym of params) { const paramDecl = paramSym.getDeclarations()?.[0]; if (!paramDecl) { continue; } // Try to extract a simple type reference name. const typeNode = paramDecl.getTypeNode?.(); let typeName = null; if (typeNode) { // For TypeReference nodes, the text usually contains the identifier name. typeName = typeNode.getText().split(/[<\s|&]/)[0]; } else { // Fallback to type text. typeName = paramDecl .getType?.() .getText(paramDecl) .split(/[<\s|&]/)[0]; } if (typeName) { const table = generateInterfaceTable(typeName, file); if (table) { return table; } } } return null; } /** * Generate a function signature markdown. * Returns the signature like: `functionName(param1: Type1, param2: Type2): ReturnType` */ function generateFunctionSignature(functionName, file) { let funcPath = resolveComponentPath(functionName, file); if (!funcPath) { return null; } const source = project.addSourceFileAtPathIfExists(funcPath); if (!source) { return null; } // Attempt to get an exported declaration for the function. const exportedDecl = source.getExportedDeclarations().get(functionName)?.[0]; const possibleDecls = [ exportedDecl, source.getFunction(functionName), source.getVariableDeclaration(functionName) ]; let funcDecl = possibleDecls.find(Boolean); if (!funcDecl) { return null; } // Retrieve call signature via type to support arrow functions. const type = funcDecl.getType?.(); const callSig = type?.getCallSignatures?.()[0]; if (!callSig) { return null; } const params = callSig.getParameters(); const returnType = cleanTypeText(callSig.getReturnType().getText(funcDecl)); // Build parameter list const paramStrs = params.map(paramSym => { const paramDecl = paramSym.getDeclarations()?.[0]; const pName = paramSym.getName(); const pType = getTypeText(paramDecl, funcDecl); const pOptional = paramDecl?.hasQuestionToken?.() ? '?' : ''; return `${pName}${pOptional}: ${pType}`; }); const signature = `${functionName}(${paramStrs.join(', ')}): ${returnType}`; return `\`${signature}\``; } /** * Generate llms.txt file for a specific library. */ function generateLibraryLlmsTxt(lib, files) { if (!files.length) { return; } const titleMap = { s2: 'React Spectrum (S2) Documentation', 'react-aria': 'React Aria Components Documentation', internationalized: 'Internationalized Documentation' }; const summaryMap = { s2: 'Plain-text markdown documentation for React Spectrum S2 components.', 'react-aria': 'Plain-text markdown documentation for React Aria components.', internationalized: 'Plain-text markdown documentation for internationalized date, time, and number utilities.' }; const title = titleMap[lib] || `${lib} documentation`; const summary = summaryMap[lib] || ''; let txt = `# ${title}\n\n`; if (summary) { txt += `> ${summary}\n\n`; } txt += '## Documentation\n'; const sorted = files.sort((a, b) => a.heading.localeCompare(b.heading)); for (const doc of sorted) { if (doc.description) { txt += `- [${doc.heading}](${doc.path}): ${doc.description}\n`; } else { txt += `- [${doc.heading}](${doc.path})\n`; } } const libDistDir = path.join(DIST_ROOT, lib); fs.mkdirSync(libDistDir, {recursive: true}); const llmsPath = path.join(libDistDir, 'llms.txt'); fs.writeFileSync(llmsPath, txt.trim() + '\n', 'utf8'); console.log('Generated', path.relative(REPO_ROOT, llmsPath)); } /** * Scans the MDX pages in packages/dev/s2-docs/pages and produces a text-based markdown variant of * each file. React-specific JSX elements such as and are replaced * with plain markdown equivalents so that the resulting *.md files can be consumed by LLMs. */ async function main() { const mdxFiles = ( await glob('*/**/*.mdx', { cwd: S2_DOCS_PAGES_ROOT, absolute: true }) ).sort((a, b) => a.localeCompare(b)); // Collect generated markdown filenames and headings for each library so we can build llms.txt files. const docsByLibrary = { s2: [], 'react-aria': [], internationalized: [], root: [] }; for (const filePath of mdxFiles) { const rawContent = fs.readFileSync(filePath, 'utf8'); // Skip redirect pages if (rawContent.includes('')) { mdContent = mdContent.replace(ROUTERS_PLACEHOLDER_REGEX, 'See the Routers section below.'); mdContent += '\n\n## Routers\n\n' + getRoutersMdxContent(); } const processor = unified() .use(remarkParse) .use(remarkMdx) .use(remarkRemoveImportsExports) .use(remarkDocsComponentsToMarkdown); const file = {value: mdContent, path: filePath}; const tree = processor.parse(file); const transformed = await processor.run(tree, file); let markdown = toMarkdown(transformed, { fences: true, bullet: '-', listItemIndent: 'one', extensions: mdxToMarkdown.extensions }); // Convert markdown links ending in .html to .md (relative links only) markdown = markdown.replace(/\[([^\]]+)\]\(([^)]+\.html)\)/g, (match, text, url) => { if (!url.startsWith('http') && !url.startsWith('//')) { return `[${text}](${url.replace(/\.html$/, '.md')})`; } return match; }); const relativePath = path.relative(S2_DOCS_PAGES_ROOT, filePath); const outPath = path.join(DIST_ROOT, relativePath).replace(/\.mdx$/, '.md'); fs.mkdirSync(path.dirname(outPath), {recursive: true}); fs.writeFileSync(outPath, markdown, 'utf8'); console.log('Generated', path.relative(REPO_ROOT, outPath)); // Extract the main heading from the markdown let heading = null; const headingMatch = markdown.match(/^#\s+(.+)$/m); if (headingMatch) { heading = headingMatch[1].trim(); } // Extract the description (first paragraph after heading). Skip if the // first block after the heading is another heading rather than prose. let description = null; const descriptionMatch = markdown.match(/^#\s+.+$\n\n(.+?)(?:\n\n|$)/m); if (descriptionMatch && !descriptionMatch[1].trim().startsWith('#')) { description = descriptionMatch[1].trim(); } // Track markdown files by library (first path segment e.g. "s2/Button.mdx" -> "s2"). const relativePathParts = relativePath.split(path.sep); const relativeOutPath = path.relative(DIST_ROOT, outPath); let libKey; let filePathForIndex; if (relativePathParts.length === 1) { // Root-level file like index.mdx libKey = 'root'; filePathForIndex = path.basename(outPath); } else { libKey = relativePathParts[0]; // For nested files like internationalized/date/index.md, use the .md path filePathForIndex = relativeOutPath.replace(new RegExp(`^${libKey}[\\\\/]`), ''); } if (docsByLibrary[libKey]) { docsByLibrary[libKey].push({ path: filePathForIndex, heading: heading || filePathForIndex.replace(/\.md$/, ''), description: description || null }); } } // Generate library-specific llms.txt files generateLibraryLlmsTxt('s2', docsByLibrary['s2']); generateLibraryLlmsTxt('react-aria', docsByLibrary['react-aria']); } main().catch(err => { console.error(err); process.exit(1); });