1 import remarkMdx from "remark-mdx"
2 import remarkParse from "remark-parse"
3 import remarkStringify from "remark-stringify"
4 import {
5 Estree,
6 FrontMatter,
7 UnistNode,
8 UnistNodeWithData,
9 UnistTree,
10 } from "types"
11 import { Plugin, Transformer, unified } from "unified"
12 import { SKIP, VisitorResult } from "unist-util-visit"
13 import type { VFile } from "vfile"
14 import {
15 ComponentParser,
16 parseCard,
17 parseCardList,
18 parseChildDocs,
19 parseCodeTabs,
20 parseColors,
21 parseComponentExample,
22 parseComponentReference,
23 parseDetails,
24 parseEventHeader,
25 parseHookValues,
26 parseIconSearch,
27 parseInjectedMarkdown,
28 parseNote,
29 parsePackageInstall,
30 parsePrerequisites,
31 parseSourceCodeLink,
32 parseSplitList,
33 parseTable,
34 parseTabs,
35 parseTypeList,
36 parseWorkflowDiagram,
37 } from "./utils/parsers.js"
38 import remarkFrontmatter from "remark-frontmatter"
39 import { matter } from "vfile-matter"
40 import {
41 collectDeclarations,
42 EvaluationScope,
43 evaluateEstreeExpression,
44 stringifyValue,
45 UNRESOLVED,
46 } from "./utils/evaluate-expression.js"
47 import { globalConfig } from "./global-config.js"
48
49 const parsers: Record<string, ComponentParser> = {
50 Card: parseCard,
51 CardList: parseCardList,
52 ChangelogList: parseInjectedMarkdown,
53 ChildDocs: parseChildDocs,
54 CodeTabs: parseCodeTabs,
55 Details: parseDetails,
56 Note: parseNote,
57 Prerequisites: parsePrerequisites,
58 SourceCodeLink: parseSourceCodeLink,
59 Table: parseTable,
60 Tabs: parseTabs,
61 TypeList: parseTypeList,
62 WorkflowDiagram: parseWorkflowDiagram,
63 ComponentExample: parseComponentExample,
64 ComponentReference: parseComponentReference,
65 PackageInstall: parsePackageInstall,
66 IconSearch: parseIconSearch,
67 HookValues: parseHookValues,
68 Colors: parseColors,
69 SplitList: parseSplitList,
70 EventHeader: parseEventHeader,
71 PricingContent: parseInjectedMarkdown,
72 }
73
74 const asyncParserNames = new Set([
75 "ChangelogList",
76 "ComponentExample",
77 "ComponentReference",
78 "PricingContent",
79 ])
80
81 const isComponentAllowed = (nodeName: string): boolean => {
82 return Object.keys(parsers).includes(nodeName)
83 }
84
85 const METADATA_EXPORT_PREFIX = "export const metadata = "
86
87 /**
88 * Pulls the page title out of an `export const metadata = { title: ... }`
89 * statement. Template placeholders such as `${pageNumber}` are stripped since
90 * they're injected by the MDX pipeline and carry no meaning in Markdown.
91 */
92 const extractMetadataTitle = (value: string): string | undefined => {
93 const regexMatch = /title: (?<title>.+),?/.exec(value)
94
95 return regexMatch?.groups?.title
96 ?.replace(/,$/, "")
97 .replaceAll(/\$\{.+\}/g, "")
98 .replaceAll(/^['"`]/g, "")
99 .replaceAll(/['"`]$/g, "")
100 .trim()
101 }
102
103 type ParserPluginOptions = {
104 [key: string]: unknown
105 }
106
107 const parseComponentsPlugin = (options: ParserPluginOptions): Transformer => {
108 return async (tree) => {
109 const { visit } = await import("unist-util-visit")
110
111 let pageTitle = ""
112
113 type AsyncParserTask = {
114 node: UnistNodeWithData
115 parent: UnistTree
116 parserName: string
117 }
118 const asyncTasks: AsyncParserTask[] = []
119
120 visit(
121 tree as UnistTree,
122 ["mdxJsxFlowElement", "element", "mdxjsEsm", "heading"],
123 (node: UnistNode, index, parent) => {
124 if (typeof index !== "number" || !parent) {
125 return
126 }
127 if (
128 node.type === "mdxjsEsm" &&
129 node.value?.startsWith("export const metadata = ") &&
130 node.data &&
131 "estree" in node.data
132 ) {
133 pageTitle = extractMetadataTitle(node.value) || pageTitle
134 }
135 if (node.type === "heading") {
136 if (node.depth === 1 && node.children?.length) {
137 if (node.children[0].value === "metadata.title") {
138 node.children[0] = {
139 type: "text",
140 value: pageTitle,
141 }
142 } else {
143 node.children = node.children
144 .filter((child) => child.type === "text")
145 .map((child) => ({
146 ...child,
147 value: child.value?.trim(),
148 }))
149 }
150 }
151 return
152 }
153 if (
154 node.type === "mdxjsEsm" ||
155 !isComponentAllowed(node.name as string)
156 ) {
157 parent?.children.splice(index, 1)
158 return [SKIP, index]
159 }
160
161 if (!node.name) {
162 return
163 }
164
165 if (asyncParserNames.has(node.name)) {
166 asyncTasks.push({
167 node: node as UnistNodeWithData,
168 parent: parent as UnistTree,
169 parserName: node.name,
170 })
171 return
172 }
173
174 const parser = parsers[node.name]
175 if (parser) {
176 const parserOptions = options[node.name] || {}
177 return parser(
178 node as UnistNodeWithData,
179 index,
180 parent,
181 parserOptions
182 ) as VisitorResult
183 }
184 }
185 )
186
187 for (const { node, parent, parserName } of asyncTasks) {
188 const currentIndex = (parent as UnistTree).children.indexOf(
189 node as UnistNode
190 )
191 if (currentIndex === -1) {
192 continue
193 }
194 const parser = parsers[parserName]
195 if (parser) {
196 await parser(node, currentIndex, parent, options[parserName] || {})
197 }
198 }
199 }
200 }
201
202 /**
203 * Parses a resolved expression's value as Markdown so that values holding
204 * Markdown syntax (links, emphasis, code spans) aren't escaped when the tree is
205 * stringified.
206 */
207 const parseMarkdownFragment = async (
208 value: string,
209 inline: boolean
210 ): Promise<UnistNode[]> => {
211 const tree = unified().use(remarkParse).parse(value) as unknown as UnistTree
212 const children = tree.children || []
213
214 if (inline && children.length === 1 && children[0].type === "paragraph") {
215 return children[0].children || []
216 }
217
218 return children
219 }
220
221 /**
222 * Resolves MDX expressions (`{config.version.number}`, `{someExportedConst}`)
223 * to their values before the components plugin strips the `export`/`import`
224 * statements that back them.
225 *
226 * Without this, expressions are stringified as-is and leak placeholders such as
227 * `v{config.version.number}` into the Markdown served to agents. Expressions
228 * that can't be resolved statically — including MDX comments — are removed
229 * instead of leaked.
230 */
231 const resolveExpressionsPlugin = (scope: EvaluationScope): Transformer => {
232 return async (tree) => {
233 const { visit } = await import("unist-util-visit")
234
235 const localScope: EvaluationScope = { ...scope }
236 type ExpressionTask = {
237 node: UnistNode
238 parent: UnistTree
239 inline: boolean
240 }
241 const tasks: ExpressionTask[] = []
242
243 visit(
244 tree as UnistTree,
245 ["mdxjsEsm", "mdxTextExpression", "mdxFlowExpression"],
246 (node: UnistNode, index, parent) => {
247 const estree = (node.data as { estree?: Estree } | undefined)?.estree
248
249 if (node.type === "mdxjsEsm") {
250 if (node.value?.startsWith(METADATA_EXPORT_PREFIX)) {
251 const title = extractMetadataTitle(node.value)
252 if (title) {
253 localScope.metadata = {
254 ...(localScope.metadata as Record<string, unknown>),
255 title,
256 }
257 }
258 return
259 }
260
261 collectDeclarations(estree, localScope)
262 return
263 }
264
265 if (typeof index !== "number" || !parent) {
266 return
267 }
268
269 tasks.push({
270 node,
271 parent: parent as UnistTree,
272 inline: node.type === "mdxTextExpression",
273 })
274 }
275 )
276
277 // Replacements happen after the traversal so that every declaration in the
278 // page is in scope, regardless of where it's declared relative to its usage.
279 for (const { node, parent, inline } of tasks) {
280 const index = parent.children.indexOf(node)
281 if (index === -1) {
282 continue
283 }
284
285 const value = evaluateEstreeExpression(
286 (node.data as { estree?: Estree } | undefined)?.estree,
287 localScope
288 )
289 const stringified =
290 value === UNRESOLVED ? undefined : stringifyValue(value)
291
292 if (stringified === undefined) {
293 parent.children.splice(index, 1)
294 continue
295 }
296
297 parent.children.splice(
298 index,
299 1,
300 ...(await parseMarkdownFragment(stringified, inline))
301 )
302 }
303 }
304 }
305
306 /**
307 * Strips the code block meta that only the docs UI understands (`npm2yarn`,
308 * `npx2yarn`, `highlights={...}`, ...). Left in place, it turns into invalid
309 * info strings like ` ```bash npx2yarn ` in the Markdown output. `title="..."`
310 * is kept since it names the file the snippet belongs to.
311 */
312 const cleanCodeMetaPlugin = (): Transformer => {
313 return async (tree) => {
314 const { visit } = await import("unist-util-visit")
315
316 visit(tree as UnistTree, "code", (node: UnistNode) => {
317 if (!node.meta) {
318 return
319 }
320
321 node.meta = /title="[^"]*"/.exec(node.meta)?.[0] || null
322 })
323 }
324 }
325
326 const removeFrontmatterPlugin = (): Transformer => {
327 return async (tree) => {
328 const { visit } = await import("unist-util-visit")
329
330 visit(
331 tree as UnistTree,
332 ["yaml", "toml"],
333 (node: UnistNode, index, parent) => {
334 if (typeof index !== "number" || parent?.type !== "root") {
335 return
336 }
337
338 parent.children.splice(index, 1)
339 return [SKIP, index]
340 }
341 )
342 }
343 }
344
345 const getParsedAsString = (file: VFile): string => {
346 let content = file.toString().replaceAll(/^([\s]*)\* /gm, "$1- ")
347 const frontmatter = file.data.matter as FrontMatter | undefined
348
349 if (frontmatter?.title) {
350 content = `# ${frontmatter.title}\n\n${frontmatter.description ? `${frontmatter.description}\n\n` : ""}${content}`
351 }
352
353 return content
354 }
355
356 export type GetCleanMdOptions = {
357 file: string
358 plugins?: {
359 before?: Plugin[]
360 after?: Plugin[]
361 }
362 parserOptions?: ParserPluginOptions
363 type?: "file" | "content"
364 /**
365 * Values that MDX expressions in the page can reference. Merged into (and
366 * taking precedence over) the defaults, which expose the docs `config`.
367 */
368 scope?: EvaluationScope
369 }
370
371 const getDefaultScope = (): EvaluationScope => ({
372 config: {
373 version: globalConfig.version,
374 },
375 })
376
377 export const getCleanMd = async ({
378 file,
379 plugins,
380 parserOptions,
381 type = "file",
382 scope,
383 }: GetCleanMdOptions): Promise<string> => {
384 const { read } = await import("to-vfile")
385 if (type === "file" && !file.endsWith(".md") && !file.endsWith(".mdx")) {
386 return ""
387 }
388 const unifier = unified()
389 .use(remarkParse)
390 .use(remarkMdx)
391 .use(remarkStringify)
392 .use(remarkFrontmatter, ["yaml"])
393 .use(() => {
394 return (tree, file) => {
395 matter(file)
396 }
397 })
398
399 plugins?.before?.forEach((plugin) => {
400 unifier.use(...(Array.isArray(plugin) ? plugin : [plugin]))
401 })
402
403 unifier
404 .use(resolveExpressionsPlugin, { ...getDefaultScope(), ...scope })
405 .use(cleanCodeMetaPlugin)
406 .use(parseComponentsPlugin, parserOptions || {})
407 .use(removeFrontmatterPlugin)
408
409 plugins?.after?.forEach((plugin) => {
410 unifier.use(...(Array.isArray(plugin) ? plugin : [plugin]))
411 })
412
413 const content = type === "file" ? await read(file) : file
414 const parsed = await unifier.process(content)
415
416 return getParsedAsString(parsed)
417 }