File size: 1,377 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import type { Group } from './route-regex'
import { DecodeError } from '../../utils'
import type { Params } from '../../../../server/request/params'
import { safeRouteMatcher } from './route-match-utils'

export interface RouteMatchFn {
  (pathname: string): false | Params
}

type RouteMatcherOptions = {
  // We only use the exec method of the RegExp object. This helps us avoid using
  // type assertions that the passed in properties are of the correct type.
  re: Pick<RegExp, 'exec'>
  groups: Record<string, Group>
}

export function getRouteMatcher({
  re,
  groups,
}: RouteMatcherOptions): RouteMatchFn {
  const rawMatcher = (pathname: string) => {
    const routeMatch = re.exec(pathname)
    if (!routeMatch) return false

    const decode = (param: string) => {
      try {
        return decodeURIComponent(param)
      } catch {
        throw new DecodeError('failed to decode param')
      }
    }

    const params: Params = {}
    for (const [key, group] of Object.entries(groups)) {
      const match = routeMatch[group.pos]
      if (match !== undefined) {
        if (group.repeat) {
          params[key] = match.split('/').map((entry) => decode(entry))
        } else {
          params[key] = decode(match)
        }
      }
    }

    return params
  }

  // Wrap with safe matcher to handle parameter cleaning
  return safeRouteMatcher(rawMatcher)
}