Skip to content
Myr

router.ts

This file

Path

src/router/pattern-router/router.ts

54 lines · 1.6 KiB · TypeScript

Last changed by

fix(pattern-router/linear-router): prevent prefix overmatch on wildcard routes (#5252)Yusuke Wadabefore adoptiona194628

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–12why, one step back
1import type { Params, Result, Router } from '../../router'
2import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router'34type Route<T> = [RegExp, string, T] // [pattern, method, handler]56const emptyParams = Object.create(null)78export class PatternRouter<T> implements Router<T> {9 name: string = 'PatternRouter'10 #routes: Route<T>[] = []1112 add(method: string, path: string, handler: T) {

fix(pattern-router/linear-router): prevent prefix overmatch on wildcard routes (#5252)Yusuke Wadabefore adoptiona194628

lines 13–14why, one step back
13 const suffix = path.endsWith('/*') ? '(?:$|/)' : path.endsWith('*') ? '' : '/?$'
14 path = path.replace(/\*$/, '')

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 15–31why, one step back
15 if (path.at(-1) === '?') {
16 path = path.slice(0, -1)17 this.add(method, path.replace(/\/[^/]+$/, ''), handler)18 }1920 const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map(21 (part) => {22 const match = part.match(/^\/:([^{]+)(?:{(.*)})?/)23 return match24 ? `/(?<${match[1]}>${match[2] || '[^/]+'})`25 : part === '/*'26 ? '/[^/]+'27 : part.replace(/[.\\+*[^\]$()]/g, '\\$&')28 }29 )3031 try {

fix(pattern-router/linear-router): prevent prefix overmatch on wildcard routes (#5252)Yusuke Wadabefore adoptiona194628

line 32why, one step back
32 this.#routes.push([new RegExp(`^${parts.join('')}${suffix}`), method, handler])

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 33–54why, one step back
33 } catch {
34 throw new UnsupportedPathError()35 }36 }3738 match(method: string, path: string): Result<T> {39 const handlers: [T, Params][] = []4041 for (let i = 0, len = this.#routes.length; i < len; i++) {42 const [pattern, routeMethod, handler] = this.#routes[i]4344 if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {45 const match = pattern.exec(path)46 if (match) {47 handlers.push([handler, match.groups || emptyParams])48 }49 }50 }5152 return [handlers]53 }54}