1 import {
2 NESTED_ROUTE_POSITIONS,
3 NestedRoutePosition,
4 } from "@medusajs/admin-shared"
5 import fs from "fs/promises"
6 import { outdent } from "outdent"
7 import {
8 File,
9 isIdentifier,
10 isNumericLiteral,
11 isObjectProperty,
12 isStringLiteral,
13 Node,
14 ObjectProperty,
15 parse,
16 ParseResult,
17 traverse,
18 } from "../babel"
19 import { logger } from "../logger"
20 import {
21 crawl,
22 getConfigObjectProperties,
23 getParserOptions,
24 normalizePath,
25 } from "../utils"
26 import { getRoute } from "./helpers"
27
28 type RouteConfig = {
29 label: boolean
30 icon: boolean
31 nested?: NestedRoutePosition
32 rank?: number
33 translationNs?: string
34 }
35
36 type MenuItem = {
37 icon?: string
38 label: string
39 path: string
40 nested?: NestedRoutePosition
41 rank?: number
42 translationNs?: string
43 }
44
45 type MenuItemResult = {
46 import: string
47 menuItem: MenuItem
48 }
49
50 export async function generateMenuItems(sources: Set<string>) {
51 const files = await getFilesFromSources(sources)
52 const results = await getMenuItemResults(files)
53
54 const imports = results.map((result) => result.import)
55 const code = generateCode(results)
56
57 return { imports, code }
58 }
59
60 function generateCode(results: MenuItemResult[]): string {
61 return outdent`
62 menuItems: [
63 ${results
64 .map((result) => formatMenuItem(result.menuItem))
65 .join(",\n")}
66 ]
67 }
68 `
69 }
70
71 function formatMenuItem(route: MenuItem): string {
72 const { label, icon, path, nested, rank, translationNs } = route
73 return `{
74 label: ${label},
75 icon: ${icon || "undefined"},
76 path: "${path}",
77 nested: ${nested ? `"${nested}"` : "undefined"},
78 rank: ${rank !== undefined ? rank : "undefined"},
79 translationNs: ${translationNs ? `${translationNs}` : "undefined"}
80 }`
81 }
82
83 async function getFilesFromSources(sources: Set<string>): Promise<string[]> {
84 const files = (
85 await Promise.all(
86 Array.from(sources).map(async (source) =>
87 crawl(`${source}/routes`, "page", { min: 1 })
88 )
89 )
90 ).flat()
91 return files
92 }
93
94 async function getMenuItemResults(files: string[]): Promise<MenuItemResult[]> {
95 const results = await Promise.all(files.map(parseFile))
96 return results.filter((item): item is MenuItemResult => item !== null)
97 }
98
99 async function parseFile(
100 file: string,
101 index: number
102 ): Promise<MenuItemResult | null> {
103 const config = await getRouteConfig(file)
104
105 if (!config) {
106 return null
107 }
108
109 if (!config.label) {
110 logger.warn(`Config is missing a label.`, {
111 file,
112 })
113 }
114
115 const import_ = generateImport(file, index)
116 const menuItem = generateMenuItem(config, file, index)
117
118 return {
119 import: import_,
120 menuItem,
121 }
122 }
123
124 function generateImport(file: string, index: number): string {
125 const path = normalizePath(file)
126 return `import { config as ${generateRouteConfigName(index)} } from "${path}"`
127 }
128
129 function generateMenuItem(
130 config: RouteConfig,
131 file: string,
132 index: number
133 ): MenuItem {
134 const configName = generateRouteConfigName(index)
135 return {
136 label: `${configName}.label`,
137 icon: config.icon ? `${configName}.icon` : undefined,
138 path: getRoute(file),
139 nested: config.nested,
140 rank: config.rank,
141 translationNs: config.translationNs
142 ? `${configName}.translationNs`
143 : undefined,
144 }
145 }
146
147 async function getRouteConfig(file: string): Promise<RouteConfig | null> {
148 const code = await fs.readFile(file, "utf-8")
149 let ast: ParseResult<File> | null = null
150
151 try {
152 ast = parse(code, getParserOptions(file))
153 } catch (e) {
154 logger.error(`An error occurred while parsing the file.`, {
155 file,
156 error: e,
157 })
158 return null
159 }
160
161 let config: RouteConfig | null = null
162 let configFound = false
163
164 try {
165 traverse(ast, {
166 /**
167 * For bundled files, the config will not be a named export,
168 * but instead a variable declaration.
169 */
170 VariableDeclarator(path) {
171 if (configFound) {
172 return
173 }
174
175 const properties = getConfigObjectProperties(path)
176 if (!properties) {
177 return
178 }
179
180 config = processConfigProperties(properties, file)
181
182 if (config) {
183 configFound = true
184 }
185 },
186 /**
187 * For unbundled files, the `config` will always be a named export.
188 */
189 ExportNamedDeclaration(path) {
190 if (configFound) {
191 return
192 }
193
194 const properties = getConfigObjectProperties(path)
195 if (!properties) {
196 return
197 }
198
199 config = processConfigProperties(properties, file)
200
201 if (config) {
202 configFound = true
203 }
204 },
205 })
206 } catch (e) {
207 logger.error(`An error occurred while traversing the file.`, {
208 file,
209 error: e,
210 })
211 }
212
213 return config
214 }
215
216 function processConfigProperties(
217 properties: Node[],
218 file: string
219 ): RouteConfig | null {
220 const hasProperty = (name: string) =>
221 properties.some(
222 (prop) => isObjectProperty(prop) && isIdentifier(prop.key, { name })
223 )
224
225 const hasLabel = hasProperty("label")
226 if (!hasLabel) {
227 return null
228 }
229
230 const nested = properties.find(
231 (prop) =>
232 isObjectProperty(prop) && isIdentifier(prop.key, { name: "nested" })
233 ) as ObjectProperty | undefined
234
235 let nestedValue: string | undefined
236
237 if (isStringLiteral(nested?.value)) {
238 nestedValue = nested.value.value
239 }
240
241 if (
242 nestedValue &&
243 !NESTED_ROUTE_POSITIONS.includes(nestedValue as NestedRoutePosition)
244 ) {
245 logger.error(
246 `Invalid nested route position: "${nestedValue}". Allowed values are: ${NESTED_ROUTE_POSITIONS.join(
247 ", "
248 )}`,
249 { file }
250 )
251 return null
252 }
253
254 const translationNs = properties.find(
255 (prop) =>
256 isObjectProperty(prop) && isIdentifier(prop.key, { name: "translationNs" })
257 ) as ObjectProperty | undefined
258
259 let translationNsValue: string | undefined = undefined
260
261 if (isStringLiteral(translationNs?.value)) {
262 translationNsValue = translationNs.value.value
263 }
264
265 const rank = properties.find(
266 (prop) =>
267 isObjectProperty(prop) && isIdentifier(prop.key, { name: "rank" })
268 ) as ObjectProperty | undefined
269
270 let rankValue: number | undefined
271
272 if (isNumericLiteral(rank?.value)) {
273 rankValue = rank.value.value
274 }
275
276 return {
277 label: hasLabel,
278 icon: hasProperty("icon"),
279 nested: nestedValue as NestedRoutePosition | undefined,
280 rank: rankValue,
281 translationNs: translationNsValue,
282 }
283 }
284
285 function generateRouteConfigName(index: number): string {
286 return `RouteConfig${index}`
287 }