Skip to content
Myr

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) ---------

authored by Taku Amano · committed by GitHub · parent 4f5a305 · Browse files · 6 files+269 added−32 removed
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

6 files+269 added−32 removed

modified:benchmarks/routers/src/bench-includes-init.mts+16 added-1 removed
modified:src/router/reg-exp-router/index.ts+1 added
added:src/router/reg-exp-router/matcher.ts+34 added
added:src/router/reg-exp-router/prepared-router.test.ts+70 added
added:src/router/reg-exp-router/prepared-router.ts+141 added
1import type { ParamIndexMap, Result, Router } from '../../router'2import { METHOD_NAME_ALL } from '../../router'3import type { HandlerData, Matcher, MatcherMap, StaticMap } from './matcher'4import { match, buildAllMatchersKey, emptyParam } from './matcher'5import { RegExpRouter } from './router'67type RelocateMap = Record<string, [(number | string)[], ParamIndexMap | undefined][]>89export class PreparedRegExpRouter<T> implements Router<T> {10 name: string = 'PreparedRegExpRouter'11 #matchers: MatcherMap<T>12 #relocateMap: RelocateMap1314 constructor(matchers: MatcherMap<T>, relocateMap: RelocateMap) {15 this.#matchers = matchers16 this.#relocateMap = relocateMap17 }1819 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 ]2930 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 }4142 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 }6465 [buildAllMatchersKey](): MatcherMap<T> {66 return this.#matchers67 }6869 match: typeof match<Router<T>, T> = match70}7172export 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 }7980 const matchers = router[buildAllMatchersKey]()81 const all = matchers[METHOD_NAME_ALL] as Matcher<string>8283 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 }114115 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 }121122 return [matchers, relocateMap]123}124125export 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
1import type { ParamIndexMap, Result, Router } from '../../router'1import type { ParamIndexMap, Router } from '../../router'2import {3 MESSAGE_MATCHER_IS_ALREADY_BUILT,4 METHOD_NAME_ALL,5 UnsupportedPathError,6} from '../../router'7import { checkOptionalParameter } from '../../utils/url'8import type { HandlerData, StaticMap, Matcher, MatcherMap } from './matcher'9import { match, emptyParam, buildAllMatchersKey } from './matcher'10import { PATH_ERROR } from './node'11import type { ParamAssocArray } from './node'12import { Trie } from './trie'1312type HandlerData<T> = [T, ParamIndexMap][]13type StaticMap<T> = Record<string, Result<T>>14type Matcher<T> = [RegExp, HandlerData<T>[], StaticMap<T>]14type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]1517const emptyParam: string[] = []16// eslint-disable-next-line @typescript-eslint/no-explicit-any17const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]1819let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)
182 unmodified lines
202 })203 }204 }205208 match(method: string, path: string): Result<T> {209 clearWildcardRegExpCache() // no longer used.206 match: typeof match<Router<T>, T> = match;207211 const matchers = this.#buildAllMatchers()208 [buildAllMatchersKey](): MatcherMap<T> {209 const matchers: MatcherMap<T> = Object.create(null)210213 this.match = (method, path) => {214 const matcher = (matchers[method] || matchers[METHOD_NAME_ALL]) as Matcher<T>215216 const staticMatch = matcher[2][path]217 if (staticMatch) {218 return staticMatch219 }220221 const match = path.match(matcher[0])222 if (!match) {223 return [[], emptyParam]224 }225226 const index = match.indexOf('', 1)227 return [matcher[1][index], match]228 }229230 return this.match(method, path)231 }232233 #buildAllMatchers(): Record<string, Matcher<T> | null> {234 const matchers: Record<string, Matcher<T> | null> = Object.create(null)235211 Object.keys(this.#routes!)212 .concat(Object.keys(this.#middleware!))213 .forEach((method) => {214 matchers[method] ||= this.#buildMatcher(method)215 })216217 // Release cache218 this.#middleware = this.#routes = undefined219 clearWildcardRegExpCache()220221 return matchers222 }223
29 unmodified lines