@tenjot/router
v1.0.0
Published
A tiny trie-based router compatible with URLPattern, forked from Hono's TrieRouter
Readme
@tenjot/router
A tiny, dependency-free trie-based router whose matching results are compatible with URLPattern.
This is a fork of Hono's TrieRouter.
Install
npm install @tenjot/routerUsage
import { createRouter } from "@tenjot/router";
const router = createRouter<string>();
router.add("GET", "/users/:id", "getUser");
router.add("GET", "/files/*", "getFile");
router.match("GET", "/users/42");
// => ["getUser", { id: "42" }]
router.match("GET", "/files/a/b.txt");
// => ["getFile", { 0: "a/b.txt" }]
router.match("POST", "/users/42");
// => nullThe handler type T is up to you — it can be a function, a string, or any value.
API
createRouter<T>(): Router<T>
Creates a new router.
router.add(method: string, path: string, handler: T): void
Registers handler for method and path. Methods are arbitrary strings and are matched exactly.
Throws a TypeError if path contains the same named parameter twice (e.g. /:foo/:foo), just like URLPattern.
router.match(method: string, path: string): [T, Params] | null
Returns the matched handler and its parameters, or null if nothing matches. Params is Record<string, string>.
Patterns
| Pattern | Matches | Params |
| -------------- | ----------------------- | --------------------------- |
| /hello | /hello | {} |
| /hello/:name | /hello/world | { name: "world" } |
| /hello/* | /hello/, /hello/a/b | { 0: "" }, { 0: "a/b" } |
| /a/*/b/* | /a/x/b/c | { 0: "x", 1: "c" } |
:namematches exactly one non-empty segment.*matches any number of characters, including/. Unnamed wildcards get numeric keys in order (0,1, …).- Params are the same as
new URLPattern({ pathname }).exec({ pathname: path }).pathname.groups; the test suite checks this against the realURLPattern.
Priority
When several routes match, the one registered first wins — not the most specific one.
router.add("GET", "/api/abc", "abc");
router.add("GET", "/api/*", "fallback");
router.match("GET", "/api/abc"); // => ["abc", {}]
router.match("GET", "/api/def"); // => ["fallback", { 0: "def" }]Register specific routes before fallbacks.
License
Based on Hono — Copyright (c) 2021 - present, Yusuke Wada and Hono contributors.
