|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import type { |
|
|
Key, |
|
|
TokensToRegexpOptions, |
|
|
ParseOptions, |
|
|
TokensToFunctionOptions, |
|
|
} from 'next/dist/compiled/path-to-regexp' |
|
|
import { |
|
|
pathToRegexp, |
|
|
compile, |
|
|
regexpToFunction, |
|
|
} from 'next/dist/compiled/path-to-regexp' |
|
|
import { |
|
|
hasAdjacentParameterIssues, |
|
|
normalizeAdjacentParameters, |
|
|
stripParameterSeparators, |
|
|
} from '../../../../lib/route-pattern-normalizer' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function safePathToRegexp( |
|
|
route: string | RegExp | Array<string | RegExp>, |
|
|
keys?: Key[], |
|
|
options?: TokensToRegexpOptions & ParseOptions |
|
|
): RegExp { |
|
|
if (typeof route !== 'string') { |
|
|
return pathToRegexp(route, keys, options) |
|
|
} |
|
|
|
|
|
|
|
|
const needsNormalization = hasAdjacentParameterIssues(route) |
|
|
const routeToUse = needsNormalization |
|
|
? normalizeAdjacentParameters(route) |
|
|
: route |
|
|
|
|
|
try { |
|
|
return pathToRegexp(routeToUse, keys, options) |
|
|
} catch (error) { |
|
|
|
|
|
if (!needsNormalization) { |
|
|
try { |
|
|
const normalizedRoute = normalizeAdjacentParameters(route) |
|
|
return pathToRegexp(normalizedRoute, keys, options) |
|
|
} catch (retryError) { |
|
|
|
|
|
throw error |
|
|
} |
|
|
} |
|
|
throw error |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function safeCompile( |
|
|
route: string, |
|
|
options?: TokensToFunctionOptions & ParseOptions |
|
|
) { |
|
|
|
|
|
const needsNormalization = hasAdjacentParameterIssues(route) |
|
|
const routeToUse = needsNormalization |
|
|
? normalizeAdjacentParameters(route) |
|
|
: route |
|
|
|
|
|
try { |
|
|
return compile(routeToUse, options) |
|
|
} catch (error) { |
|
|
|
|
|
if (!needsNormalization) { |
|
|
try { |
|
|
const normalizedRoute = normalizeAdjacentParameters(route) |
|
|
return compile(normalizedRoute, options) |
|
|
} catch (retryError) { |
|
|
|
|
|
throw error |
|
|
} |
|
|
} |
|
|
throw error |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function safeRegexpToFunction< |
|
|
T extends Record<string, any> = Record<string, any>, |
|
|
>(regexp: RegExp, keys?: Key[]): (pathname: string) => { params: T } | false { |
|
|
const originalMatcher = regexpToFunction<T>(regexp, keys || []) |
|
|
|
|
|
return (pathname: string) => { |
|
|
const result = originalMatcher(pathname) |
|
|
if (!result) return false |
|
|
|
|
|
|
|
|
return { |
|
|
...result, |
|
|
params: stripParameterSeparators(result.params as any) as T, |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function safeRouteMatcher<T extends Record<string, any>>( |
|
|
matcherFn: (pathname: string) => false | T |
|
|
): (pathname: string) => false | T { |
|
|
return (pathname: string) => { |
|
|
const result = matcherFn(pathname) |
|
|
if (!result) return false |
|
|
|
|
|
|
|
|
return stripParameterSeparators(result) as T |
|
|
} |
|
|
} |
|
|
|