$ show pillarjs/path-to-regexp
path-to-regexp is a TypeScript library that converts path patterns like '/user/:id' into regular expressions for URL matching. It provides a suite of functions: parse, compile, match, stringify, and pathToRegexp. The library handles named parameters, wildcards, optional groups (using braces), custom delimiters, and complex backtracking scenarios. It is the foundation for Express-style routing but is framework-agnostic. The code is well-structured, thoroughly tested (including ReDoS safety checks), and follows modern TypeScript practices. It is a mature, high-quality library with active maintenance.
The LLM identified 2 files worth highlighting for reuse:
The `parse` function is a character-by-character state machine that tokenizes path strings into `TokenData` objects. It handles escape sequences, quoted parameter names, Unicode identifiers, optional groups, and reserved characters. It is self-contained and could be reused for any DSL that needs similar tokenization logic. The `PathError` class provides structured error messages that include the original path and a help URL, demonstrating a reusable pattern for user-facing error handling.
The `toRegExpSource` function is the core regex builder. It converts a flat sequence of tokens into a RegExp pattern, handling complex backtracking negations for parameters and wildcards. It uses a `negate` helper to prevent catastrophic backtracking by generating character classes that exclude known delimiter patterns. This logic is non-trivial and could be extracted for other regex generation tasks that require safe alternation.