UNPKG

next

Version:

The React Framework

81 lines (80 loc) 3.36 kB
/** * Client-safe utilities for route matching that don't import server-side * utilities to avoid bundling issues with Turbopack */ import { pathToRegexp, compile, regexpToFunction } from 'next/dist/compiled/path-to-regexp'; import { hasAdjacentParameterIssues, normalizeAdjacentParameters, stripParameterSeparators } from '../../../../lib/route-pattern-normalizer'; /** * Client-safe wrapper around pathToRegexp that handles path-to-regexp 6.3.0+ validation errors. * This includes both "Can not repeat without prefix/suffix" and "Must have text between parameters" errors. */ export function safePathToRegexp(route, keys, options) { if (typeof route !== 'string') { return pathToRegexp(route, keys, options); } // Check if normalization is needed and cache the result const needsNormalization = hasAdjacentParameterIssues(route); const routeToUse = needsNormalization ? normalizeAdjacentParameters(route) : route; try { return pathToRegexp(routeToUse, keys, options); } catch (error) { // Only try normalization if we haven't already normalized if (!needsNormalization) { try { const normalizedRoute = normalizeAdjacentParameters(route); return pathToRegexp(normalizedRoute, keys, options); } catch (retryError) { // If that doesn't work, fall back to original error throw error; } } throw error; } } /** * Client-safe wrapper around compile that handles path-to-regexp 6.3.0+ validation errors. * No server-side error reporting to avoid bundling issues. */ export function safeCompile(route, options) { // Check if normalization is needed and cache the result const needsNormalization = hasAdjacentParameterIssues(route); const routeToUse = needsNormalization ? normalizeAdjacentParameters(route) : route; try { return compile(routeToUse, options); } catch (error) { // Only try normalization if we haven't already normalized if (!needsNormalization) { try { const normalizedRoute = normalizeAdjacentParameters(route); return compile(normalizedRoute, options); } catch (retryError) { // If that doesn't work, fall back to original error throw error; } } throw error; } } /** * Client-safe wrapper around regexpToFunction that automatically cleans parameters. */ export function safeRegexpToFunction(regexp, keys) { const originalMatcher = regexpToFunction(regexp, keys || []); return (pathname)=>{ const result = originalMatcher(pathname); if (!result) return false; // Clean parameters before returning return { ...result, params: stripParameterSeparators(result.params) }; }; } /** * Safe wrapper for route matcher functions that automatically cleans parameters. * This is client-safe and doesn't import path-to-regexp. */ export function safeRouteMatcher(matcherFn) { return (pathname)=>{ const result = matcherFn(pathname); if (!result) return false; // Clean parameters before returning return stripParameterSeparators(result); }; } //# sourceMappingURL=route-match-utils.js.map