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 getConfigObjectProperties,
7 getParserOptions,
8 hasDefaultExport,
9 normalizePath,
10 } from "../utils"
11 import { getLayoutFilesFromSources } from "./helpers"
12
13 type ParsedLayoutConfig = {
14 import: string
15 componentName: string
16 configName: string
17 }
18
19 export async function generateLayouts(sources: Set<string>) {
20 const files = await getLayoutFilesFromSources(sources)
21 const results = await getLayoutResults(files)
22
23 const imports = results.map((r) => r.import)
24 const code = generateCode(results)
25
26 return { imports, code }
27 }
28
29 async function getLayoutResults(
30 files: string[]
31 ): Promise<ParsedLayoutConfig[]> {
32 return (await Promise.all(files.map(parseFile))).filter(
33 (r) => r !== null
34 ) as ParsedLayoutConfig[]
35 }
36
37 function generateCode(results: ParsedLayoutConfig[]): string {
38 return outdent`
39 layouts: [
40 ${results
41 .map(
42 ({ componentName, configName }) =>
43 `{ ...${configName}, Component: ${componentName} }`
44 )
45 .join(",\n ")}
46 ]
47 `
48 }
49
50 async function parseFile(
51 file: string,
52 index: number
53 ): Promise<ParsedLayoutConfig | null> {
54 const code = await fs.readFile(file, "utf-8")
55 let ast: ParseResult<File>
56
57 try {
58 ast = parse(code, getParserOptions(file))
59 } catch (e) {
60 logger.error(`An error occurred while parsing the layout file.`, {
61 file,
62 error: e,
63 })
64 return null
65 }
66
67 let fileHasDefaultExport = false
68 try {
69 fileHasDefaultExport = await hasDefaultExport(ast)
70 } catch (e) {
71 logger.error(`An error occurred while checking for a default export.`, {
72 file,
73 error: e,
74 })
75 return null
76 }
77
78 if (!fileHasDefaultExport) {
79 logger.warn(`Layout file has no default export, skipping.`, { file })
80 return null
81 }
82
83 if (!hasConfigExport(ast)) {
84 logger.warn(
85 `Layout file has no 'config' named export. Export 'export const config = defineLayoutConfig(...)'.`,
86 { file }
87 )
88 return null
89 }
90
91 const componentName = `LayoutComponent${index}`
92 const configName = `LayoutConfig${index}`
93
94 return {
95 import: generateImport(file, componentName, configName),
96 componentName,
97 configName,
98 }
99 }
100
101 /**
102 * Checks whether the file exports a `config` defined via `defineLayoutConfig(...)`.
103 * This is a lightweight check — we don't validate the shape here; that
104 * happens at runtime when the layout is registered.
105 */
106 function hasConfigExport(ast: ParseResult<File>): boolean {
107 let found = false
108
109 traverse(ast, {
110 ExportNamedDeclaration(path) {
111 if (found) {
112 return
113 }
114 if (getConfigObjectProperties(path)) {
115 found = true
116 }
117 },
118 })
119
120 return found
121 }
122
123 function generateImport(
124 file: string,
125 componentName: string,
126 configName: string
127 ): string {
128 const path = normalizePath(file)
129 return `import ${componentName}, { config as ${configName} } from "${path}"`
130 }