2019-05-27 20:20:33 +02:00
|
|
|
export function getRouteRegex(
|
2019-05-30 22:42:45 +02:00
|
|
|
normalizedRoute: string
|
2019-12-02 22:55:49 +01:00
|
|
|
): {
|
|
|
|
re: RegExp
|
|
|
|
groups: { [groupName: string]: { pos: number; repeat: boolean } }
|
|
|
|
} {
|
2019-06-21 00:27:04 +02:00
|
|
|
// Escape all characters that could be considered RegEx
|
2019-05-30 22:42:45 +02:00
|
|
|
const escapedRoute = (normalizedRoute.replace(/\/$/, '') || '/').replace(
|
2019-05-27 20:20:33 +02:00
|
|
|
/[|\\{}()[\]^$+*?.-]/g,
|
2019-05-29 13:57:26 +02:00
|
|
|
'\\$&'
|
2019-05-27 20:20:33 +02:00
|
|
|
)
|
|
|
|
|
2019-12-02 22:55:49 +01:00
|
|
|
const groups: { [groupName: string]: { pos: number; repeat: boolean } } = {}
|
2019-05-27 20:20:33 +02:00
|
|
|
let groupIndex = 1
|
|
|
|
|
|
|
|
const parameterizedRoute = escapedRoute.replace(
|
2019-11-11 04:24:53 +01:00
|
|
|
/\/\\\[([^/]+?)\\\](?=\/|$)/g,
|
2019-12-02 22:55:49 +01:00
|
|
|
(_, $1) => {
|
|
|
|
const isCatchAll = /^(\\\.){3}/.test($1)
|
|
|
|
groups[
|
2019-05-29 23:29:02 +02:00
|
|
|
$1
|
|
|
|
// Un-escape key
|
|
|
|
.replace(/\\([|\\{}()[\]^$+*?.-])/g, '$1')
|
2019-11-15 08:19:41 +01:00
|
|
|
.replace(/^\.{3}/, '')
|
2019-11-11 04:24:53 +01:00
|
|
|
// eslint-disable-next-line no-sequences
|
2019-12-02 22:55:49 +01:00
|
|
|
] = { pos: groupIndex++, repeat: isCatchAll }
|
|
|
|
return isCatchAll ? '/(.+?)' : '/([^/]+?)'
|
|
|
|
}
|
2019-05-27 20:20:33 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
return {
|
|
|
|
re: new RegExp('^' + parameterizedRoute + '(?:/)?$', 'i'),
|
|
|
|
groups,
|
|
|
|
}
|
|
|
|
}
|