1 import { existsSync, mkdirSync, readdirSync, statSync } from "fs"
2 import path from "path"
3 import { getSidebarItemLink, sidebarAttachCommonOptions } from "./index.js"
4 import getCoreFlowsRefSidebarChildren from "./utils/get-core-flows-ref-sidebar-children.js"
5 import { parseTags } from "./utils/parse-tags.js"
6 import numberSidebarItems from "./utils/number-sidebar-items.js"
7 import { sortSidebarItems } from "./utils/sidebar-sorting.js"
8 import { Sidebar } from "types"
9 import { validateSidebarUniqueIds } from "./utils/validate-sidebar-unique-ids.js"
10 import getApiRefSidebarChildren from "./utils/get-api-ref-sidebar-children.js"
11
12 export type ItemsToAdd = Sidebar.SidebarItem & {
13 sidebar_position?: number
14 }
15
16 export type GenerateSidebarOptions = {
17 addNumbering?: boolean
18 writeToFile?: boolean
19 }
20
21 const customGenerators: Record<
22 string,
23 (sidebar?: Sidebar.RawSidebar) => Promise<ItemsToAdd[]>
24 > = {
25 "core-flows": getCoreFlowsRefSidebarChildren,
26 "api-ref": getApiRefSidebarChildren,
27 }
28
29 function sortItems(itemA: ItemsToAdd, itemB: ItemsToAdd): number {
30 const itemASidebarPosition = itemA.sidebar_position || 0
31 const itemBSidebarPosition = itemB.sidebar_position || 0
32
33 if (itemASidebarPosition > itemBSidebarPosition) {
34 return 1
35 }
36
37 return itemASidebarPosition < itemBSidebarPosition ? -1 : 0
38 }
39
40 async function getAutogeneratedSidebarItems(
41 dir: string,
42 nested = false
43 ): Promise<ItemsToAdd[]> {
44 const isRefDir =
45 dir.startsWith("/references") && dir !== "/references-overview"
46 const basePath = isRefDir ? path.resolve() : path.resolve("app")
47 const fullPath = path.resolve(basePath, dir.replace(/^\//, ""))
48 const items: ItemsToAdd[] = []
49
50 const files = readdirSync(fullPath)
51 let mainPageIndex = -1
52
53 for (const file of files) {
54 const filePath = path.join(fullPath, file)
55 const fileBasename = path.basename(file)
56 if (fileBasename.startsWith("_")) {
57 continue
58 }
59
60 if (fileBasename !== "page.mdx" && statSync(filePath).isDirectory()) {
61 const newItems = await getAutogeneratedSidebarItems(
62 filePath.replace(basePath, ""),
63 true
64 )
65 if (nested && newItems.length > 1) {
66 items.push({
67 type: "sub-category",
68 title:
69 fileBasename.charAt(0).toUpperCase() + fileBasename.substring(1),
70 children: newItems,
71 loaded: true,
72 })
73 } else {
74 items.push(...newItems)
75 }
76 continue
77 }
78
79 const newItem = await getSidebarItemLink({
80 filePath,
81 basePath,
82 fileBasename,
83 })
84
85 if (!newItem) {
86 continue
87 }
88
89 items.push(newItem)
90
91 mainPageIndex = items.length - 1
92 }
93
94 if (
95 mainPageIndex !== -1 &&
96 items.length > 1 &&
97 items[0].type !== "separator"
98 ) {
99 // push all other items to be children of that page.
100 const mainPageChildren = [
101 ...items.splice(0, mainPageIndex),
102 ...items.splice(1),
103 ]
104 mainPageChildren.sort(sortItems)
105 items[0].children = mainPageChildren
106 } else if (items.length > 1) {
107 items.sort(sortItems)
108 }
109
110 return items
111 }
112
113 async function getAutogeneratedTagSidebarItems(
114 tags: string,
115 type: "link" | "ref",
116 existingChildren?: Sidebar.RawSidebarItem[]
117 ): Promise<ItemsToAdd[]> {
118 const items: ItemsToAdd[] = []
119
120 const parsedTags = parseTags(tags)
121
122 items.push(
123 ...parsedTags
124 .filter((tagItem) => {
125 return existingChildren
126 ? existingChildren.every((existingItem) => {
127 if (existingItem.type !== "link" && existingItem.type !== "ref") {
128 return true
129 }
130
131 return !tagItem.path.endsWith(existingItem.path)
132 })
133 : true
134 })
135 .map(
136 (tagItem) =>
137 ({
138 type,
139 ...tagItem,
140 }) as ItemsToAdd
141 )
142 )
143
144 return items
145 }
146
147 function validateItem(item: Sidebar.RawSidebarItem): void {
148 if (!item.type) {
149 throw new Error(
150 `ERROR: The following item doesn't have a type: ${JSON.stringify(
151 item,
152 undefined,
153 2
154 )}`
155 )
156 }
157 if (item.type === "sidebar" && !item.sidebar_id) {
158 throw new Error(
159 `ERROR: The following sidebar item doesn't have a sidebar_id: ${JSON.stringify(
160 item,
161 undefined,
162 2
163 )}`
164 )
165 }
166 if (item.type === "link" && !item.path) {
167 throw new Error(
168 `ERROR: The following link item doesn't have a path: ${JSON.stringify(
169 item,
170 undefined,
171 2
172 )}`
173 )
174 }
175 }
176
177 async function checkItem(
178 item: Sidebar.RawSidebarItem
179 ): Promise<Sidebar.RawSidebarItem> {
180 if (item.type === "separator") {
181 return item
182 }
183
184 validateItem(item)
185
186 if (item.children) {
187 item.children = await checkItems(item.children)
188 }
189
190 if (item.autogenerate_path) {
191 item.children = [
192 ...(item.children || []),
193 ...(await getAutogeneratedSidebarItems(item.autogenerate_path)).map(
194 (child) => {
195 delete child.sidebar_position
196
197 return child
198 }
199 ),
200 ]
201 } else if (item.autogenerate_tags) {
202 item.children = [
203 ...(item.children || []),
204 ...(await getAutogeneratedTagSidebarItems(
205 item.autogenerate_tags,
206 item.autogenerate_as_ref ? "ref" : "link",
207 item.children
208 )),
209 ]
210 } else if (
211 item.custom_autogenerate &&
212 Object.hasOwn(customGenerators, item.custom_autogenerate)
213 ) {
214 item.children = [
215 ...(item.children || []),
216 ...(await customGenerators[item.custom_autogenerate]()),
217 ]
218 }
219
220 item.children = sortSidebarItems({
221 items: item.children as Sidebar.RawSidebarItem[],
222 type: item.sort_sidebar,
223 })
224
225 return item
226 }
227
228 async function checkItems(
229 items: Sidebar.RawSidebarItem[],
230 options?: GenerateSidebarOptions
231 ): Promise<Sidebar.RawSidebarItem[]> {
232 let updatedItems = (
233 await Promise.all(items.map(async (item) => await checkItem(item)))
234 ).filter((item) => {
235 if (item.type !== "category" && item.type !== "sub-category") {
236 return true
237 }
238
239 return (item.children?.length || 0) > 0
240 })
241
242 if (options?.addNumbering) {
243 updatedItems = numberSidebarItems(updatedItems)
244 }
245
246 return sidebarAttachCommonOptions(updatedItems)
247 }
248
249 export async function generateSidebar(
250 sidebars: Sidebar.RawSidebar[],
251 options?: GenerateSidebarOptions
252 ): Promise<void | Sidebar.RawSidebar[]> {
253 const path = await import("path")
254 const { writeFileSync } = await import("fs")
255
256 const normalizedSidebars: Sidebar.RawSidebar[] = []
257
258 const { writeToFile = true, ...restOptions } = options || {}
259
260 validateSidebarUniqueIds(sidebars)
261
262 for (const sidebarItem of sidebars) {
263 const hasCustomAutogenerator =
264 sidebarItem.custom_autogenerate &&
265 Object.hasOwn(customGenerators, sidebarItem.custom_autogenerate)
266 normalizedSidebars.push({
267 ...sidebarItem,
268 items: !hasCustomAutogenerator
269 ? await checkItems(sidebarItem.items, restOptions)
270 : await customGenerators[sidebarItem.custom_autogenerate!](sidebarItem),
271 })
272 }
273
274 if (!writeToFile) {
275 return normalizedSidebars
276 }
277
278 const generatedDirPath = path.resolve("generated")
279
280 if (!existsSync(generatedDirPath)) {
281 mkdirSync(generatedDirPath)
282 }
283
284 // write normalized sidebar
285 writeFileSync(
286 path.resolve(generatedDirPath, "sidebar.mjs"),
287 `export const generatedSidebars = ${JSON.stringify(
288 normalizedSidebars,
289 null,
290 2
291 )}`,
292 {
293 flag: "w",
294 }
295 )
296 }