UNPKG

kequapp

Version:

A minimal, zero-magic Node web framework built on native APIs

28 lines (27 loc) 959 B
import { getParts } from "./util/extract.js"; export const PARA = '[^/]+'; export const WILD = '.*'; export default function createRegexp(url, isWild = false) { return new RegExp(`^/${convertUrl(url, isWild)}$`, 'i'); } function convertUrl(url, isWild) { const parts = getParts(url); const wildIndex = getWildIndex(parts, isWild); const hasWild = wildIndex > -1; const trimmed = hasWild ? parts.slice(0, wildIndex) : parts; const converted = trimmed.map(replaceParam).join('/'); return hasWild ? `${converted}(?<wild>${WILD})` : converted; } function getWildIndex(parts, isWild) { const wildIndex = parts.indexOf('**'); return wildIndex > -1 || !isWild ? wildIndex : parts.length; } function replaceParam(part) { if (part.startsWith(':')) { return `(?<${part.substring(1)}>${PARA})`; } return escapeRegExp(part); } function escapeRegExp(part) { return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }