1 import fs from "fs/promises"
2 import { outdent } from "outdent"
3 import { File, parse, ParseResult, traverse } from "../babel"
4 import { logger } from "../logger"
5 import {
6 crawl,
7 getParserOptions,
8 hasDefaultExport,
9 normalizePath,
10 } from "../utils"
11 import { getRoute } from "./helpers"
12
13 type Route = {
14 Component: string
15 path: string
16 handle?: string
17 loader?: string
18 children?: Route[]
19 }
20
21 type RouteResult = {
22 imports: string[]
23 route: Route
24 }
25
26 export async function generateRoutes(sources: Set<string>) {
27 const files = await getFilesFromSources(sources)
28 const results = await getRouteResults(files)
29 const imports = results.map((result) => result.imports).flat()
30 const code = generateCode(results)
31
32 return {
33 imports,
34 code,
35 }
36 }
37
38 function generateCode(results: RouteResult[]): string {
39 return outdent`
40 routes: [
41 ${results.map((result) => formatRoute(result.route)).join(",\n")}
42 ]
43 }
44 `
45 }
46
47 function formatRoute(route: Route): string {
48 let base = `{
49 Component: ${route.Component},
50 path: "${route.path}"`
51
52 if (route.handle) {
53 base += `,
54 handle: ${route.handle}`
55 }
56
57 if (route.loader) {
58 base += `,
59 loader: ${route.loader}`
60 }
61
62 if (route.children?.length) {
63 return `${base},
64 children: [
65 ${route.children.map((child) => formatRoute(child)).join(",\n ")}
66 ]
67 }`
68 }
69
70 return `${base}
71 }`
72 }
73
74 async function getFilesFromSources(sources: Set<string>): Promise<string[]> {
75 const files = (
76 await Promise.all(
77 Array.from(sources).map(async (source) =>
78 crawl(`${source}/routes`, "page", { min: 1 })
79 )
80 )
81 ).flat()
82 return files
83 }
84
85 async function getRouteResults(files: string[]): Promise<RouteResult[]> {
86 const results = (await Promise.all(files.map(parseFile))).filter(
87 (result): result is RouteResult => result !== null
88 )
89
90 const routeMap = new Map<string, RouteResult>()
91
92 results.forEach((result) => {
93 const routePath = result.route.path
94 const isParallel = routePath.includes("/@")
95
96 if (isParallel) {
97 const parentPath = routePath.split("/@")[0]
98 const parent = routeMap.get(parentPath)
99 if (parent) {
100 parent.route.children = parent.route.children || []
101
102 /**
103 * We do not want to include the @ in the final path, so we remove it.
104 */
105 const finalRoute = {
106 ...result.route,
107 path: result.route.path.replace("@", ""),
108 }
109
110 parent.route.children.push(finalRoute)
111 parent.imports.push(...result.imports)
112 }
113 } else {
114 routeMap.set(routePath, result)
115 }
116 })
117
118 return Array.from(routeMap.values())
119 }
120
121 async function parseFile(
122 file: string,
123 index: number
124 ): Promise<RouteResult | null> {
125 const code = await fs.readFile(file, "utf-8")
126
127 let ast: ParseResult<File> | null = null
128
129 try {
130 ast = parse(code, getParserOptions(file))
131 } catch (e) {
132 logger.error("An error occurred while parsing the file.", {
133 file,
134 error: e,
135 })
136 return null
137 }
138
139 if (!(await isValidRouteFile(ast, file))) {
140 return null
141 }
142
143 const { hasHandle, hasLoader, hasConfig } = await hasNamedExports(ast, file)
144 const routePath = getRoute(file)
145
146 const imports = generateImports(file, index, hasHandle, hasLoader, hasConfig)
147 const route = generateRoute(routePath, index, hasHandle, hasLoader, hasConfig)
148
149 return {
150 imports,
151 route,
152 }
153 }
154
155 async function isValidRouteFile(
156 ast: ParseResult<File>,
157 file: string
158 ): Promise<boolean> {
159 try {
160 return await hasDefaultExport(ast)
161 } catch (e) {
162 logger.error(
163 `An error occurred while checking for a default export in ${file}. The file will be ignored. See the below error for more details:\n${e}`
164 )
165 return false
166 }
167 }
168
169 function generateImports(
170 file: string,
171 index: number,
172 hasHandle: boolean,
173 hasLoader: boolean,
174 hasConfig: boolean
175 ): string[] {
176 const imports: string[] = []
177 const route = generateRouteComponentName(index)
178 const importPath = normalizePath(file)
179
180 if (!hasHandle && !hasLoader && !hasConfig) {
181 imports.push(`import ${route} from "${importPath}"`)
182 } else {
183 const namedImports = [
184 hasHandle && `handle as ${generateHandleName(index)}`,
185 hasLoader && `loader as ${generateLoaderName(index)}`,
186 hasConfig && `config as ${generateRouteConfigName(index)}`,
187 ]
188 .filter(Boolean)
189 .join(", ")
190 imports.push(`import ${route}, { ${namedImports} } from "${importPath}"`)
191 }
192
193 return imports
194 }
195
196 function generateRoute(
197 route: string,
198 index: number,
199 hasHandle: boolean,
200 hasLoader: boolean,
201 hasConfig: boolean
202 ): Route {
203 return {
204 Component: generateRouteComponentName(index),
205 path: route,
206 handle: generateHandle(index, hasHandle, hasConfig),
207 loader: hasLoader ? generateLoaderName(index) : undefined,
208 }
209 }
210
211 /**
212 * Builds the route's `handle` expression.
213 *
214 * When the route file exports a `config` (via `defineRouteConfig`), its `label`
215 * and `translationNs` are surfaced on the handle so the dashboard can fall back
216 * to the sidebar label for the document title when no `seo` resolver is
217 * provided. An explicit `handle` export always wins.
218 */
219 function generateHandle(
220 index: number,
221 hasHandle: boolean,
222 hasConfig: boolean
223 ): string | undefined {
224 if (!hasHandle && !hasConfig) {
225 return undefined
226 }
227
228 if (!hasConfig) {
229 return generateHandleName(index)
230 }
231
232 const configName = generateRouteConfigName(index)
233 const labelFields = `label: ${configName}.label, translationNs: ${configName}.translationNs`
234
235 return hasHandle
236 ? `{ ${labelFields}, ...${generateHandleName(index)} }`
237 : `{ ${labelFields} }`
238 }
239
240 function generateRouteComponentName(index: number): string {
241 return `RouteComponent${index}`
242 }
243
244 function generateHandleName(index: number): string {
245 return `handle${index}`
246 }
247
248 /**
249 * Distinct from the menu-item module's `RouteConfig${index}` binding: both
250 * modules are concatenated into the same virtual file, so the route module
251 * needs its own local name to avoid a duplicate import declaration.
252 */
253 function generateRouteConfigName(index: number): string {
254 return `HandleConfig${index}`
255 }
256
257 function generateLoaderName(index: number): string {
258 return `loader${index}`
259 }
260
261 async function hasNamedExports(
262 ast: ParseResult<File>,
263 file: string
264 ): Promise<{ hasHandle: boolean; hasLoader: boolean; hasConfig: boolean }> {
265 let hasHandle = false
266 let hasLoader = false
267 let hasConfig = false
268
269 try {
270 traverse(ast, {
271 ExportNamedDeclaration(path) {
272 const declaration = path.node.declaration
273
274 // Handle: export const handle = {...}
275 if (declaration?.type === "VariableDeclaration") {
276 declaration.declarations.forEach((decl) => {
277 if (decl.id.type === "Identifier" && decl.id.name === "handle") {
278 hasHandle = true
279 }
280 if (decl.id.type === "Identifier" && decl.id.name === "loader") {
281 hasLoader = true
282 }
283 if (decl.id.type === "Identifier" && decl.id.name === "config") {
284 hasConfig = true
285 }
286 })
287 }
288
289 // Handle: export function loader() or export async function loader()
290 if (
291 declaration?.type === "FunctionDeclaration" &&
292 declaration.id?.name === "loader"
293 ) {
294 hasLoader = true
295 }
296 },
297 })
298 } catch (e) {
299 logger.error("An error occurred while checking for named exports.", {
300 file,
301 error: e,
302 })
303 }
304
305 return { hasHandle, hasLoader, hasConfig }
306 }