1 import * as fs from "fs"
2 import * as path from "path"
3 import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils"
4 import { parse } from "@typescript-eslint/typescript-estree"
5 import { createRule } from "../../create-rule"
6 import { FRAMEWORK_HTTP_SOURCE } from "../../constants"
7 import { findApiRoot, getApiRouteSegments } from "../../util/api-route"
8
9 type MessageIds = "useValidatedBody" | "useValidatedQuery"
10
11 const HTTP_METHODS = new Set([
12 "GET",
13 "POST",
14 "PUT",
15 "PATCH",
16 "DELETE",
17 "OPTIONS",
18 "HEAD",
19 ])
20
21 const VALIDATE_BODY = "validateAndTransformBody"
22 const VALIDATE_QUERY = "validateAndTransformQuery"
23 const DEFINE_MIDDLEWARES = "defineMiddlewares"
24
25 const MIDDLEWARE_BASENAMES = ["middlewares.ts", "middlewares.js"]
26
27 type ValidationMap = {
28 body: Set<string> // uppercase HTTP methods covered by body validation; "*" means all
29 query: Set<string> // same for query validation
30 }
31
32 function getApiRoutePath(filename: string): string | null {
33 const segments = getApiRouteSegments(filename)
34 if (!segments) {
35 return null
36 }
37 return "/" + segments.join("/")
38 }
39
40 function findMiddlewaresFile(filename: string): string | null {
41 const apiRoot = findApiRoot(filename)
42 if (!apiRoot) {
43 return null
44 }
45 for (const base of MIDDLEWARE_BASENAMES) {
46 const candidate = `${apiRoot}/${base}`
47 if (fs.existsSync(candidate)) {
48 return candidate
49 }
50 }
51 return null
52 }
53
54 function matcherToRegex(matcher: string): RegExp {
55 // Convert Medusa matcher syntax to a regex.
56 // - `:param` segments → `[^/]+`
57 // - `*` → `.*`
58 // - escape other regex chars
59 let out = ""
60 let i = 0
61 while (i < matcher.length) {
62 const c = matcher[i]
63 if (c === ":") {
64 // skip param name
65 i++
66 while (i < matcher.length && /[A-Za-z0-9_]/.test(matcher[i])) {
67 i++
68 }
69 out += "[^/]+"
70 continue
71 }
72 if (c === "*") {
73 out += ".*"
74 i++
75 continue
76 }
77 if (/[.+?^${}()|[\]\\]/.test(c)) {
78 out += "\\" + c
79 } else {
80 out += c
81 }
82 i++
83 }
84 return new RegExp(`^${out}/?$`)
85 }
86
87 function routePathToMatchable(routePath: string): string {
88 // Convert `[id]` → `:id` so we can run the same regex.
89 return routePath.replace(/\[([A-Za-z_][A-Za-z0-9_]*)\]/g, ":$1")
90 }
91
92 function collectValidationFromMiddlewaresFile(
93 filePath: string,
94 routePath: string
95 ): ValidationMap | null {
96 let source: string
97 try {
98 source = fs.readFileSync(filePath, "utf8")
99 } catch {
100 return null
101 }
102 let ast: ReturnType<typeof parse>
103 try {
104 ast = parse(source, {
105 jsx: filePath.endsWith("x"),
106 loc: false,
107 range: false,
108 })
109 } catch {
110 return null
111 }
112
113 // Track local names for validateAndTransformBody/Query and defineMiddlewares
114 const bodyValidatorNames = new Set<string>()
115 const queryValidatorNames = new Set<string>()
116 const defineMiddlewaresNames = new Set<string>()
117
118 for (const node of ast.body) {
119 if (node.type !== "ImportDeclaration") {
120 continue
121 }
122 if (
123 typeof node.source.value !== "string" ||
124 node.source.value !== FRAMEWORK_HTTP_SOURCE
125 ) {
126 continue
127 }
128 for (const spec of node.specifiers) {
129 if (
130 spec.type !== "ImportSpecifier" ||
131 spec.imported.type !== "Identifier"
132 ) {
133 continue
134 }
135 if (spec.imported.name === VALIDATE_BODY) {
136 bodyValidatorNames.add(spec.local.name)
137 } else if (spec.imported.name === VALIDATE_QUERY) {
138 queryValidatorNames.add(spec.local.name)
139 } else if (spec.imported.name === DEFINE_MIDDLEWARES) {
140 defineMiddlewaresNames.add(spec.local.name)
141 }
142 }
143 }
144
145 const result: ValidationMap = { body: new Set(), query: new Set() }
146 const matchable = routePathToMatchable(routePath)
147
148 const extractMethods = (node: any): string[] => {
149 if (!node) {
150 return []
151 }
152 if (node.type === "Literal" && typeof node.value === "string") {
153 return [node.value.toUpperCase()]
154 }
155 if (node.type === "ArrayExpression") {
156 const out: string[] = []
157 for (const el of node.elements) {
158 if (el && el.type === "Literal" && typeof el.value === "string") {
159 out.push(el.value.toUpperCase())
160 }
161 }
162 return out
163 }
164 return []
165 }
166
167 const handleRouteEntry = (entry: any): void => {
168 if (!entry || entry.type !== "ObjectExpression") {
169 return
170 }
171 let matcher: string | null = null
172 let methods: string[] = []
173 let middlewares: any[] = []
174 for (const prop of entry.properties) {
175 if (
176 prop.type !== "Property" ||
177 prop.computed ||
178 (prop.key.type !== "Identifier" && prop.key.type !== "Literal")
179 ) {
180 continue
181 }
182 const keyName =
183 prop.key.type === "Identifier" ? prop.key.name : String(prop.key.value)
184 if (keyName === "matcher") {
185 if (
186 prop.value.type === "Literal" &&
187 typeof prop.value.value === "string"
188 ) {
189 matcher = prop.value.value
190 }
191 } else if (keyName === "method" || keyName === "methods") {
192 methods = extractMethods(prop.value)
193 } else if (keyName === "middlewares") {
194 if (prop.value.type === "ArrayExpression") {
195 middlewares = prop.value.elements
196 }
197 }
198 }
199 if (!matcher) {
200 return
201 }
202
203 let regex: RegExp
204 try {
205 regex = matcherToRegex(matcher)
206 } catch {
207 return
208 }
209 if (!regex.test(matchable)) {
210 return
211 }
212
213 const targets = methods.length ? methods : ["*"]
214 let hasBody = false
215 let hasQuery = false
216 for (const mw of middlewares) {
217 if (!mw || mw.type !== "CallExpression") {
218 continue
219 }
220 if (mw.callee.type !== "Identifier") {
221 continue
222 }
223 if (bodyValidatorNames.has(mw.callee.name)) {
224 hasBody = true
225 }
226 if (queryValidatorNames.has(mw.callee.name)) {
227 hasQuery = true
228 }
229 }
230 if (hasBody) {
231 for (const m of targets) {
232 result.body.add(m)
233 }
234 }
235 if (hasQuery) {
236 for (const m of targets) {
237 result.query.add(m)
238 }
239 }
240 }
241
242 const walk = (node: unknown): void => {
243 if (!node || typeof node !== "object") {
244 return
245 }
246 if (Array.isArray(node)) {
247 for (const child of node) {
248 walk(child)
249 }
250 return
251 }
252 const n = node as { type?: string; [k: string]: unknown }
253 if (
254 n.type === "CallExpression" &&
255 (n as any).callee?.type === "Identifier" &&
256 defineMiddlewaresNames.has((n as any).callee.name)
257 ) {
258 const arg = (n as any).arguments?.[0]
259 if (arg?.type === "ObjectExpression") {
260 for (const prop of arg.properties) {
261 if (
262 prop.type !== "Property" ||
263 prop.computed ||
264 !(
265 (prop.key.type === "Identifier" && prop.key.name === "routes") ||
266 (prop.key.type === "Literal" && prop.key.value === "routes")
267 )
268 ) {
269 continue
270 }
271 if (prop.value.type === "ArrayExpression") {
272 for (const el of prop.value.elements) {
273 handleRouteEntry(el)
274 }
275 }
276 }
277 }
278 }
279 for (const key of Object.keys(n)) {
280 if (key === "parent" || key === "loc" || key === "range") {
281 continue
282 }
283 walk(n[key])
284 }
285 }
286 walk(ast.body)
287 return result
288 }
289
290 function getHandlerFunction(
291 node: TSESTree.ExportNamedDeclaration
292 ): { fn: TSESTree.Node; method: string } | null {
293 const decl = node.declaration
294 if (!decl) {
295 return null
296 }
297 if (decl.type === AST_NODE_TYPES.VariableDeclaration) {
298 for (const d of decl.declarations) {
299 if (
300 d.id.type === AST_NODE_TYPES.Identifier &&
301 HTTP_METHODS.has(d.id.name) &&
302 d.init &&
303 (d.init.type === AST_NODE_TYPES.ArrowFunctionExpression ||
304 d.init.type === AST_NODE_TYPES.FunctionExpression)
305 ) {
306 return { fn: d.init, method: d.id.name }
307 }
308 }
309 return null
310 }
311 if (
312 decl.type === AST_NODE_TYPES.FunctionDeclaration &&
313 decl.id &&
314 HTTP_METHODS.has(decl.id.name)
315 ) {
316 return { fn: decl, method: decl.id.name }
317 }
318 return null
319 }
320
321 function getFirstParamName(
322 fn: TSESTree.Node
323 ):
324 | { name: string; pattern: false }
325 | { node: TSESTree.ObjectPattern; pattern: true }
326 | null {
327 if (
328 fn.type !== AST_NODE_TYPES.ArrowFunctionExpression &&
329 fn.type !== AST_NODE_TYPES.FunctionExpression &&
330 fn.type !== AST_NODE_TYPES.FunctionDeclaration
331 ) {
332 return null
333 }
334 const first = fn.params[0]
335 if (!first) {
336 return null
337 }
338 if (first.type === AST_NODE_TYPES.Identifier) {
339 return { name: first.name, pattern: false }
340 }
341 // Handle `(req: ..., res)` with type annotation wrapper — AST_NODE_TYPES.Identifier still
342 // For object destructuring: `({ body, query }, res) => ...`
343 if (first.type === AST_NODE_TYPES.ObjectPattern) {
344 return { node: first, pattern: true }
345 }
346 return null
347 }
348
349 export const rule = createRule<[], MessageIds>({
350 name: "use-validated-body-or-query",
351 meta: {
352 type: "suggestion",
353 docs: {
354 description:
355 "Prefer `req.validatedBody` / `req.validatedQuery` when a `validateAndTransformBody` / `validateAndTransformQuery` middleware is applied to the route.",
356 },
357 messages: {
358 useValidatedBody:
359 "Use `req.validatedBody` instead of `req.body`; `validateAndTransformBody` is applied to this route in the middlewares file.",
360 useValidatedQuery:
361 "Use `req.validatedQuery` instead of `req.query`; `validateAndTransformQuery` is applied to this route in the middlewares file.",
362 },
363 fixable: "code",
364 schema: [],
365 },
366 defaultOptions: [],
367 create(context) {
368 const filename = context.filename
369 if (!filename || filename.startsWith("<")) {
370 return {}
371 }
372 const base = path.basename(filename)
373 if (base !== "route.ts" && base !== "route.js" && base !== "route.tsx") {
374 return {}
375 }
376 const routePath = getApiRoutePath(filename)
377 if (!routePath) {
378 return {}
379 }
380
381 const middlewaresFile = findMiddlewaresFile(filename)
382 if (!middlewaresFile) {
383 return {}
384 }
385
386 const validation = collectValidationFromMiddlewaresFile(
387 middlewaresFile,
388 routePath
389 )
390 if (!validation) {
391 return {}
392 }
393 if (validation.body.size === 0 && validation.query.size === 0) {
394 return {}
395 }
396
397 const methodApplies = (set: Set<string>, method: string): boolean =>
398 set.has("*") || set.has(method)
399
400 const handlerFns: Array<{
401 fn: TSESTree.Node
402 paramName: string
403 method: string
404 }> = []
405
406 return {
407 ExportNamedDeclaration(node) {
408 const handler = getHandlerFunction(node)
409 if (!handler) {
410 return
411 }
412 const param = getFirstParamName(handler.fn)
413 if (!param || param.pattern) {
414 return
415 }
416 handlerFns.push({
417 fn: handler.fn,
418 paramName: param.name,
419 method: handler.method,
420 })
421 },
422 "Program:exit"() {
423 for (const h of handlerFns) {
424 const reqName = h.paramName
425 const flagBody = methodApplies(validation.body, h.method)
426 const flagQuery = methodApplies(validation.query, h.method)
427 if (!flagBody && !flagQuery) {
428 continue
429 }
430 const visit = (node: TSESTree.Node): void => {
431 if (
432 node.type === AST_NODE_TYPES.MemberExpression &&
433 !node.computed &&
434 node.object.type === AST_NODE_TYPES.Identifier &&
435 node.object.name === reqName &&
436 node.property.type === AST_NODE_TYPES.Identifier
437 ) {
438 if (flagBody && node.property.name === "body") {
439 context.report({
440 node,
441 messageId: "useValidatedBody",
442 fix: (fixer) =>
443 fixer.replaceText(node.property, "validatedBody"),
444 })
445 } else if (flagQuery && node.property.name === "query") {
446 context.report({
447 node,
448 messageId: "useValidatedQuery",
449 fix: (fixer) =>
450 fixer.replaceText(node.property, "validatedQuery"),
451 })
452 }
453 }
454 for (const key of Object.keys(node) as Array<keyof typeof node>) {
455 if (key === "parent") {
456 continue
457 }
458 const value = (node as unknown as Record<string, unknown>)[
459 key as string
460 ]
461 if (!value) {
462 continue
463 }
464 if (Array.isArray(value)) {
465 for (const child of value) {
466 if (child && typeof child === "object" && "type" in child) {
467 visit(child as TSESTree.Node)
468 }
469 }
470 } else if (
471 typeof value === "object" &&
472 "type" in (value as object)
473 ) {
474 visit(value as TSESTree.Node)
475 }
476 }
477 }
478 const fn = h.fn as TSESTree.FunctionLike
479 if ("body" in fn && fn.body) {
480 visit(fn.body as TSESTree.Node)
481 }
482 }
483 },
484 }
485 },
486 })
487
488 export default rule