1 import { z } from "@medusajs/deps/zod"
2 import { dynamicImport, FileSystem, isFileSkipped } from "@medusajs/utils"
3 import { join } from "path"
4
5 import { logger } from "../logger"
6 import {
7 type AdditionalDataValidatorRoute,
8 type BodyParserConfigRoute,
9 HTTP_METHODS,
10 type MedusaErrorHandlerFunction,
11 type MiddlewareDescriptor,
12 type MiddlewaresConfig,
13 } from "./types"
14
15 /**
16 * File name that is used to indicate that the file is a middleware file
17 */
18 const MIDDLEWARE_FILE_NAME = "middlewares"
19
20 /**
21 * Exposes the API to scan a directory and load the `middleware.ts` file. This file contains
22 * the configuration for certain global middlewares and core routes validators. Also, it may
23 * contain custom middlewares.
24 */
25 export class MiddlewareFileLoader {
26 /**
27 * Global error handler exported from the middleware file loader
28 */
29 #errorHandler?: MedusaErrorHandlerFunction
30
31 /**
32 * Middleware collected manually or by scanning directories
33 */
34 #middleware: MiddlewareDescriptor[] = []
35
36 /**
37 * Route matchers on which a custom additional data validator is
38 * defined
39 */
40 #additionalDataValidatorRoutes: AdditionalDataValidatorRoute[] = []
41
42 /**
43 * Route matchers on which a custom body parser config is used
44 */
45 #bodyParserConfigRoutes: BodyParserConfigRoute[] = []
46
47 /**
48 * Processes the middleware file and returns the middleware and the
49 * routes config exported by it.
50 */
51 async #processMiddlewareFile(absolutePath: string): Promise<void> {
52 const middlewareExports = await dynamicImport(absolutePath)
53
54 if (isFileSkipped(middlewareExports)) {
55 return
56 }
57
58 const middlewareConfig = middlewareExports.default
59 if (!middlewareConfig) {
60 logger.warn(
61 `No middleware configuration found in ${absolutePath}. Skipping middleware configuration.`
62 )
63 return
64 }
65
66 const routes = middlewareConfig.routes as MiddlewaresConfig["routes"]
67 if (!routes || !Array.isArray(routes)) {
68 logger.warn(
69 `Invalid default export found in ${absolutePath}. Make sure to use "defineMiddlewares" function and export its output.`
70 )
71 return
72 }
73
74 const result = routes.reduce<{
75 bodyParserConfigRoutes: BodyParserConfigRoute[]
76 additionalDataValidatorRoutes: AdditionalDataValidatorRoute[]
77 middleware: MiddlewareDescriptor[]
78 }>(
79 (result, route) => {
80 if (!route.matcher) {
81 throw new Error(
82 `Middleware is missing a \`matcher\` field. The 'matcher' field is required when applying middleware. ${JSON.stringify(
83 route,
84 null,
85 2
86 )}`
87 )
88 }
89
90 /**
91 * The matcher can be a string or a regular expression.
92 * A regular expression must be preserved as-is so that it can be passed
93 * to Express directly. Stringifying it (e.g. via `String(regexp)`) turns
94 * it into its literal source (`/^\/admin$/`), which Express then compiles
95 * as a string path that matches no request, silently disabling the
96 * middleware.
97 */
98 const matcher =
99 route.matcher instanceof RegExp
100 ? route.matcher
101 : String(route.matcher)
102
103 if (route.bodyParser !== undefined) {
104 let methods = route.methods || [...HTTP_METHODS]
105 if (methods.includes("ALL")) {
106 methods = [...HTTP_METHODS]
107 }
108
109 logger.debug(
110 `using custom bodyparser config on matcher ${methods}:${route.matcher}`
111 )
112
113 result.bodyParserConfigRoutes.push({
114 matcher: matcher,
115 methods,
116 config: route.bodyParser,
117 })
118 }
119
120 if (route.additionalDataValidator !== undefined) {
121 let methods = route.methods || [...HTTP_METHODS]
122 if (methods.includes("ALL")) {
123 methods = [...HTTP_METHODS]
124 }
125
126 logger.debug(
127 `assigning additionalData validator on matcher ${methods}:${route.matcher}`
128 )
129
130 result.additionalDataValidatorRoutes.push({
131 matcher: matcher,
132 methods,
133 schema: route.additionalDataValidator,
134 validator: z.object(route.additionalDataValidator).nullish(),
135 })
136 }
137
138 if (route.middlewares || route.policies) {
139 const middlewares = route.middlewares ?? []
140 if (route.policies && !route.middlewares?.length) {
141 middlewares.push((_, __, next) => {
142 next()
143 })
144 }
145
146 middlewares.forEach((middleware) => {
147 result.middleware.push({
148 handler: middleware,
149 matcher: matcher,
150 methods: route.methods,
151 policies: route.policies,
152 })
153 })
154 }
155 return result
156 },
157 {
158 bodyParserConfigRoutes: [],
159 additionalDataValidatorRoutes: [],
160 middleware: [],
161 }
162 )
163
164 const errorHandler =
165 middlewareConfig.errorHandler as MiddlewaresConfig["errorHandler"]
166
167 if (errorHandler) {
168 this.#errorHandler = errorHandler
169 }
170 this.#middleware = this.#middleware.concat(result.middleware)
171 this.#bodyParserConfigRoutes = this.#bodyParserConfigRoutes.concat(
172 result.bodyParserConfigRoutes
173 )
174 this.#additionalDataValidatorRoutes =
175 this.#additionalDataValidatorRoutes.concat(
176 result.additionalDataValidatorRoutes
177 )
178 }
179
180 /**
181 * Scans a given directory for the "middleware.ts" or "middleware.js" files and
182 * imports them for reading the registered middleware and configuration for
183 * existing routes/middleware.
184 */
185 async scanDir(sourceDir: string) {
186 const fs = new FileSystem(sourceDir)
187 if (await fs.exists(`${MIDDLEWARE_FILE_NAME}.ts`)) {
188 await this.#processMiddlewareFile(
189 join(sourceDir, `${MIDDLEWARE_FILE_NAME}.ts`)
190 )
191 } else if (await fs.exists(`${MIDDLEWARE_FILE_NAME}.js`)) {
192 await this.#processMiddlewareFile(
193 join(sourceDir, `${MIDDLEWARE_FILE_NAME}.js`)
194 )
195 }
196 }
197
198 /**
199 * Returns the globally registered error handler (if any)
200 */
201 getErrorHandler() {
202 return this.#errorHandler
203 }
204
205 /**
206 * Returns a collection of registered middleware
207 */
208 getMiddlewares() {
209 return this.#middleware
210 }
211
212 /**
213 * Returns routes that have bodyparser config on them
214 */
215 getBodyParserConfigRoutes() {
216 return this.#bodyParserConfigRoutes
217 }
218
219 /**
220 * Returns routes that have additional validator configured
221 * on them
222 */
223 getAdditionalDataValidatorRoutes() {
224 return this.#additionalDataValidatorRoutes
225 }
226 }