Skip to content
Myr

fix(reg-exp-router): associate wildcard middleware with matching routes (#5266)

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

* fix(reg-exp-router): associate suffix wildcard routes * fix(reg-exp-router): preserve wildcard parameter names * fix(reg-exp-router): associate patterned wildcard routes * perf(reg-exp-router): reduce minified bundle size * fix(reg-exp-router): associate complex wildcard patterns * perf(reg-exp-router): compact route registration

authored by Taku Amano · committed by GitHub · parent 48e360f · Browse files · 4 files+175 added−101 removed
This commit

State

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

Diff stats

4 files+175 added−101 removed

  • tests:+112 added−0 removed
  • other:+63 added−101 removed

4 files+175 added−101 removed

modified:src/router/linear-router/router.test.ts+9 added
modified:src/router/reg-exp-router/node.ts+3 added-3 removed
1const LABEL_REG_EXP_STR = '[^/]+'2const ONLY_WILDCARD_REG_EXP_STR = '.*'3const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'1export const LABEL_REG_EXP_STR = '[^/]+'2export const ONLY_WILDCARD_REG_EXP_STR = '.*'3export const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'4export const PATH_ERROR = Symbol()56export type ParamAssocArray = [string, number][]7export interface Context {
161 unmodified lines
modified:src/router/reg-exp-router/router.ts+60 added-98 removed
1import type { ParamIndexMap, Router } from '../../router'1import type { 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 } from './matcher'10import { PATH_ERROR } from './node'10import {11 LABEL_REG_EXP_STR,12 ONLY_WILDCARD_REG_EXP_STR,13 PATH_ERROR,14 TAIL_WILDCARD_REG_EXP_STR,15} from './node'16import { Trie } from './trie'1713type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]18type HandlerWithMetadata<T> = [T, string] // [handler, path]1920let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)21function buildWildcardRegExp(path: string): RegExp {22 return (wildcardRegExpCache[path] ??= new RegExp(18 path === '*'19 ? ''20 : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) =>21 metaChar ? `\\${metaChar}` : '(?:|/.*)'22 )}$`23 `^${path.replace(24 /\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,25 (match, metaChar) =>26 metaChar27 ? `\\${metaChar}`28 : match === '/*'29 ? TAIL_WILDCARD_REG_EXP_STR30 : match === '*'31 ? ONLY_WILDCARD_REG_EXP_STR32 : `/:${LABEL_REG_EXP_STR}`33 )}$`34 ))35}3626function clearWildcardRegExpCache() {27 wildcardRegExpCache = Object.create(null)28}2930function findMiddleware<T>(31 middleware: Record<string, T[]> | undefined,32 path: string33): T[] | undefined {34 if (!middleware) {35 return undefined36 }3737function findMiddleware<T>(middleware: Record<string, T[]>, path: string): T[] | undefined {38 for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {39 if (buildWildcardRegExp(k).test(path)) {40 return [...middleware[k]]41 }
23 unmodified lines
65 }6667 add(method: string, path: string, handler: T) {68 const middleware = this.#middleware69 const routes = this.#routes69 const routes = this.#routes!7071 if (!middleware || !routes) {71 if (!middleware) {72 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)73 }7475 if (!middleware[method]) {76 this.#tries![method] = new Trie()77 ;[middleware, routes].forEach((handlerMap) => {77 for (const handlerMap of [middleware, routes]) {78 handlerMap[method] = Object.create(null)79 Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {79 for (const p in handlerMap[METHOD_NAME_ALL]) {80 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]81 this.#insertPath(method, p)82 })83 })82 }83 }84 }8586 if (path === '/*') {87 path = '*'88 }89 const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method]9090 const paramCount = (path.match(/\/:/g) || []).length9191 if (/\*$/.test(path)) {92 const re = buildWildcardRegExp(path)94 Object.keys(middleware).forEach((m) => {95 if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {93 for (const m of methods) {94 if (!middleware[m][path]) {95 this.#insertPath(m, path)96 middleware[m][path] =97 findMiddleware(middleware[m], path) ||98 findMiddleware(middleware[METHOD_NAME_ALL], path) ||99 []100 }102 })103 Object.keys(middleware).forEach((m) => {104 if (method === METHOD_NAME_ALL || method === m) {105 Object.keys(middleware[m]).forEach((p) => {106 re.test(p) && middleware[m][p].push([handler, paramCount])107 })101 }102 for (const handlerMap of [middleware, routes]) {103 for (const m of methods) {104 for (const p in handlerMap[m]) {105 re.test(p) && handlerMap[m][p].push([handler, path])106 }107 }109 })108 }109111 Object.keys(routes).forEach((m) => {112 if (method === METHOD_NAME_ALL || method === m) {113 Object.keys(routes[m]).forEach(114 (p) => re.test(p) && routes[m][p].push([handler, paramCount])115 )116 }117 })118110 return111 }112113 const paths = checkOptionalParameter(path) || [path]123 for (let i = 0, len = paths.length; i < len; i++) {124 const path = paths[i]125126 Object.keys(routes).forEach((m) => {127 if (method === METHOD_NAME_ALL || method === m) {128 if (!routes[m][path]) {129 this.#insertPath(m, path)130 routes[m][path] = [131 ...(findMiddleware(middleware[m], path) ||132 findMiddleware(middleware[METHOD_NAME_ALL], path) ||133 []),114 for (const path of paths) {115 for (const m of methods) {116 if (!routes[m][path]) {117 this.#insertPath(m, path)118 routes[m][path] =119 findMiddleware(middleware[m], path) ||120 findMiddleware(middleware[METHOD_NAME_ALL], path) ||121 []134 ]135 }136 routes[m][path].push([handler, paramCount - len + i + 1])122 }138 })123 routes[m][path].push([handler, path])124 }125 }126 }127128 match: typeof match<Router<T>, T> = match129130 protected buildAllMatchers(): MatcherMap<T> {131 const matchers: MatcherMap<T> = Object.create(null)132147 Object.keys(this.#routes!)148 .concat(Object.keys(this.#middleware!))149 .forEach((method) => {150 matchers[method] ||= this.#buildMatcher(method)151 })133 for (const method of Object.keys(this.#routes!)) {134 matchers[method] = this.#buildMatcher(method)135 }136137 // Release cache138 this.#middleware = this.#routes = this.#tries = undefined155 clearWildcardRegExpCache()139 wildcardRegExpCache = Object.create(null)140141 return matchers142 }143
3 unmodified lines
147148 const trie = this.#tries![method]149 const staticMap: StaticMap<T> = Object.create(null)150 const handlerData: HandlerData<T>[] = []151 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()152168 ;[middleware, routes].forEach((r) => {153 for (const r of [middleware, routes]) {154 for (const path in r) {155 const handlers = r[path]156 const pathData = trie.paths[path]157 if (!pathData) {158 staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]159 continue160 }176 const paramAssoc = pathData[1]177 handlerData[pathData[0]] = handlers.map(([h, paramCount]) => {178 const paramIndexMap: ParamIndexMap = Object.create(null)179 paramCount -= 1180 for (; paramCount >= 0; paramCount--) {181 const [key, value] = paramAssoc[paramCount]182 paramIndexMap[key] = value183 }184 return [h, paramIndexMap]185 })161 handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [162 h,163 trie.paths[handlerPath][1].reduceRight((map, [key], i) => {164 map[key] = paramReplacementMap[pathData[1][i][1]]165 return map166 }, Object.create(null)),167 ])168 }187 })188189 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()190 for (let i = 0, len = handlerData.length; i < len; i++) {191 for (let j = 0, len = handlerData[i].length; j < len; j++) {192 const map = handlerData[i][j]?.[1]193 if (!map) {194 continue195 }196 const keys = Object.keys(map)197 for (let k = 0, len = keys.length; k < len; k++) {198 map[keys[k]] = paramReplacementMap[map[keys[k]]]199 }200 }169 }170203 const handlerMap: HandlerData<T>[] = []204 // using `in` because indexReplacementMap is a sparse array205 for (const i in indexReplacementMap) {206 handlerMap[i] = handlerData[indexReplacementMap[i]]207 }208209 return [regexp, handlerMap, staticMap] as Matcher<T>171 return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap] as Matcher<T>172 }173}
modified:src/router/common.case.test.ts+103 added
395 unmodified lines
396 it('GET /asset', async () => {397 const res = match('GET', '/asset')398 expect(res.length).toBe(0)399 })400401 it.each([402 ['/assets*', '/assets/app.js'],403 ['/assets/app.js', '/assets*'],404 ])('associates %s before %s', async (first, second) => {405 router.add('POST', first, first)406 router.add('POST', second, second)407 const res = match('POST', '/assets/app.js')408 expect(res.map(({ handler }) => handler)).toEqual([first, second])409 })410 })411412 describe('Trailing wildcard', () => {413 beforeEach(() => {
17 unmodified lines
431 expect(res.length).toBe(0)432 })433 })434435 describe('Trailing wildcard after a label', () => {436 beforeEach(() => {437 router.add('GET', '/:name/*', 'middleware')438 router.add('GET', '/:id', 'handler')439 })440441 it('GET /abc', async () => {442 const res = match('GET', '/abc')443 expect(res.length).toBe(2)444 expect(res[0]).toEqual({ handler: 'middleware', params: { name: 'abc' } })445 expect(res[1]).toEqual({ handler: 'handler', params: { id: 'abc' } })446 })447448 it('GET /abc/sub', async () => {449 const res = match('GET', '/abc/sub')450 expect(res).toEqual([{ handler: 'middleware', params: { name: 'abc' } }])451 })452 })453454 describe('Trailing wildcard after a pattern label', () => {455 beforeEach(() => {456 router.add('GET', '/:name{[a-z]+}/*', 'middleware')457 router.add('GET', '/:id{[a-z]+}', 'handler')458 })459460 it('GET /abc', async () => {461 const res = match('GET', '/abc')462 expect(res.length).toBe(2)463 expect(res[0]).toEqual({ handler: 'middleware', params: { name: 'abc' } })464 expect(res[1]).toEqual({ handler: 'handler', params: { id: 'abc' } })465 })466467 it('GET /reverse/abc in reverse registration order', async () => {468 router = newRouter()469 router.add('GET', '/reverse/:id{[a-z]+}', 'handler')470 router.add('GET', '/reverse/:name{[a-z]+}/*', 'middleware')471 const res = match('GET', '/reverse/abc')472 expect(res.map(({ handler }) => handler)).toEqual(['handler', 'middleware'])473 })474475 it('POST /all/abc with ALL middleware', async () => {476 router = newRouter()477 router.add('ALL', '/all/:name{[a-z]+}/*', 'middleware')478 router.add('POST', '/all/:id{[a-z]+}', 'handler')479 const res = match('POST', '/all/abc')480 expect(res.map(({ handler }) => handler)).toEqual(['middleware', 'handler'])481 })482483 it('GET /posts/2024/comments with nested braces', async () => {484 router = newRouter()485 router.add('GET', '/posts/:year{[0-9]{4}}/*', 'middleware')486 router.add('GET', '/posts/:yr{[0-9]{4}}/comments', 'handler')487 const res = match('GET', '/posts/2024/comments')488 expect(res).toEqual([489 { handler: 'middleware', params: { year: '2024' } },490 { handler: 'handler', params: { yr: '2024' } },491 ])492 })493494 it('GET /files/foo/detail with regexp meta characters', async () => {495 router = newRouter()496 router.add('GET', '/files/:kind{(?:foo|bar)}/*', 'middleware')497 router.add('GET', '/files/:type{(?:foo|bar)}/detail', 'handler')498 const res = match('GET', '/files/foo/detail')499 expect(res).toEqual([500 { handler: 'middleware', params: { kind: 'foo' } },501 { handler: 'handler', params: { type: 'foo' } },502 ])503 })504505 it('GET /user/123/profile with the default pattern', async () => {506 router = newRouter()507 router.add('GET', '/user/:userId{[^/]+}/*', 'middleware')508 router.add('GET', '/user/:id/profile', 'handler')509 const res = match('GET', '/user/123/profile')510 expect(res).toEqual([511 { handler: 'middleware', params: { userId: '123' } },512 { handler: 'handler', params: { id: '123' } },513 ])514 })515516 it('GET /user/123/profile with the default pattern in reverse registration order', async () => {517 router = newRouter()518 router.add('GET', '/user/:id/profile', 'handler')519 router.add('GET', '/user/:userId{[^/]+}/*', 'middleware')520 const res = match('GET', '/user/123/profile')521 expect(res).toEqual([522 { handler: 'handler', params: { id: '123' } },523 { handler: 'middleware', params: { userId: '123' } },524 ])525 })526 })527528 describe('Trailing wildcard after a middle wildcard', () => {529 beforeEach(() => {530 router.add('GET', '/a/*/b/*', 'b')531 })
570 unmodified lines