import { HttpError, notFound } from './http.js'; /** * Minimal router: `/api/repositories/:owner/:repo` style patterns, no dependency (M16-T01). * A trailing `*` captures the rest of the path under `params.rest`. */ function compile(pattern) { const segments = pattern.split('/').filter(Boolean); return { segments, pattern }; } function match(route, segments) { const params = {}; for (const [index, expected] of route.segments.entries()) { if (expected === '*') { params.rest = segments.slice(index).join('/'); return params; } const actual = segments[index]; if (actual === undefined) return null; if (expected.startsWith(':')) params[expected.slice(1)] = decodeURIComponent(actual); else if (expected !== actual) return null; } return segments.length === route.segments.length ? params : null; } export function createRouter() { const routes = []; const add = (method, pattern, handler, options = {}) => { routes.push({ method, ...compile(pattern), handler, options }); }; return { get: (pattern, handler, options) => add('GET', pattern, handler, options), post: (pattern, handler, options) => add('POST', pattern, handler, options), put: (pattern, handler, options) => add('PUT', pattern, handler, options), patch: (pattern, handler, options) => add('PATCH', pattern, handler, options), delete: (pattern, handler, options) => add('DELETE', pattern, handler, options), /** * Finds the handler for a request. * Throws 405 when the path exists under another method, which is easier to * debug from the browser console than a plain 404. */ resolve(method, pathname) { const segments = pathname.split('/').filter(Boolean); let pathMatched = false; for (const route of routes) { const params = match(route, segments); if (!params) continue; pathMatched = true; if (route.method === method) return { ...route, params }; } throw pathMatched ? new HttpError(405, `Méthode ${method} non autorisée ici`) : notFound(); }, list: () => routes.map((route) => `${route.method} ${route.pattern}`), }; }