1 import type { OpenAPI } from "types"
2 import { getCleanMd } from "docs-utils"
3 import { crossProjectLinksPlugin } from "remark-rehype-plugins"
4 import { getIntroSection } from "@/utils/area"
5 import { apiRefIntroContent as rawIntroContent } from "@/generated/intro-content.mjs"
6 import { crossProjectLinksOptions } from "@/utils/cross-project-links-options.mjs"
7
8 // The raw `.mjs` is emitted with literal (non-indexable) types, so read the
9 // bundled intro MDX through a typed view.
10 const apiRefIntroContent = rawIntroContent as Record<OpenAPI.Area, string>
11
12 /**
13 * The api-reference intro MDX wraps its content in structural layout components
14 * that carry no semantic meaning in Markdown. `getCleanMd` strips any component
15 * not in its allow-list *including its children*, so we unwrap these wrappers
16 * (hoisting their children) before that stripping runs, and turn the custom
17 * `<H1>` into a real heading. Everything else (`CodeTabs`, `Note`,
18 * `Prerequisites`, `Feedback`, `ClientLibraries`) is left to `getCleanMd`.
19 */
20 const UNWRAP_COMPONENTS = new Set([
21 "Section",
22 "SectionContainer",
23 "DividedMarkdownLayout",
24 "DividedMarkdownContent",
25 "DividedMarkdownCode",
26 ])
27
28 // `<H1>` can be parsed as a flow element or (when inline) a text element
29 // wrapped in a paragraph.
30 const isH1 = (node: any): boolean =>
31 (node?.type === "mdxJsxFlowElement" || node?.type === "mdxJsxTextElement") &&
32 node.name === "H1"
33
34 const toHeading = (node: any) => ({
35 type: "heading",
36 depth: 1,
37 children: (node.children || []).filter((c: any) => c.type === "text"),
38 })
39
40 const isBlankText = (node: any): boolean =>
41 node?.type === "text" && !node.value?.trim()
42
43 // Dependency-free recursive unwrap: hoist wrapper children and rewrite `<H1>`
44 // to a heading. Recursion handles arbitrarily-nested wrappers.
45 const unwrapChildren = (children: any[]): any[] => {
46 const result: any[] = []
47 for (const child of children || []) {
48 if (
49 child?.type === "mdxJsxFlowElement" &&
50 UNWRAP_COMPONENTS.has(child.name)
51 ) {
52 result.push(...unwrapChildren(child.children || []))
53 continue
54 }
55 if (isH1(child)) {
56 result.push(toHeading(child))
57 continue
58 }
59 // A paragraph wrapping the inline `<H1>` — lift the heading out, keeping any
60 // remaining inline content as a paragraph.
61 if (child?.type === "paragraph" && (child.children || []).some(isH1)) {
62 const h1 = child.children.find(isH1)
63 result.push(toHeading(h1))
64 const rest = child.children.filter(
65 (c: any) => !isH1(c) && !isBlankText(c)
66 )
67 if (rest.length) {
68 result.push({ type: "paragraph", children: rest })
69 }
70 continue
71 }
72 if (Array.isArray(child?.children)) {
73 child.children = unwrapChildren(child.children)
74 }
75 result.push(child)
76 }
77 return result
78 }
79
80 const unwrapPlugin = () => (tree: any) => {
81 tree.children = unwrapChildren(tree.children || [])
82 }
83
84 /**
85 * Clean the raw intro MDX to Markdown: unwrap structural components and resolve
86 * cross-project (`!area!`) links exactly like the rendered page.
87 */
88 export const cleanIntroContent = async (raw: string): Promise<string> =>
89 getCleanMd({
90 file: raw,
91 type: "content",
92 plugins: {
93 before: [
94 unwrapPlugin,
95 [crossProjectLinksPlugin, crossProjectLinksOptions],
96 ] as any,
97 },
98 })
99
100 /** Extract the Markdown from a `## {title}` heading up to the next `## `. */
101 export const sliceSection = (content: string, title: string): string | null => {
102 const lines = content.split("\n")
103 const headingRe = new RegExp(
104 `^##\\s+${title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*$`,
105 "i"
106 )
107 const start = lines.findIndex((line) => headingRe.test(line))
108 if (start === -1) {
109 return null
110 }
111
112 let end = lines.length
113 for (let i = start + 1; i < lines.length; i++) {
114 // Next level-2 heading (`## `, not `### `) ends the section.
115 if (/^##\s+(?!#)/.test(lines[i])) {
116 end = i
117 break
118 }
119 }
120
121 return lines.slice(start, end).join("\n").trim()
122 }
123
124 /**
125 * Converts an area's intro MDX to Markdown. Without `section`, returns the whole
126 * intro; with `section`, returns only that `## ` section's Markdown.
127 */
128 export default async function introToMarkdown(
129 area: OpenAPI.Area,
130 section?: string
131 ): Promise<string | null> {
132 const raw = apiRefIntroContent[area]
133 if (!raw) {
134 return null
135 }
136
137 const cleaned = await cleanIntroContent(raw)
138
139 if (!section) {
140 return cleaned
141 }
142
143 const introSection = getIntroSection(area, section)
144 if (!introSection) {
145 return null
146 }
147
148 return sliceSection(cleaned, introSection.title)
149 }