All files / src/core/routing route-matcher.ts

100% Statements 13/13
83.33% Branches 5/6
100% Functions 3/3
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                                  41x 41x     42x     41x 38x 38x   36x 36x   8x 8x     36x             5x      
/**
 * Route matching against requests
 * Core logic - no Vite dependencies
 */
 
import type { Route, RouteMatch } from './route-types.js';
import { normalizePath } from '../../shared/utils.js';
 
/**
 * Finds the route that matches a path and method
 */
export function matchRoute(
  routes: Route[],
  path: string,
  method: string
): RouteMatch | null {
  // Normalize path ensuring it starts with /
  const normalizedPath = path.startsWith('/') ? path : `/${path}`;
  const normalizedMethod = method.toLowerCase();
  
  // Filter routes by method
  const methodRoutes = routes.filter(r => r.method === normalizedMethod);
  
  // Try to match in order
  for (const route of methodRoutes) {
    const match = normalizedPath.match(route.regex);
    if (match) {
      // Extract parameters from match
      const params: Record<string, string> = {};
      route.params.forEach((paramName, index) => {
        // +1 because match[0] is the complete match
        const value = match[index + 1];
        params[paramName] = value !== undefined ? value : '';
      });
      
      return {
        route,
        params,
      };
    }
  }
  
  return null;
}