1 import chalk from "chalk"
2 import { globSync } from "glob"
3 import { dirname, resolve } from "path"
4 import ts from "typescript"
5 import { API_ROUTE_PARAM_REGEX } from "../../constants.js"
6 import loadTsModule from "../../utils/load-ts-module.js"
7
8 const VALIDATE_QUERY_FN_NAME = "validateAndTransformQuery"
9 const PARAM_PLACEHOLDER = "1"
10
11 /**
12 * The fields and relations restrictions of an API route's query configuration.
13 */
14 export type FieldRestrictions = {
15 /**
16 * The fields and relations that can be requested. If it's not set, all
17 * fields and relations can be requested.
18 */
19 allowed?: string[]
20 /**
21 * The fields and relations that can never be requested.
22 */
23 disallowed?: string[]
24 }
25
26 /**
27 * A route's query configuration, as referenced in a middleware.
28 */
29 type QueryConfigReference = {
30 /**
31 * The path of the file exporting the query configuration, without its extension.
32 */
33 modulePath: string
34 /**
35 * The name of the exported query configuration.
36 */
37 exportName: string
38 }
39
40 type MiddlewareRoute = {
41 matcher: string
42 methods: string[]
43 queryConfig: QueryConfigReference
44 }
45
46 /**
47 * Helper used to retrieve the query configuration that an API route's middleware
48 * applies to it. Since the configuration isn't available in the route's file, its
49 * middlewares are parsed to find it.
50 */
51 export default class QueryConfigHelper {
52 private middlewareRoutes: Map<string, MiddlewareRoute[]> = new Map()
53
54 /**
55 * Retrieve the fields and relations restrictions applied to an API route.
56 *
57 * @param param0 - The route's details.
58 * @returns The route's restrictions, if it has any.
59 */
60 getFieldRestrictions({
61 routeFilePath,
62 oasPath,
63 httpMethod,
64 }: {
65 /**
66 * The path of the route's file.
67 */
68 routeFilePath: string
69 /**
70 * The route's OAS path, such as `store/products/[id]`.
71 */
72 oasPath: string
73 /**
74 * The route's lowercase HTTP method, such as `get`.
75 */
76 httpMethod: string
77 }): FieldRestrictions | undefined {
78 const apiPath = this.getApiPath(routeFilePath)
79
80 if (!apiPath) {
81 return
82 }
83
84 const middlewareRoute = this.findMiddlewareRoute({
85 middlewareRoutes: this.getMiddlewareRoutes(apiPath),
86 oasPath,
87 httpMethod,
88 })
89
90 if (!middlewareRoute) {
91 return
92 }
93
94 const queryConfig = this.loadQueryConfig(middlewareRoute.queryConfig)
95
96 if (!queryConfig) {
97 return
98 }
99
100 const allowed = this.normalizeFields(queryConfig.allowed)
101 const disallowed = this.normalizeFields(queryConfig.disallowed)
102
103 if (!allowed?.length && !disallowed?.length) {
104 return
105 }
106
107 return {
108 ...(allowed?.length ? { allowed } : {}),
109 ...(disallowed?.length ? { disallowed } : {}),
110 }
111 }
112
113 /**
114 * Retrieve the path of the `api` directory that a route belongs to.
115 *
116 * @param routeFilePath - The path of the route's file.
117 * @returns The path of the `api` directory, if found.
118 */
119 private getApiPath(routeFilePath: string): string | undefined {
120 const apiIndex = routeFilePath.indexOf("/api/")
121
122 return apiIndex === -1
123 ? undefined
124 : routeFilePath.substring(0, apiIndex + "/api".length)
125 }
126
127 /**
128 * Retrieve the routes that the middlewares of an `api` directory are applied to.
129 * The routes are cached since they're the same for every route of the directory.
130 *
131 * @param apiPath - The path of the `api` directory.
132 * @returns The middlewares' routes.
133 */
134 private getMiddlewareRoutes(apiPath: string): MiddlewareRoute[] {
135 const cachedRoutes = this.middlewareRoutes.get(apiPath)
136
137 if (cachedRoutes) {
138 return cachedRoutes
139 }
140
141 const routes = globSync("**/middlewares.ts", {
142 cwd: apiPath,
143 absolute: true,
144 }).flatMap((filePath) => this.parseMiddlewareFile(filePath))
145
146 this.middlewareRoutes.set(apiPath, routes)
147
148 return routes
149 }
150
151 /**
152 * Parse a middlewares file to retrieve the routes that apply a query configuration.
153 *
154 * @param filePath - The path of the middlewares file.
155 * @returns The file's middleware routes.
156 */
157 private parseMiddlewareFile(filePath: string): MiddlewareRoute[] {
158 const sourceFile = ts.createSourceFile(
159 filePath,
160 ts.sys.readFile(filePath) || "",
161 ts.ScriptTarget.ES2021,
162 true
163 )
164 const routes: MiddlewareRoute[] = []
165
166 const findRoutes = (node: ts.Node) => {
167 if (ts.isObjectLiteralExpression(node)) {
168 const route = this.parseMiddlewareRoute(node, sourceFile)
169
170 if (route) {
171 routes.push(route)
172 }
173 }
174
175 ts.forEachChild(node, findRoutes)
176 }
177
178 findRoutes(sourceFile)
179
180 return routes
181 }
182
183 /**
184 * Parse an object literal into a middleware route.
185 *
186 * @param node - The object literal to parse.
187 * @param sourceFile - The source file that the object literal belongs to.
188 * @returns The middleware route, if the object literal is one that applies a
189 * query configuration.
190 */
191 private parseMiddlewareRoute(
192 node: ts.ObjectLiteralExpression,
193 sourceFile: ts.SourceFile
194 ): MiddlewareRoute | undefined {
195 const matcherProperty = this.getProperty(node, "matcher")
196 const middlewaresProperty = this.getProperty(node, "middlewares")
197
198 if (
199 !matcherProperty ||
200 !middlewaresProperty ||
201 !ts.isStringLiteralLike(matcherProperty.initializer) ||
202 !ts.isArrayLiteralExpression(middlewaresProperty.initializer)
203 ) {
204 return
205 }
206
207 const validateQueryCall = middlewaresProperty.initializer.elements.find(
208 (element) =>
209 ts.isCallExpression(element) &&
210 element.expression.getText() === VALIDATE_QUERY_FN_NAME
211 ) as ts.CallExpression | undefined
212 const queryConfigArgument = validateQueryCall?.arguments[1]
213
214 if (!queryConfigArgument) {
215 return
216 }
217
218 const queryConfig = this.getQueryConfigReference(
219 queryConfigArgument,
220 sourceFile
221 )
222
223 if (!queryConfig) {
224 return
225 }
226
227 return {
228 matcher: matcherProperty.initializer.text,
229 methods: this.getMethods(node),
230 queryConfig,
231 }
232 }
233
234 /**
235 * Retrieve the file and export name of the query configuration passed to a
236 * middleware.
237 *
238 * @param node - The expression passed as the query configuration.
239 * @param sourceFile - The source file that the expression belongs to.
240 * @returns The query configuration's reference, if it can be resolved.
241 */
242 private getQueryConfigReference(
243 node: ts.Expression,
244 sourceFile: ts.SourceFile
245 ): QueryConfigReference | undefined {
246 // the configuration is either accessed through a namespace import, such as
247 // `QueryConfig.listProductQueryConfig`, or imported directly.
248 const localName = ts.isPropertyAccessExpression(node)
249 ? node.expression.getText()
250 : ts.isIdentifier(node)
251 ? node.getText()
252 : undefined
253 const exportName = ts.isPropertyAccessExpression(node)
254 ? node.name.getText()
255 : localName
256
257 if (!localName || !exportName) {
258 return
259 }
260
261 const importPath = this.getImportPath(localName, sourceFile)
262
263 return {
264 modulePath: importPath
265 ? resolve(dirname(sourceFile.fileName), importPath)
266 : sourceFile.fileName,
267 exportName,
268 }
269 }
270
271 /**
272 * Retrieve the relative path that a name is imported from in a file.
273 *
274 * @param localName - The name as it's used in the file.
275 * @param sourceFile - The file to retrieve the import path from.
276 * @returns The import's relative path, if the name is imported.
277 */
278 private getImportPath(
279 localName: string,
280 sourceFile: ts.SourceFile
281 ): string | undefined {
282 let importPath: string | undefined
283
284 sourceFile.statements.forEach((statement) => {
285 if (
286 importPath ||
287 !ts.isImportDeclaration(statement) ||
288 !ts.isStringLiteralLike(statement.moduleSpecifier) ||
289 !statement.importClause?.namedBindings
290 ) {
291 return
292 }
293
294 const { namedBindings } = statement.importClause
295 const isImported = ts.isNamespaceImport(namedBindings)
296 ? namedBindings.name.getText() === localName
297 : namedBindings.elements.some(
298 (element) => element.name.getText() === localName
299 )
300
301 if (isImported) {
302 importPath = statement.moduleSpecifier.text
303 }
304 })
305
306 return importPath
307 }
308
309 /**
310 * Retrieve the HTTP methods that a middleware route is applied to.
311 *
312 * @param node - The middleware route's object literal.
313 * @returns The uppercase HTTP methods.
314 */
315 private getMethods(node: ts.ObjectLiteralExpression): string[] {
316 const methodProperty = this.getProperty(node, "method")
317
318 if (!methodProperty) {
319 return []
320 }
321
322 const { initializer } = methodProperty
323
324 if (ts.isStringLiteralLike(initializer)) {
325 return [initializer.text]
326 }
327
328 if (!ts.isArrayLiteralExpression(initializer)) {
329 return []
330 }
331
332 return initializer.elements
333 .filter((element) => ts.isStringLiteralLike(element))
334 .map((element) => (element as ts.StringLiteral).text)
335 }
336
337 private getProperty(
338 node: ts.ObjectLiteralExpression,
339 name: string
340 ): ts.PropertyAssignment | undefined {
341 return node.properties.find(
342 (property): property is ts.PropertyAssignment =>
343 ts.isPropertyAssignment(property) && property.name.getText() === name
344 )
345 }
346
347 /**
348 * Find the middleware route that applies a query configuration to an API route.
349 * Since more than one middleware route can match, such as a wildcard matcher and
350 * an exact one, the most specific match is used.
351 *
352 * @param param0 - The API route's details.
353 * @returns The matching middleware route, if any.
354 */
355 private findMiddlewareRoute({
356 middlewareRoutes,
357 oasPath,
358 httpMethod,
359 }: {
360 middlewareRoutes: MiddlewareRoute[]
361 oasPath: string
362 httpMethod: string
363 }): MiddlewareRoute | undefined {
364 const routePath = `/${oasPath.replaceAll(
365 API_ROUTE_PARAM_REGEX,
366 PARAM_PLACEHOLDER
367 )}`
368 const method = httpMethod.toUpperCase()
369
370 return middlewareRoutes
371 .filter((middlewareRoute) => {
372 const matchesMethod = middlewareRoute.methods.some(
373 (middlewareMethod) =>
374 middlewareMethod === "ALL" || middlewareMethod === method
375 )
376
377 return (
378 matchesMethod &&
379 this.matcherToRegex(middlewareRoute.matcher).test(routePath)
380 )
381 })
382 .sort(
383 (matchA, matchB) =>
384 this.getMatcherSpecificity(matchB.matcher) -
385 this.getMatcherSpecificity(matchA.matcher)
386 )
387 .at(0)
388 }
389
390 /**
391 * Convert a middleware's matcher into a regular expression that can be tested
392 * against a route's path. Path parameters are matched by name-insensitive
393 * patterns since a matcher's parameter name can be different than the route
394 * directory's, and `*` is matched as a wildcard.
395 *
396 * @param matcher - The matcher to convert.
397 * @returns The matcher's regular expression.
398 */
399 private matcherToRegex(matcher: string): RegExp {
400 const pattern = matcher
401 .split("/")
402 .map((segment) => {
403 return segment.startsWith(":")
404 ? PARAM_PLACEHOLDER
405 : segment
406 .replaceAll(/[.+?^${}()|[\]\\]/g, "\\$&")
407 .replaceAll("*", ".*")
408 })
409 .join("/")
410
411 return new RegExp(`^${pattern}$`)
412 }
413
414 /**
415 * Retrieve how specific a matcher is, which is used to choose between matchers
416 * that are applied to the same route. A matcher without wildcards is more
417 * specific than one with them, and a longer matcher is more specific than a
418 * shorter one.
419 *
420 * @param matcher - The matcher to check.
421 * @returns The matcher's specificity.
422 */
423 private getMatcherSpecificity(matcher: string): number {
424 return matcher.includes("*") ? matcher.length : matcher.length + 1000
425 }
426
427 /**
428 * Load the query configuration that a middleware applies.
429 *
430 * @param param0 - The query configuration's reference.
431 * @returns The query configuration, if it can be loaded.
432 */
433 private loadQueryConfig({
434 modulePath,
435 exportName,
436 }: QueryConfigReference):
437 | { allowed?: unknown; disallowed?: unknown }
438 | undefined {
439 try {
440 const queryConfig = loadTsModule(modulePath.replace(/\.tsx?$/, ""))[
441 exportName
442 ]
443
444 return typeof queryConfig === "object" && queryConfig !== null
445 ? (queryConfig as { allowed?: unknown; disallowed?: unknown })
446 : undefined
447 } catch (e) {
448 console.warn(
449 chalk.yellow(
450 `[WARNING] Couldn't load the query configuration ${exportName} of ${modulePath}: ${
451 e instanceof Error ? e.message : e
452 }`
453 )
454 )
455 return
456 }
457 }
458
459 /**
460 * Normalize the fields of a query configuration into strings that can be added
461 * to an OAS. Regular expressions are kept as patterns since they express a
462 * family of fields, such as `/_link$/`.
463 *
464 * @param fields - The fields to normalize.
465 * @returns The normalized fields without duplicates.
466 */
467 private normalizeFields(fields: unknown): string[] | undefined {
468 if (!Array.isArray(fields)) {
469 return
470 }
471
472 const normalizedFields = fields
473 .map((field) => {
474 if (typeof field === "string") {
475 return field
476 }
477
478 // the fields are evaluated in a separate context, so a regular expression
479 // there isn't an instance of this context's `RegExp`.
480 return Object.prototype.toString.call(field) === "[object RegExp]"
481 ? String(field)
482 : undefined
483 })
484 .filter((field): field is string => field !== undefined)
485
486 return Array.from(new Set(normalizedFields))
487 }
488 }