1 import { readFileSync } from "fs"
2 import { getFrontMatter, findPageTitle } from "docs-utils"
3 import { ItemsToAdd, sidebarAttachCommonOptions } from "../index.js"
4 import { FrontMatter, Sidebar } from "types"
5
6 /**
7 * Reference pages are the JSON doc-model (`page.json`), not MDX, so their title
8 * and sidebar frontmatter live inside the serialized `DocPage` rather than in a
9 * `---` block. Read those fields from the JSON.
10 */
11 function getReferencePageMeta(filePath: string): {
12 frontmatter: FrontMatter
13 title?: string
14 } {
15 try {
16 const page = JSON.parse(readFileSync(filePath, "utf-8")) as {
17 title?: string
18 frontmatter?: FrontMatter
19 }
20 return { frontmatter: page.frontmatter || {}, title: page.title }
21 } catch {
22 return { frontmatter: {}, title: undefined }
23 }
24 }
25
26 export async function getSidebarItemLink({
27 filePath,
28 basePath,
29 fileBasename,
30 }: {
31 filePath: string
32 basePath: string
33 fileBasename: string
34 }): Promise<ItemsToAdd | undefined> {
35 const isJsonReference = fileBasename.endsWith(".json")
36 const { frontmatter, title } = isJsonReference
37 ? getReferencePageMeta(filePath)
38 : {
39 frontmatter: await getFrontMatter(filePath),
40 title: findPageTitle(filePath),
41 }
42
43 if (frontmatter.sidebar_autogenerate_exclude) {
44 return
45 }
46
47 const newItem = sidebarAttachCommonOptions([
48 {
49 type: "link",
50 path:
51 frontmatter.slug ||
52 filePath.replace(basePath, "").replace(`/${fileBasename}`, ""),
53 title: frontmatter.sidebar_label || title || "",
54 description: frontmatter.sidebar_description || "",
55 },
56 ])[0] as Sidebar.InteractiveSidebarItem
57
58 return {
59 ...newItem,
60 sidebar_position: frontmatter.sidebar_position,
61 }
62 }