Skip to content
Myr

feat(reg-exp-router): throw UnsupportedPathError during route registration (#5171)

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

* fix(reg-exp-router): make wildcard sibling order in the regexp deterministic compareKey() was inconsistent when comparing the only wildcard with the tail wildcard, so their order relied on the insertion order normalized by the path-length sort in the matcher build. * fix(reg-exp-router): capture params on a label node created by an unnamed wildcard A param like /w/:id/y registered together with /w/*/x reused the label node created by the unnamed wildcard, which has no var index assigned, so the param value was lost. * feat(reg-exp-router): throw UnsupportedPathError when adding routes Insert paths into per-method tries incrementally in add() so that unsupported path combinations are detected at registration time instead of at the first match. - Static paths are inserted as real nodes (character by character, with no pattern interpretation), but branches without a dynamic terminal are excluded from the regexp, so the generated matchers stay identical to the previous implementation. - Conflict checks no longer depend on the insertion order: wildcard nodes coexist with anything, and a single-character pattern like /:x{a} coexists with single-character literals. - Node#insert is now a loop instead of recursion with array spreads, making registration plus the first match roughly 20% faster. * test(reg-exp-router): cover method-specific path validation

authored by Taku Amano · committed by GitHub · parent 3feb355 · Browse files · 4 files+331 added−233 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+331 added−233 removed

  • tests:+159 added−35 removed
  • other:+172 added−198 removed

4 files+331 added−233 removed

modified:src/router/reg-exp-router/node.ts+86 added-80 removed
modified:src/router/reg-exp-router/router.test.ts+159 added-35 removed
1import type { ParamStash } from '../../router'1import type { ParamIndexMap, ParamStash } from '../../router'2import { UnsupportedPathError } from '../../router'3import { runTest } from '../common.case.test'4import { RegExpRouter } from './router'5
32 unmodified lines
38 })3940 describe('UnsupportedPathError', () => {41 describe('Ambiguous', () => {42 const router = new RegExpRouter<string>()4344 router.add('GET', '/:user/entries', 'get user entries')45 router.add('GET', '/entry/:name', 'get entry')46 router.add('POST', '/entry', 'create entry')4748 it('GET /entry/entries', () => {42 it('GET /entry/:name', () => {43 const router = new RegExpRouter<string>()44 router.add('GET', '/:user/entries', 'get user entries')45 expect(() => {50 router.match('GET', '/entry/entries')46 router.add('GET', '/entry/:name', 'get entry')47 }).toThrowError(UnsupportedPathError)48 })49 })5051 describe('Multiple handlers with different label', () => {56 const router = new RegExpRouter<string>()5758 router.add('GET', '/:type/:id', ':type')59 router.add('GET', '/:class/:id', ':class')60 router.add('GET', '/:model/:id', ':model')6162 it('GET /entry/123', () => {52 it('GET /:class/:id', () => {53 const router = new RegExpRouter<string>()54 router.add('GET', '/:type/:id', ':type')55 expect(() => {64 router.match('GET', '/entry/123')56 router.add('GET', '/:class/:id', ':class')57 }).toThrowError(UnsupportedPathError)58 })59 })6061 it('parent', () => {62 const router = new RegExpRouter<string>()63 router.add('GET', '/:id/:action', 'foo')72 router.add('GET', '/posts/:id', 'bar')64 expect(() => {74 router.match('GET', '/')65 router.add('GET', '/posts/:id', 'bar')66 }).toThrowError(UnsupportedPathError)67 })6869 it('child', () => {70 const router = new RegExpRouter<string>()71 router.add('GET', '/posts/:id', 'foo')81 router.add('GET', '/:id/:action', 'bar')8272 expect(() => {84 router.match('GET', '/')73 router.add('GET', '/:id/:action', 'bar')74 }).toThrowError(UnsupportedPathError)75 })7677 describe('static and dynamic', () => {78 it('static first', () => {79 const router = new RegExpRouter<string>()80 router.add('GET', '/reg-exp/router', 'foo')92 router.add('GET', '/reg-exp/:id', 'bar')9381 expect(() => {95 router.match('GET', '/')82 router.add('GET', '/reg-exp/:id', 'bar')83 }).toThrowError(UnsupportedPathError)84 })8586 it('long label', () => {87 const router = new RegExpRouter<string>()88 router.add('GET', '/reg-exp/router', 'foo')102 router.add('GET', '/reg-exp/:service', 'bar')10389 expect(() => {105 router.match('GET', '/')90 router.add('GET', '/reg-exp/:service', 'bar')91 }).toThrowError(UnsupportedPathError)92 })9394 it('dynamic first', () => {95 const router = new RegExpRouter<string>()96 router.add('GET', '/reg-exp/:id', 'bar')112 router.add('GET', '/reg-exp/router', 'foo')11397 expect(() => {115 router.match('GET', '/')98 router.add('GET', '/reg-exp/router', 'foo')99 }).toThrowError(UnsupportedPathError)100 })101 })102103 it('different regular expression', () => {104 const router = new RegExpRouter<string>()105 router.add('GET', '/:id/:action{create|update}', 'foo')123 router.add('GET', '/:id/:action{delete}', 'bar')106 expect(() => {125 router.match('GET', '/')107 router.add('GET', '/:id/:action{delete}', 'bar')108 }).toThrowError(UnsupportedPathError)109 })110111 it('ALL route added after a specific-method route', () => {112 const router = new RegExpRouter<string>()113 router.add('GET', '/foo/:a', 'foo')114 expect(() => {115 router.add('ALL', '/foo/:b', 'bar')116 }).toThrowError(UnsupportedPathError)117 })118119 it('specific-method route added after an ALL route', () => {120 const router = new RegExpRouter<string>()121 router.add('ALL', '/reg-exp/router', 'foo')122123 expect(() => {124 router.add('GET', '/reg-exp/:id', 'bar')125 }).toThrowError(UnsupportedPathError)126 })127128 it('different methods do not conflict', () => {129 const router = new RegExpRouter<string>()130 router.add('GET', '/reg-exp/router', 'foo')131 router.add('POST', '/reg-exp/:id', 'bar')132133 expect(router.match('GET', '/reg-exp/router')[0][0][0]).toBe('foo')134 expect(router.match('POST', '/reg-exp/router')[0][0][0]).toBe('bar')135 })136137 describe('Capture Group', () => {138 describe('Complex capturing group', () => {139 it('GET request', () => {140 const router = new RegExpRouter<string>()133 router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')141 expect(() => {135 router.match('GET', '/foo/bar')142 router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')143 }).toThrowError(UnsupportedPathError)144 })145 })146 })147 })148149 describe('Wildcard after label', () => {150 it('Should be able to add a tail wildcard after a label', () => {151 const router = new RegExpRouter<string>()152 router.add('GET', '/api/:x', 'label')153 router.add('GET', '/api/*', 'wildcard')154155 const [res] = router.match('GET', '/api/foo')156 expect(res.length).toBe(2)157 expect(res[0][0]).toBe('label')158 expect(res[1][0]).toBe('wildcard')159 })160161 it('Should prioritize the only wildcard over the tail wildcard regardless of the order', () => {162 for (const paths of [163 ['/a*', '/a/*'],164 ['/a/*', '/a*'],165 ]) {166 const router = new RegExpRouter<string>()167 for (const path of paths) {168 router.add('GET', path, path)169 }170 const [res] = router.match('GET', '/a')171 expect(res[0][0]).toBe('/a*')172 }173 })174 })175176 describe('Single character regexp pattern', () => {177 it('Should capture a param even if a static path created the node first', () => {178 const router = new RegExpRouter<string>()179 router.add('GET', '/a/c', 'static')180 router.add('GET', '/:x{a}/b', 'pattern')181182 const [res, stash] = router.match('GET', '/a/b')183 expect(res.length).toBe(1)184 expect(res[0][0]).toBe('pattern')185 expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['x']]).toBe('a')186 })187188 it('Should throw an error when a pattern terminal conflicts with a static terminal', () => {189 for (const paths of [190 ['/a', '/:x{a}'],191 ['/:x{a}', '/a'],192 ]) {193 const router = new RegExpRouter<string>()194 router.add('GET', paths[0], paths[0])195 expect(() => {196 router.add('GET', paths[1], paths[1])197 }).toThrowError(UnsupportedPathError)198 }199 })200201 it('Should coexist with static paths regardless of the order', () => {202 for (const paths of [203 ['/foo/bar', '/:y{b}'],204 ['/:y{b}', '/foo/bar'],205 ]) {206 const router = new RegExpRouter<string>()207 for (const path of paths) {208 router.add('GET', path, path)209 }210 expect(router.match('GET', '/foo/bar')[0][0][0]).toBe('/foo/bar')211 expect(router.match('GET', '/b')[0][0][0]).toBe('/:y{b}')212 }213 })214215 it('Should coexist with dynamic paths regardless of the order', () => {216 for (const paths of [217 ['/foo/:p', '/:x{a}'],218 ['/:x{a}', '/foo/:p'],219 ]) {220 const router = new RegExpRouter<string>()221 for (const path of paths) {222 router.add('GET', path, path)223 }224 expect(router.match('GET', '/a')[0][0][0]).toBe('/:x{a}')225 expect(router.match('GET', '/foo/v')[0][0][0]).toBe('/foo/:p')226 }227 })228229 it('Should throw an error for a single meta character pattern', () => {230 const router = new RegExpRouter<string>()231 expect(() => {232 router.add('GET', '/:x{.}', 'meta')233 }).toThrowError(UnsupportedPathError)234 })235 })236237 describe('Capture a param of a label node created by a middle wildcard', () => {238 it('Should capture the param', () => {239 const router = new RegExpRouter<string>()240 router.add('GET', '/w/*/x', 'wildcard')241 router.add('GET', '/w/:id/y', 'label')242243 const [res, stash] = router.match('GET', '/w/123/y')244 expect(res.length).toBe(1)245 expect(res[0][0]).toBe('label')246 expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['id']]).toBe('123')247 })248 })249250 describe('Static path including a colon in the middle', () => {251 it('Should be treated as a static path', () => {252 for (const paths of [253 ['/v1/name:activate', '/v1/name2'],254 ['/v1/name2', '/v1/name:activate'],255 ]) {256 const router = new RegExpRouter<string>()257 for (const path of paths) {258 router.add('GET', path, path)259 }260 expect(router.match('GET', '/v1/name:activate')[0][0][0]).toBe('/v1/name:activate')261 expect(router.match('GET', '/v1/name2')[0][0][0]).toBe('/v1/name2')262 }263 })264 })265})
modified:src/router/reg-exp-router/router.ts+71 added-112 removed
6 unmodified lines
7import { checkOptionalParameter } from '../../utils/url'8import type { HandlerData, StaticMap, Matcher, MatcherMap } from './matcher'9import { match, emptyParam } from './matcher'10import { PATH_ERROR } from './node'11import type { ParamAssocArray } from './node'11import { Trie } from './trie'1213type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]1416// eslint-disable-next-line @typescript-eslint/no-explicit-any17const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]1815let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)16function buildWildcardRegExp(path: string): RegExp {17 return (wildcardRegExpCache[path] ??= new RegExp(18 path === '*'
7 unmodified lines
26function clearWildcardRegExpCache() {27 wildcardRegExpCache = Object.create(null)28}2934function buildMatcherFromPreprocessedRoutes<T>(35 routes: [string, HandlerWithMetadata<T>[]][]36): Matcher<T> {37 const trie = new Trie()38 const handlerData: HandlerData<T>[] = []39 if (routes.length === 0) {40 return nullMatcher41 }4243 const routesWithStaticPathFlag = routes44 .map(45 (route) => [!/\*|\/:/.test(route[0]), ...route] as [boolean, string, HandlerWithMetadata<T>[]]46 )47 .sort(([isStaticA, pathA], [isStaticB, pathB]) =>48 isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length49 )5051 const staticMap: StaticMap<T> = Object.create(null)52 for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {53 const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]54 if (pathErrorCheckOnly) {55 staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]56 } else {57 j++58 }5960 let paramAssoc: ParamAssocArray61 try {62 paramAssoc = trie.insert(path, j, pathErrorCheckOnly)63 } catch (e) {64 throw e === PATH_ERROR ? new UnsupportedPathError(path) : e65 }6667 if (pathErrorCheckOnly) {68 continue69 }7071 handlerData[j] = handlers.map(([h, paramCount]) => {72 const paramIndexMap: ParamIndexMap = Object.create(null)73 paramCount -= 174 for (; paramCount >= 0; paramCount--) {75 const [key, value] = paramAssoc[paramCount]76 paramIndexMap[key] = value77 }78 return [h, paramIndexMap]79 })80 }8182 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()83 for (let i = 0, len = handlerData.length; i < len; i++) {84 for (let j = 0, len = handlerData[i].length; j < len; j++) {85 const map = handlerData[i][j]?.[1]86 if (!map) {87 continue88 }89 const keys = Object.keys(map)90 for (let k = 0, len = keys.length; k < len; k++) {91 map[keys[k]] = paramReplacementMap[map[keys[k]]]92 }93 }94 }9596 const handlerMap: HandlerData<T>[] = []97 // using `in` because indexReplacementMap is a sparse array98 for (const i in indexReplacementMap) {99 handlerMap[i] = handlerData[indexReplacementMap[i]]100 }101102 return [regexp, handlerMap, staticMap] as Matcher<T>103}10430function findMiddleware<T>(31 middleware: Record<string, T[]> | undefined,32 path: string33): T[] | undefined {
13 unmodified lines
47export class RegExpRouter<T> implements Router<T> {48 name: string = 'RegExpRouter'49 #middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>50 #routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>51 #tries?: Record<string, Trie>5253 constructor() {54 this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }55 this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }56 this.#tries = { [METHOD_NAME_ALL]: new Trie() }57 }5859 #insertPath(method: string, path: string) {60 try {61 this.#tries![method].insert(path, !/\*|\/:/.test(path))62 } catch (e) {63 throw e === PATH_ERROR ? new UnsupportedPathError(path) : e64 }65 }6667 add(method: string, path: string, handler: T) {68 const middleware = this.#middleware69 const routes = this.#routes70
1 unmodified line
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) => {78 handlerMap[method] = Object.create(null)79 Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {80 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]81 this.#insertPath(method, p)82 })83 })84 }85
4 unmodified lines
90 const paramCount = (path.match(/\/:/g) || []).length9192 if (/\*$/.test(path)) {93 const re = buildWildcardRegExp(path)157 if (method === METHOD_NAME_ALL) {158 Object.keys(middleware).forEach((m) => {159 middleware[m][path] ||=94 Object.keys(middleware).forEach((m) => {95 if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {96 this.#insertPath(m, path)97 middleware[m][path] =98 findMiddleware(middleware[m], path) ||99 findMiddleware(middleware[METHOD_NAME_ALL], path) ||100 []163 })164 } else {165 middleware[method][path] ||=166 findMiddleware(middleware[method], path) ||167 findMiddleware(middleware[METHOD_NAME_ALL], path) ||168 []169 }101 }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])
17 unmodified lines
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)195 routes[m][path] ||= [196 ...(findMiddleware(middleware[m], path) ||197 findMiddleware(middleware[METHOD_NAME_ALL], path) ||198 []),199 ]130 routes[m][path] = [131 ...(findMiddleware(middleware[m], path) ||132 findMiddleware(middleware[METHOD_NAME_ALL], path) ||133 []),134 ]135 }136 routes[m][path].push([handler, paramCount - len + i + 1])137 }138 })139 }
10 unmodified lines
150 matchers[method] ||= this.#buildMatcher(method)151 })152153 // Release cache218 this.#middleware = this.#routes = undefined154 this.#middleware = this.#routes = this.#tries = undefined155 clearWildcardRegExpCache()156157 return matchers158 }159224 #buildMatcher(method: string): Matcher<T> | null {225 const routes: [string, HandlerWithMetadata<T>[]][] = []160 #buildMatcher(method: string): Matcher<T> {161 const middleware = this.#middleware![method]162 const routes = this.#routes![method]163227 let hasOwnRoute = method === METHOD_NAME_ALL164 const trie = this.#tries![method]165 const staticMap: StaticMap<T> = Object.create(null)166 const handlerData: HandlerData<T>[] = []167229 ;[this.#middleware!, this.#routes!].forEach((r) => {230 const ownRoute = r[method]231 ? Object.keys(r[method]).map((path) => [path, r[method][path]])232 : []233 if (ownRoute.length !== 0) {234 hasOwnRoute ||= true235 routes.push(...(ownRoute as [string, HandlerWithMetadata<T>[]][]))236 } else if (method !== METHOD_NAME_ALL) {237 routes.push(238 ...(Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) as [239 string,240 HandlerWithMetadata<T>[],241 ][])242 )168 ;[middleware, routes].forEach((r) => {169 for (const path in r) {170 const handlers = r[path]171 const pathData = trie.paths[path]172 if (!pathData) {173 staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]174 continue175 }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 })186 }187 })188246 if (!hasOwnRoute) {247 return null248 } else {249 return buildMatcherFromPreprocessedRoutes(routes)189 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 }201 }202203 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>210 }211}
modified:src/router/reg-exp-router/trie.ts+15 added-6 removed
4 unmodified lines
56export class Trie {7 #context: Context = { varIndex: 0 }8 #root: Node = new Node()9 #index: number = 010 // dynamic path -> [handler index, param assoc]; static paths are not registered11 paths: Record<string, [number, ParamAssocArray]> = Object.create(null)1210 insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {13 insert(path: string, isStatic: boolean): void {14 if (isStatic) {15 // a static path has no pattern; every character is a literal token16 this.#root.insert(path.split(''), 0, [], this.#context, true)17 return18 }1920 const paramAssoc: ParamAssocArray = []2122 const groups: [string, string][] = [] // [mark, original string]23 let markedPath = path24 for (let i = 0; ; ) {25 let replaced = false16 path = path.replace(/\{[^}]+\}/g, (m) => {26 markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {27 const mark = `@\\${i}`28 groups[i] = [mark, m]29 i++30 replaced = true
8 unmodified lines
39 * - pattern (:label, :label{0-9]+}, ...)40 * - /* wildcard41 * - character42 */33 const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []43 const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []44 for (let i = groups.length - 1; i >= 0; i--) {45 const [mark] = groups[i]46 for (let j = tokens.length - 1; j >= 0; j--) {47 if (tokens[j].indexOf(mark) !== -1) {
2 unmodified lines
50 }51 }52 }5344 this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly)4546 return paramAssoc54 this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false)55 this.paths[path] = [this.#index++, paramAssoc]56 }5758 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {59 let regexp = this.#root.buildRegExpStr()
24 unmodified lines