Skip to content
Myr

feat: RegExpRouter (#109)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Make the Router abstract class. * Introduce RegExpRouter. * Add RegExpRouter to benchmark target. * Optimize for special short routes. ``` * "*" * "/path/to/*" * "/path/to/*/content" ``` * Add assertion to `add` method.

authored by Taku Amano · committed by GitHub · parent ea329b8 · Browse files · 10 files+407 added−44 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+407 added−44 removed

  • tests:+73 added−3 removed
  • other:+334 added−41 removed

10 files+407 added−44 removed

modified:benchmarks/handle-event/index.js+29 added-18 removed
added:src/router/reg-exp-router/index.ts+1 added
added:src/router/reg-exp-router/node.ts+110 added
1const LABEL_REG_EXP_STR = '[^/]+'2const ONLY_WILDCARD_REG_EXP_STR = '.*'3const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'45export interface ParamMap {6 [key: string]: number7}8export interface Context {9 varIndex: number10}1112/**13 * Sort order:14 * 1. literal15 * 2. special pattern (e.g. :label{[0-9]+})16 * 3. common label pattern (e.g. :label)17 * 4. wildcard18 */19function compareKey(a: string, b: string): number {20 if (a.length === 1) {21 return b.length === 1 ? (a < b ? -1 : 1) : -122 }23 if (b.length === 1) {24 return 125 }2627 // wildcard28 if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {29 return 130 } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {31 return -132 }3334 // label35 if (a === LABEL_REG_EXP_STR) {36 return 137 } else if (b === LABEL_REG_EXP_STR) {38 return -139 }4041 return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length42}4344export class Node {45 index?: number46 varIndex?: number47 children: {48 [key: string]: Node49 } = {}5051 insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void {52 if (tokens.length === 0) {53 this.index = index54 return55 }5657 const [token, ...restTokens] = tokens58 const pattern =59 token === '*'60 ? restTokens.length === 061 ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths62 : ['', '', LABEL_REG_EXP_STR]63 : token === '/*'64 ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$65 : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)6667 let node68 if (pattern) {69 const name = pattern[1]70 const regexpStr = pattern[2] || LABEL_REG_EXP_STR7172 node = this.children[regexpStr]73 if (!node) {74 node = this.children[regexpStr] = new Node()75 if (name !== '') {76 node.varIndex = context.varIndex++77 }78 }79 if (name !== '') {80 paramMap[name] = node.varIndex81 }82 } else {83 node = this.children[token] ||= new Node()84 }8586 node.insert(restTokens, index, paramMap, context)87 }8889 buildRegExpStr(): string {90 const strList = Object.keys(this.children)91 .sort(compareKey)92 .map((k) => {93 const c = this.children[k]94 return (typeof c.varIndex === 'number' ? `(${k})@${c.varIndex}` : k) + c.buildRegExpStr()95 })9697 if (typeof this.index === 'number') {98 strList.push(`#${this.index}`)99 }100101 if (strList.length === 0) {102 return ''103 }104 if (strList.length === 1) {105 return strList[0]106 }107108 return '(?:' + strList.join('|') + ')'109 }110}
added:src/router/reg-exp-router/router.test.ts+70 added
added:src/router/reg-exp-router/router.ts+119 added
1import { Router, Result, METHOD_NAME_OF_ALL } from '../../router'2import type { ParamMap, ReplacementMap } from './trie'3import { Trie } from './trie'45type Route<T> = [string, T]6type HandlerData<T> = [T, ParamMap]7type Matcher<T> = [RegExp | true, ReplacementMap, HandlerData<T>[]]89export class RegExpRouter<T> extends Router<T> {10 routes?: {11 [method: string]: Route<T>[]12 } = {}1314 matchers?: {15 [method: string]: Matcher<T> | null16 } = null1718 add(method: string, path: string, handler: T) {19 if (!this.routes) {20 throw new Error('Can not add a route since the matcher is already built.')21 }2223 this.routes[method] ||= []24 this.routes[method].push([path, handler])25 }2627 match(method: string, path: string): Result<T> | null {28 if (!this.matchers) {29 this.buildAllMatchers()30 }3132 const matcher = this.matchers[method] || this.matchers[METHOD_NAME_OF_ALL]33 if (!matcher) {34 return null35 }3637 const [regexp, replacementMap, handlers] = matcher38 if (regexp === true) {39 // '*'40 return new Result(handlers[0][0], {})41 }4243 const match = path.match(regexp)44 if (!match) {45 return null46 }47 if (!replacementMap) {48 // there is only one route and no capture49 return new Result(handlers[0][0], {})50 }5152 const index = match.indexOf('', 1)53 const [handler, paramMap] = handlers[replacementMap[index]]54 const params: { [key: string]: string } = {}55 const keys = Object.keys(paramMap)56 for (let i = 0; i < keys.length; i++) {57 params[keys[i]] = match[paramMap[keys[i]]]58 }59 return new Result(handler, params)60 }6162 private buildAllMatchers() {63 this.matchers ||= {}6465 Object.keys(this.routes).forEach((method) => {66 this.buildMatcher(method)67 })6869 delete this.routes // to reduce memory usage70 }7172 private buildMatcher(method: string) {73 this.matchers ||= {}7475 const trie = new Trie()76 const handlers: HandlerData<T>[] = []7778 const targetMethods = [method]79 if (method !== METHOD_NAME_OF_ALL) {80 targetMethods.unshift(METHOD_NAME_OF_ALL)81 }82 const routes = targetMethods.flatMap((method) => this.routes[method] || [])8384 if (routes.length === 0) {85 this.matchers[method] = null86 return87 }8889 if (routes.length === 1 && routes[0][0] === '*') {90 this.matchers[method] = [true, null, [[routes[0][1], {}]]]91 return92 }9394 if (routes.length === 1 && !routes[0][0].match(/:/)) {95 // there is only one route and no capture96 const tmp = routes[0][0].endsWith('*')97 ? routes[0][0].replace(/\/\*$/, '(?:$|/)') // /path/to/* => /path/to(?:$|/)98 : `${routes[0][0]}$` // /path/to/action => /path/to/action$99 const regExpStr = `^${tmp.replace(/\*/g, '[^/]+')}` // /prefix/*/path/to => /prefix/[^/]+/path/to100 this.matchers[method] = [new RegExp(regExpStr), null, [[routes[0][1], {}]]]101 return102 }103104 for (let i = 0; i < routes.length; i++) {105 const paramMap = trie.insert(routes[i][0], i)106 handlers[i] = [routes[i][1], paramMap]107 }108109 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()110 for (let i = 0; i < handlers.length; i++) {111 const paramMap = handlers[i][1]112 Object.keys(paramMap).forEach((k) => {113 paramMap[k] = paramReplacementMap[paramMap[k]]114 })115 }116117 this.matchers[method] = [new RegExp(regexp), indexReplacementMap, handlers]118 }119}
added:src/router/reg-exp-router/trie.ts+47 added
1import type { ParamMap, Context } from './node'2import { Node } from './node'34export type { ParamMap } from './node'5export type ReplacementMap = number[]67export class Trie {8 context: Context = { varIndex: 0 }9 root: Node = new Node()1011 insert(path: string, index: number): ParamMap {12 const paramMap = {}1314 /**15 * - pattern (:label, :label{0-9]+}, ...)16 * - /* wildcard17 * - character18 */19 const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g)20 this.root.insert(tokens, index, paramMap, this.context)2122 return paramMap23 }2425 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {26 let regexp = this.root.buildRegExpStr()2728 let captureIndex = 029 const indexReplacementMap: ReplacementMap = []30 const paramReplacementMap: ReplacementMap = []3132 regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {33 if (typeof handlerIndex !== 'undefined') {34 indexReplacementMap[++captureIndex] = Number(handlerIndex)35 return '$()'36 }37 if (typeof paramIndex !== 'undefined') {38 paramReplacementMap[Number(paramIndex)] = ++captureIndex39 return ''40 }4142 return ''43 })4445 return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]46 }47}
modified:src/hono.ts+12 added-12 removed
1import type { Result } from './node'2import { Node, METHOD_NAME_OF_ALL } from './node'1import { Node } from './node'2import { compose } from './compose'3import { getPathFromURL, mergePath } from './utils/url'4import { Context } from './context'5import type { Env } from './context'6import type { Result } from './router'7import { Router, METHOD_NAME_OF_ALL } from './router'89declare global {10 interface Request<ParamKeyType = string> {11 param: (key: ParamKeyType) => string
22 unmodified lines
34type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`35 ? ParamKey<Component> | ParamKeys<Rest>36 : ParamKey<Path>3737export class Router<T> {38export class TrieRouter<T> extends Router<T> {39 node: Node<T>4041 constructor() {42 super()43 this.node = new Node()44 }4546 add(method: string, path: string, handler: T) {
4 unmodified lines
51 return this.node.search(method, path)52 }53}5453type Init = {54 strict?: boolean55}5655export class Hono {56 routerClass: { new (): Router<any> } = TrieRouter57 strict: boolean = true // strict routing - default is true58 router: Router<Handler>59 middlewareRouters: Router<MiddlewareHandler>[]60 tempPath: string61 strict: boolean6163 constructor(init: Init = { strict: true }) {64 this.router = new Router()62 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {63 Object.assign(this, init)6465 this.router = new this.routerClass()66 this.middlewareRouters = []67 this.tempPath = null67 this.strict = init.strict // strict routing - default is true68 }6970 /* HTTP METHODS */71 get<Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>): Hono
47 unmodified lines
119 use(path: string, middleware: MiddlewareHandler): void {120 if (middleware.constructor.name !== 'AsyncFunction') {121 throw new TypeError('middleware must be a async function!')122 }123 const router = new Router<MiddlewareHandler>()123 const router = new this.routerClass()124 router.add(METHOD_NAME_OF_ALL, path, middleware)125 this.middlewareRouters.push(router)126 }127
102 unmodified lines
modified:src/node.ts+1 added-11 removed
1import type { Pattern } from './utils/url'2import { splitPath, getPattern } from './utils/url'3import { Result, METHOD_NAME_OF_ALL } from './router'44export const METHOD_NAME_OF_ALL = 'ALL'56export class Result<T> {7 handler: T8 params: Record<string, string>9 constructor(handler: T, params: Record<string, string>) {10 this.handler = handler11 this.params = params12 }13}145const noRoute = (): null => {6 return null7}8
112 unmodified lines
added:src/router.ts+15 added
modified:test/router.test.ts+3 added-3 removed
1import { Router } from '../src/hono'1import { TrieRouter } from '../src/hono'23describe('Basic Usage', () => {4 const router = new Router<string>()4 const router = new TrieRouter<string>()56 router.add('GET', '/hello', 'get hello')7 router.add('POST', '/hello', 'post hello')8
14 unmodified lines
23 })24})2526describe('Complex', () => {27 const router = new Router<string>()27 const router = new TrieRouter<string>()2829 it('Named Param', async () => {30 router.add('GET', '/entry/:id', 'get entry')31 const res = router.match('GET', '/entry/123')
36 unmodified lines