router.ts 2.05 KB
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Route, ServerCtx } from './context';

interface CompiledRoute {
    method: string;
    regex: RegExp;
    keys: string[];
    handle: Route['handle'];
}

/** 把 `:param` / `*` 路径模式编译成正则 + 参数名列表。 */
function compile(path: string): { regex: RegExp; keys: string[] } {
    const keys: string[] = [];
    const parts = path.split('/').map((seg) => {
        if (seg === '*') {
            keys.push('splat'); // 通配段
            return '(.*?)';
        }
        const named = /^:(.+)$/.exec(seg);
        if (named) {
            keys.push(named[1]);
            return '([^/]+)';
        }
        // 转义正则元字符(保留我们自己的 token 已先行处理)
        return seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    });
    const regex = new RegExp('^' + parts.join('/') + '/?$');
    return { regex, keys };
}

/**
 * 极薄路由表:按注册顺序匹配 method + path,命中后调用 handler。
 * 无框架、无中间件链;handler 直接操作 req/res,保持原生语义。
 */
export function createRouter(routes: Route[]) {
    const compiled: CompiledRoute[] = routes.map((r) => {
        const { regex, keys } = compile(r.path);
        return { method: r.method, regex, keys, handle: r.handle };
    });

    return {
        async dispatch(
            ctx: ServerCtx,
            req: IncomingMessage,
            res: ServerResponse,
            url: URL,
        ): Promise<boolean> {
            for (const c of compiled) {
                if (c.method !== req.method) continue;
                const m = c.regex.exec(url.pathname);
                if (!m) continue;
                const params: Record<string, string> = {};
                c.keys.forEach((k, i) => {
                    params[k] = decodeURIComponent(m[i + 1]);
                });
                const handled = await c.handle({ ctx, req, res, url, params });
                if (handled !== false) return true;
            }
            return false;
        },
    };
}