feat(reg-exp-router): Introduced PreparedRegExpRouter (#1796)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(reg-exp-router): Introduced PreparedRegExpRouter * fix: explicitly specify a type of `match` method. * test: refactor PreparedRegExpRouter test * refactor: simplify PreparedRegExpRouter API. * fix(reg-exp-router): run `bun run format:fix` * fix: applying updates from the main branch * fix: merge relocateMap if path is already in the map * fix: should not skip wildcard path * test(reg-exp-router): fix test for PreparedRegExpRouter * refactor(reg-exp-router): fix import statement order * refactor(reg-exp-router): in the first call, call the method directly instead of this.match * refactor(reg-exp-router): use for...in instead of Object.keys * docs(reg-exp-router): add comments * refactor(reg-exp-router): use a more explicit type instead of `as any`. * refactor(reg-exp-router): improve static route handling * refactor(reg-exp-router): throws an Error when an unregistered path is passed. * test(reg-exp-router): add test for PreparedRegExpRouter * refactor(reg-exp-router): remove unnecessary guards as only METHOD_NAME_ALL is guaranteed to be used during parameter generation. * ci: apply automated fixes * fix(reg-exp-router): fix typo in test comment * test(reg-exp-router): remove unnecessary type annotation in test * chore(benchmarks): update buildInitParams to use paths (spec change) ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Diff stats
6 files+269 added−32 removed
- tests:+70 added−0 removed
- other:+199 added−32 removed
Provenance
- Commit
53f87dd- Tree
42b4158- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
4f5a305
6 files changed+269 added−32 removed
modified:benchmarks/routers/src/bench-includes-init.mts+16 added-1 removed
3 unmodified lines456789101181213141516171819202122232439 unmodified lines64656667686970717273747576777845 unmodified lines3 unmodified linesimport KoaRouter from 'koa-tree-router'import { run, bench, group } from 'mitata'import TrekRouter from 'trek-router'import { LinearRouter } from '../../../src/router/linear-router/index.ts'import { RegExpRouter, PreparedRegExpRouter, buildInitParams,import { RegExpRouter } from '../../../src/router/reg-exp-router/index.ts'} from '../../../src/router/reg-exp-router/index.ts'import { TrieRouter } from '../../../src/router/trie-router/index.ts'import type { Route } from './tool.mts'import { routes } from './tool.mts'
const preparedParams = buildInitParams({ paths: routes.map((r) => r.path),})
const benchRoutes: (Route & { name: string })[] = [ { name: 'short static', method: 'GET',39 unmodified lines router.add(route.method, route.path, () => {}) } router.match(benchRoute.method, benchRoute.path) }) bench('PreparedRegExpRouter', () => { const router = new PreparedRegExpRouter(preparedParams[0], preparedParams[1]) for (const route of routes) { router.add(route.method, route.path, () => {}) } router.match(benchRoute.method, benchRoute.path) }) bench('TrieRouter', () => { const router = new TrieRouter() for (const route of routes) { router.add(route.method, route.path, () => {})45 unmodified linesmodified:src/router/reg-exp-router/index.ts+1 added
2 unmodified lines345672 unmodified lines * RegExpRouter for Hono. */
export { RegExpRouter } from './router'export { PreparedRegExpRouter, buildInitParams, serializeInitParams } from './prepared-router'added:src/router/reg-exp-router/matcher.ts+34 added
12345678910111213141516171819202122232425262728293031323334import type { ParamIndexMap, Result, Router } from '../../router'import { METHOD_NAME_ALL } from '../../router'
export type HandlerData<T> = [T, ParamIndexMap][]export type StaticMap<T> = Record<string, Result<T>>export type Matcher<T> = [RegExp, HandlerData<T>[], StaticMap<T>]export type MatcherMap<T> = Record<string, Matcher<T> | null>
export const emptyParam: string[] = []export const buildAllMatchersKey = Symbol('buildAllMatchers')export function match<R extends Router<T>, T>(this: R, method: string, path: string): Result<T> { // eslint-disable-next-line @typescript-eslint/no-explicit-any const matchers: MatcherMap<T> = (this as any)[buildAllMatchersKey]()
const match = ((method, path) => { const matcher = (matchers[method] || matchers[METHOD_NAME_ALL]) as Matcher<T>
const staticMatch = matcher[2][path] if (staticMatch) { return staticMatch }
const match = path.match(matcher[0]) if (!match) { return [[], emptyParam] }
const index = match.indexOf('', 1) return [matcher[1][index], match] }) as Router<T>['match']
this.match = match return match(method, path)}added:src/router/reg-exp-router/prepared-router.test.ts+70 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import { runTest } from '../common.case.test'import { buildInitParams, serializeInitParams, PreparedRegExpRouter } from './prepared-router'
describe('PreparedRegExpRouter', async () => { runTest({ skip: [ { reason: 'UnsupportedPath', tests: [ 'Duplicate param name > parent', 'Duplicate param name > child', 'Capture Group > Complex capturing group > GET request', 'Capture complex multiple directories > GET /part1/middle-b/latest', 'Capture complex multiple directories > GET /part1/middle-b/end-c/latest', 'Complex > Parameter with {.*} regexp', ], }, { reason: 'This route can not be added with `:label` to PreparedRegExpRouter. This is ambiguous', tests: ['Including slashes > GET /js/main.js'], }, ], newRouter: <T>() => { let router: PreparedRegExpRouter<T> const routes: [string, string, T][] = [] return { name: 'PreparedRegExpRouterBuilder', add: (method: string, path: string, handler: T) => { routes.push([method, path, handler]) }, match: (method: string, path: string) => { if (!router) { const serialized = serializeInitParams( buildInitParams({ paths: routes.map((r) => r[1]), }) ) const params = eval(serialized) as ConstructorParameters<typeof PreparedRegExpRouter<T>> router = new PreparedRegExpRouter<T>(...params)
for (const route of routes) { router.add(...route) } } return router.match(method, path) }, } }, })
describe('add()', () => { it('should add a route', () => { const params = buildInitParams({ paths: ['/hello'], }) const router = new PreparedRegExpRouter(...params) router.add('GET', '/hello', 'get hello') expect(router.match('GET', '/hello')).toEqual([[['get hello', {}]], []]) })
it('should throw an error if the path is not pre-registered', () => { const params = buildInitParams({ paths: ['/hello'], }) const router = new PreparedRegExpRouter(...params) expect(() => router.add('GET', '/unknown', 'get hello')).toThrowError() }) })})added:src/router/reg-exp-router/prepared-router.ts+141 added
1+import type { ParamIndexMap, Result, Router } from '../../router'2+import { METHOD_NAME_ALL } from '../../router'3+import type { HandlerData, Matcher, MatcherMap, StaticMap } from './matcher'4+import { match, buildAllMatchersKey, emptyParam } from './matcher'5+import { RegExpRouter } from './router'6+7+type RelocateMap = Record<string, [(number | string)[], ParamIndexMap | undefined][]>8+9+export class PreparedRegExpRouter<T> implements Router<T> {10+ name: string = 'PreparedRegExpRouter'11+ #matchers: MatcherMap<T>12+ #relocateMap: RelocateMap13+14+ constructor(matchers: MatcherMap<T>, relocateMap: RelocateMap) {15+ this.#matchers = matchers16+ this.#relocateMap = relocateMap17+ }18+19+ add(method: string, path: string, handler: T) {20+ const all = this.#matchers[METHOD_NAME_ALL] as Matcher<T>21+ this.#matchers[method] ||= [22+ all[0],23+ all[1].map((list) => (Array.isArray(list) ? list.slice() : 0)) as HandlerData<T>[],24+ Object.keys(all[2]).reduce((obj, key) => {25+ obj[key] = [all[2][key][0].slice(), emptyParam] as Result<T>26+ return obj27+ }, {} as StaticMap<T>),28+ ]29+30+ if (path === '/*' || path === '*') {31+ const defaultHandlerData: [T, ParamIndexMap] = [handler, {}]32+ ;(method === METHOD_NAME_ALL ? Object.keys(this.#matchers) : [method]).forEach((m) => {33+ const matcher = this.#matchers[m] as Matcher<T>34+ matcher[1].forEach((list) => list && list.push(defaultHandlerData))35+ Object.values(matcher[2]).forEach((list) =>36+ (list[0] as [T, ParamIndexMap][]).push(defaultHandlerData)37+ )38+ })39+ return40+ }41+42+ const data = this.#relocateMap[path]43+ if (!data) {44+ throw new Error(`Path ${path} is not registered`)45+ }46+ for (const [indexes, map] of data) {47+ ;(method === METHOD_NAME_ALL ? Object.keys(this.#matchers) : [method]).forEach((m) => {48+ const matcher = this.#matchers[m] as Matcher<T>49+ if (!map) {50+ // assumed to be a static route51+ matcher[2][path][0].push([handler, {}])52+ } else {53+ indexes.forEach((index) => {54+ if (typeof index === 'number') {55+ matcher[1][index].push([handler, map])56+ } else {57+ ;(matcher[2][index || path][0] as [T, ParamIndexMap][]).push([handler, map])58+ }59+ })60+ }61+ })62+ }63+ }64+65+ [buildAllMatchersKey](): MatcherMap<T> {66+ return this.#matchers67+ }68+69+ match: typeof match<Router<T>, T> = match70+}71+72+export const buildInitParams: (params: {73+ paths: string[]74+}) => ConstructorParameters<typeof PreparedRegExpRouter> = ({ paths }) => {75+ const router = new RegExpRouter<string>()76+ for (const path of paths) {77+ router.add(METHOD_NAME_ALL, path, path)78+ }79+80+ const matchers = router[buildAllMatchersKey]()81+ const all = matchers[METHOD_NAME_ALL] as Matcher<string>82+83+ const relocateMap: RelocateMap = {}84+ for (const path of paths) {85+ all[1].forEach((list, i) => {86+ list.forEach(([p, map]) => {87+ if (p === path) {88+ if (relocateMap[path]) {89+ relocateMap[path][0][1] = {90+ ...relocateMap[path][0][1],91+ ...map,92+ }93+ } else {94+ relocateMap[path] = [[[], map]]95+ }96+ if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) {97+ relocateMap[path][0][0].push(i)98+ }99+ }100+ })101+ })102+ for (const path2 in all[2]) {103+ all[2][path2][0].forEach(([p]) => {104+ if (p === path) {105+ relocateMap[path] ||= [[[], undefined]]106+ const value = path2 === path ? '' : path2107+ if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) {108+ relocateMap[path][0][0].push(value)109+ }110+ }111+ })112+ }113+ }114+115+ for (let i = 0, len = all[1].length; i < len; i++) {116+ all[1][i] = all[1][i] ? [] : (0 as unknown as HandlerData<string>)117+ }118+ for (const path in all[2]) {119+ all[2][path][0] = []120+ }121+122+ return [matchers, relocateMap]123+}124+125+export const serializeInitParams: (126+ params: ConstructorParameters<typeof PreparedRegExpRouter>127+) => string = ([matchers, relocateMap]) => {128+ for (const method in matchers) {129+ const matcher = matchers[method] as Matcher<string>130+ // escape the regular expression to serialize it with `JSON.stringify`131+ ;(matcher[0] as RegExp & { toJSON: () => string }).toJSON = function () {132+ return `@${this.toString()}@`133+ }134+ }135+ // unescape the regular expression so that it can be deserialized with `eval`.136+ const matchersStr = JSON.stringify(matchers).replace(/"@(.+?)@"/g, (_, str) =>137+ str.replace(/\\\\/g, '\\')138+ )139+ const relocateMapStr = JSON.stringify(relocateMap)140+ return `[${matchersStr},${relocateMapStr}]`141+}modified:src/router/reg-exp-router/router.ts+7 added-31 removed
1-import type { ParamIndexMap, Result, Router } from '../../router'1+import type { ParamIndexMap, Router } from '../../router'2 import {3 MESSAGE_MATCHER_IS_ALREADY_BUILT,4 METHOD_NAME_ALL,5 UnsupportedPathError,6 } from '../../router'7 import { checkOptionalParameter } from '../../utils/url'8+import type { HandlerData, StaticMap, Matcher, MatcherMap } from './matcher'9+import { match, emptyParam, buildAllMatchersKey } from './matcher'10 import { PATH_ERROR } from './node'11 import type { ParamAssocArray } from './node'12 import { Trie } from './trie'13 12-type HandlerData<T> = [T, ParamIndexMap][]13-type StaticMap<T> = Record<string, Result<T>>14-type Matcher<T> = [RegExp, HandlerData<T>[], StaticMap<T>]14 type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]15 17-const emptyParam: string[] = []16 // eslint-disable-next-line @typescript-eslint/no-explicit-any17 const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]18 19 let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)182 unmodified lines202 })203 }204 }205 208- match(method: string, path: string): Result<T> {209- clearWildcardRegExpCache() // no longer used.206+ match: typeof match<Router<T>, T> = match;207 211- const matchers = this.#buildAllMatchers()208+ [buildAllMatchersKey](): MatcherMap<T> {209+ const matchers: MatcherMap<T> = Object.create(null)210 213- this.match = (method, path) => {214- const matcher = (matchers[method] || matchers[METHOD_NAME_ALL]) as Matcher<T>215-216- const staticMatch = matcher[2][path]217- if (staticMatch) {218- return staticMatch219- }220-221- const match = path.match(matcher[0])222- if (!match) {223- return [[], emptyParam]224- }225-226- const index = match.indexOf('', 1)227- return [matcher[1][index], match]228- }229-230- return this.match(method, path)231- }232-233- #buildAllMatchers(): Record<string, Matcher<T> | null> {234- const matchers: Record<string, Matcher<T> | null> = Object.create(null)235-211 Object.keys(this.#routes!)212 .concat(Object.keys(this.#middleware!))213 .forEach((method) => {214 matchers[method] ||= this.#buildMatcher(method)215 })216 217 // Release cache218 this.#middleware = this.#routes = undefined219+ clearWildcardRegExpCache()220 221 return matchers222 }223 29 unmodified lines