1 import { createRule } from "../../create-rule"
2 import { toPosix } from "../../util/filename"
3 import { getApiRouteSegments } from "../../util/api-route"
4
5 type MessageIds = "invalidDynamicFolder" | "leadingDynamicFolder"
6
7 const VALID_PARAM_FOLDER = /^\[[a-zA-Z_][a-zA-Z0-9_]*\]$/
8 const BRACKETED_FOLDER = /^\[.*\]$/
9
10 /**
11 * Returns the route's path segments (excluding the `route.ts` / `page.tsx`
12 * file), relative to the route root — `src/api/` for API routes (so the first
13 * segment is the first path part after `/api`, regardless of any group such as
14 * `store`/`admin`/`auth`/custom), or `src/admin/routes/` for admin UI routes.
15 * Returns `null` when the file isn't a route.
16 *
17 * A dynamic segment at index 0 therefore means the route starts with a
18 * parameter, which Medusa doesn't allow.
19 */
20 function getRouteSegments(filename: string): string[] | null {
21 const apiSegments = getApiRouteSegments(filename)
22 if (apiSegments) {
23 return apiSegments
24 }
25
26 const posix = toPosix(filename)
27 const adminMatch =
28 posix.match(/(?:^|\/)src\/admin\/routes\/(.+)$/) ??
29 posix.match(/(?:^|\/)admin\/routes\/(.+)$/)
30
31 if (adminMatch) {
32 const segments = adminMatch[1].split("/")
33 segments.pop()
34 return segments
35 }
36
37 return null
38 }
39
40 export const rule = createRule<[], MessageIds>({
41 name: "route-dynamic-folder-syntax",
42 meta: {
43 type: "problem",
44 docs: {
45 description:
46 "Dynamic route parameters must use `[param]` folder syntax and cannot appear as the first segment of a route.",
47 },
48 messages: {
49 invalidDynamicFolder:
50 "Invalid dynamic route folder `{{segment}}`. Medusa only recognizes `[param]` (single brackets, identifier name).",
51 leadingDynamicFolder:
52 "Route cannot start with a dynamic segment `{{segment}}`. Add a static prefix segment before it.",
53 },
54 schema: [],
55 },
56 defaultOptions: [],
57 create(context) {
58 const filename = context.filename
59 if (!filename || filename.startsWith("<")) {
60 return {}
61 }
62
63 const segments = getRouteSegments(filename)
64 if (!segments) {
65 return {}
66 }
67
68 return {
69 Program(node) {
70 for (let i = 0; i < segments.length; i++) {
71 const segment = segments[i]
72 if (!BRACKETED_FOLDER.test(segment)) {
73 continue
74 }
75
76 if (!VALID_PARAM_FOLDER.test(segment)) {
77 context.report({
78 node,
79 messageId: "invalidDynamicFolder",
80 data: { segment },
81 })
82 continue
83 }
84
85 if (i === 0) {
86 context.report({
87 node,
88 messageId: "leadingDynamicFolder",
89 data: { segment },
90 })
91 }
92 }
93 },
94 }
95 },
96 })
97
98 export default rule