Skip to content

Commit ea9a657

Browse files
feat(router-generator): allow escaping any special string in file-based routing
This change extends the router-generator's escaping mechanism to allow ANY special string to be escaped using square bracket syntax, not just dots. ## Problem Previously, the router-generator only supported escaping dots using [.] syntax (e.g., script[.]js.tsx -> /script.js). However, special strings like 'index', 'route', 'lazy', and underscores ('_') could not be escaped, making it impossible to create routes with literal paths like /index, /route, /lazy, or paths containing literal underscores. ## Solution Extended the escaping mechanism to support: 1. **Escaped special suffixes**: [index], [route], [lazy], [component], etc. - [index].tsx -> /index (literal path, NOT treated as index route) - [route].tsx -> /route (literal path, NOT treated as layout config) - [lazy].tsx -> /lazy (literal path, NOT treated as lazy-loaded route) 2. **Escaped underscores in any position**: - Leading: [_]layout.tsx -> /_layout (literal, NOT pathless layout) - Trailing: blog[_].tsx -> /blog_ (literal, NOT escaping parent layout) - Middle: foo[_]bar.tsx -> /foo_bar (literal underscore preserved) - Multiple: api[_]v2[_]users.tsx -> /api_v2_users - Fully escaped: [_prefix_middle_suffix].tsx -> /_prefix_middle_suffix 3. **Custom token escaping**: Works with custom indexToken and routeToken - [_1nd3x].tsx with indexToken='_1nd3x' -> /_1nd3x (literal path) - posts.[_r0ut3_].tsx with routeToken='_r0ut3_' -> /posts/_r0ut3_ ## Implementation Details ### src/utils.ts - Removed '_' from DISALLOWED_ESCAPE_CHARS to allow underscore escaping - Added isSegmentEscaped() to check if a segment was bracket-escaped - Added hasEscapedLeadingUnderscore() to detect [_] prefix or [_...] patterns - Added hasEscapedTrailingUnderscore() to detect [_] suffix or [..._] patterns - Added removeUnderscoresWithEscape() to preserve escaped underscores - Added removeLayoutSegmentsWithEscape() to preserve escaped layout segments - Added isSegmentPathless() to check for non-escaped leading underscores - Updated inferFullPath() to use escape-aware functions ### src/filesystem/physical/getRouteNodes.ts - Added escape checking for special suffixes (route, lazy, component, etc.) - Updated isValidPathlessLayoutRoute() to check for escaped underscores - Updated getRouteMeta() to accept originalRoutePath and check escaping ### src/generator.ts - Updated handleNode() to use escape-aware path processing functions - Compute trimmedOriginalPath alongside trimmedPath for escape detection ## Tests Added - escaped-special-strings: Tests escaping of index, route, lazy, and underscores in various positions (leading, trailing, middle, multiple) - escaped-custom-tokens: Tests escaping with custom indexToken and routeToken configurations
1 parent 27d1c5e commit ea9a657

24 files changed

Lines changed: 852 additions & 60 deletions

‎packages/router-generator/src/filesystem/physical/getRouteNodes.ts‎

Lines changed: 119 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from 'node:path'
22
import * as fsp from 'node:fs/promises'
33
import {
44
determineInitialRoutePath,
5+
hasEscapedLeadingUnderscore,
56
removeExt,
67
replaceBackslash,
78
routePathToVariable,
@@ -153,7 +154,7 @@ export async function getRouteNodes(
153154
throw new Error(errorMessage)
154155
}
155156

156-
const meta = getRouteMeta(routePath, config)
157+
const meta = getRouteMeta(routePath, originalRoutePath, config)
157158
const variableName = meta.variableName
158159
let routeType: FsRouteType = meta.fsRouteType
159160

@@ -164,7 +165,14 @@ export async function getRouteNodes(
164165

165166
// this check needs to happen after the lazy route has been cleaned up
166167
// since the routePath is used to determine if a route is pathless
167-
if (isValidPathlessLayoutRoute(routePath, routeType, config)) {
168+
if (
169+
isValidPathlessLayoutRoute(
170+
routePath,
171+
originalRoutePath,
172+
routeType,
173+
config,
174+
)
175+
) {
168176
routeType = 'pathless_layout'
169177
}
170178

@@ -189,37 +197,64 @@ export async function getRouteNodes(
189197
})
190198
}
191199

192-
routePath = routePath.replace(
193-
new RegExp(
194-
`/(component|errorComponent|notFoundComponent|pendingComponent|loader|${config.routeToken}|lazy)$`,
195-
),
196-
'',
197-
)
198-
199-
originalRoutePath = originalRoutePath.replace(
200-
new RegExp(
201-
`/(component|errorComponent|notFoundComponent|pendingComponent|loader|${config.routeToken}|lazy)$`,
202-
),
203-
'',
204-
)
200+
// Get the last segment of originalRoutePath to check for escaping
201+
const originalSegments = originalRoutePath.split('/').filter(Boolean)
202+
const lastOriginalSegmentForSuffix =
203+
originalSegments[originalSegments.length - 1] || ''
204+
205+
// List of special suffixes that can be escaped
206+
const specialSuffixes = [
207+
'component',
208+
'errorComponent',
209+
'notFoundComponent',
210+
'pendingComponent',
211+
'loader',
212+
config.routeToken,
213+
'lazy',
214+
]
215+
216+
// Only strip the suffix if it wasn't escaped (not wrapped in brackets)
217+
const suffixToStrip = specialSuffixes.find((suffix) => {
218+
const endsWithSuffix = routePath.endsWith(`/${suffix}`)
219+
const isEscaped = lastOriginalSegmentForSuffix === `[${suffix}]`
220+
return endsWithSuffix && !isEscaped
221+
})
205222

206-
if (routePath === config.indexToken) {
207-
routePath = '/'
223+
if (suffixToStrip) {
224+
routePath = routePath.replace(new RegExp(`/${suffixToStrip}$`), '')
225+
originalRoutePath = originalRoutePath.replace(
226+
new RegExp(`/${suffixToStrip}$`),
227+
'',
228+
)
208229
}
209230

210-
if (originalRoutePath === config.indexToken) {
211-
originalRoutePath = '/'
231+
// Check if the index token should be treated specially or as a literal path
232+
// If it's escaped (wrapped in brackets in originalRoutePath), it should be literal
233+
const lastOriginalSegment =
234+
originalRoutePath.split('/').filter(Boolean).pop() || ''
235+
const isIndexEscaped =
236+
lastOriginalSegment === `[${config.indexToken}]`
237+
238+
if (!isIndexEscaped) {
239+
if (routePath === config.indexToken) {
240+
routePath = '/'
241+
}
242+
243+
if (originalRoutePath === config.indexToken) {
244+
originalRoutePath = '/'
245+
}
246+
247+
routePath =
248+
routePath.replace(new RegExp(`/${config.indexToken}$`), '/') ||
249+
'/'
250+
251+
originalRoutePath =
252+
originalRoutePath.replace(
253+
new RegExp(`/${config.indexToken}$`),
254+
'/',
255+
) || '/'
212256
}
213257

214-
routePath =
215-
routePath.replace(new RegExp(`/${config.indexToken}$`), '/') || '/'
216-
217-
originalRoutePath =
218-
originalRoutePath.replace(
219-
new RegExp(`/${config.indexToken}$`),
220-
'/',
221-
) || '/'
222-
223258
routeNodes.push({
224259
filePath,
225260
fullPath,
@@ -266,12 +301,14 @@ export async function getRouteNodes(
266301
/**
267302
* Determines the metadata for a given route path based on the provided configuration.
268303
*
269-
* @param routePath - The determined initial routePath.
304+
* @param routePath - The determined initial routePath (with brackets removed).
305+
* @param originalRoutePath - The original route path (may contain brackets for escaped content).
270306
* @param config - The user configuration object.
271307
* @returns An object containing the type of the route and the variable name derived from the route path.
272308
*/
273309
export function getRouteMeta(
274310
routePath: string,
311+
originalRoutePath: string,
275312
config: Pick<Config, 'routeToken' | 'indexToken'>,
276313
): {
277314
// `__root` is can be more easily determined by filtering down to routePath === /${rootPathId}
@@ -292,25 +329,50 @@ export function getRouteMeta(
292329
} {
293330
let fsRouteType: FsRouteType = 'static'
294331

295-
if (routePath.endsWith(`/${config.routeToken}`)) {
332+
// Get the last segment from the original path to check for escaping
333+
const originalSegments = originalRoutePath.split('/').filter(Boolean)
334+
const lastOriginalSegment =
335+
originalSegments[originalSegments.length - 1] || ''
336+
337+
// Helper to check if a specific suffix is escaped
338+
const isSuffixEscaped = (suffix: string): boolean => {
339+
return lastOriginalSegment === `[${suffix}]`
340+
}
341+
342+
if (
343+
routePath.endsWith(`/${config.routeToken}`) &&
344+
!isSuffixEscaped(config.routeToken)
345+
) {
296346
// layout routes, i.e `/foo/route.tsx` or `/foo/_layout/route.tsx`
297347
fsRouteType = 'layout'
298-
} else if (routePath.endsWith('/lazy')) {
348+
} else if (routePath.endsWith('/lazy') && !isSuffixEscaped('lazy')) {
299349
// lazy routes, i.e. `/foo.lazy.tsx`
300350
fsRouteType = 'lazy'
301-
} else if (routePath.endsWith('/loader')) {
351+
} else if (routePath.endsWith('/loader') && !isSuffixEscaped('loader')) {
302352
// loader routes, i.e. `/foo.loader.tsx`
303353
fsRouteType = 'loader'
304-
} else if (routePath.endsWith('/component')) {
354+
} else if (
355+
routePath.endsWith('/component') &&
356+
!isSuffixEscaped('component')
357+
) {
305358
// component routes, i.e. `/foo.component.tsx`
306359
fsRouteType = 'component'
307-
} else if (routePath.endsWith('/pendingComponent')) {
360+
} else if (
361+
routePath.endsWith('/pendingComponent') &&
362+
!isSuffixEscaped('pendingComponent')
363+
) {
308364
// pending component routes, i.e. `/foo.pendingComponent.tsx`
309365
fsRouteType = 'pendingComponent'
310-
} else if (routePath.endsWith('/errorComponent')) {
366+
} else if (
367+
routePath.endsWith('/errorComponent') &&
368+
!isSuffixEscaped('errorComponent')
369+
) {
311370
// error component routes, i.e. `/foo.errorComponent.tsx`
312371
fsRouteType = 'errorComponent'
313-
} else if (routePath.endsWith('/notFoundComponent')) {
372+
} else if (
373+
routePath.endsWith('/notFoundComponent') &&
374+
!isSuffixEscaped('notFoundComponent')
375+
) {
314376
// not found component routes, i.e. `/foo.notFoundComponent.tsx`
315377
fsRouteType = 'notFoundComponent'
316378
}
@@ -323,11 +385,14 @@ export function getRouteMeta(
323385
/**
324386
* Used to validate if a route is a pathless layout route
325387
* @param normalizedRoutePath Normalized route path, i.e `/foo/_layout/route.tsx` and `/foo._layout.route.tsx` to `/foo/_layout/route`
388+
* @param originalRoutePath Original route path with brackets for escaped content
389+
* @param routeType The route type determined from file extension
326390
* @param config The `router-generator` configuration object
327391
* @returns Boolean indicating if the route is a pathless layout route
328392
*/
329393
function isValidPathlessLayoutRoute(
330394
normalizedRoutePath: string,
395+
originalRoutePath: string,
331396
routeType: FsRouteType,
332397
config: Pick<Config, 'routeToken' | 'indexToken'>,
333398
): boolean {
@@ -336,13 +401,18 @@ function isValidPathlessLayoutRoute(
336401
}
337402

338403
const segments = normalizedRoutePath.split('/').filter(Boolean)
404+
const originalSegments = originalRoutePath.split('/').filter(Boolean)
339405

340406
if (segments.length === 0) {
341407
return false
342408
}
343409

344410
const lastRouteSegment = segments[segments.length - 1]!
411+
const lastOriginalSegment =
412+
originalSegments[originalSegments.length - 1] || ''
345413
const secondToLastRouteSegment = segments[segments.length - 2]
414+
const secondToLastOriginalSegment =
415+
originalSegments[originalSegments.length - 2]
346416

347417
// If segment === __root, then exit as false
348418
if (lastRouteSegment === rootPathId) {
@@ -352,14 +422,25 @@ function isValidPathlessLayoutRoute(
352422
// If segment === config.routeToken and secondToLastSegment is a string that starts with _, then exit as true
353423
// Since the route is actually a configuration route for a layout/pathless route
354424
// i.e. /foo/_layout/route.tsx === /foo/_layout.tsx
425+
// But if the underscore is escaped, it's not a pathless layout
355426
if (
356427
lastRouteSegment === config.routeToken &&
357-
typeof secondToLastRouteSegment === 'string'
428+
typeof secondToLastRouteSegment === 'string' &&
429+
typeof secondToLastOriginalSegment === 'string'
358430
) {
431+
// Check if the underscore is escaped
432+
if (hasEscapedLeadingUnderscore(secondToLastOriginalSegment)) {
433+
return false
434+
}
359435
return secondToLastRouteSegment.startsWith('_')
360436
}
361437

362-
// Segment starts with _
438+
// Segment starts with _ but check if it's escaped
439+
// If the original segment has [_] at the start, the underscore is escaped and it's not a pathless layout
440+
if (hasEscapedLeadingUnderscore(lastOriginalSegment)) {
441+
return false
442+
}
443+
363444
return (
364445
lastRouteSegment !== config.indexToken &&
365446
lastRouteSegment !== config.routeToken &&

‎packages/router-generator/src/generator.ts‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,15 @@ import {
2828
getResolvedRouteNodeVariableName,
2929
hasParentRoute,
3030
isRouteNodeValidForAugmentation,
31+
isSegmentPathless,
3132
mergeImportDeclarations,
3233
multiSortBy,
3334
removeExt,
3435
removeGroups,
3536
removeLastSegmentFromPath,
36-
removeLayoutSegments,
37+
removeLayoutSegmentsWithEscape,
3738
removeTrailingSlash,
38-
removeUnderscores,
39+
removeUnderscoresWithEscape,
3940
replaceBackslash,
4041
trimPathLeft,
4142
} from './utils'
@@ -1363,16 +1364,30 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
13631364
node.path = determineNodePath(node)
13641365

13651366
const trimmedPath = trimPathLeft(node.path ?? '')
1367+
const trimmedOriginalPath = trimPathLeft(
1368+
node.originalRoutePath?.replace(
1369+
node.parent?.originalRoutePath ?? '',
1370+
'',
1371+
) ?? '',
1372+
)
13661373

13671374
const split = trimmedPath.split('/')
1375+
const originalSplit = trimmedOriginalPath.split('/')
13681376
const lastRouteSegment = split[split.length - 1] ?? trimmedPath
1377+
const lastOriginalSegment =
1378+
originalSplit[originalSplit.length - 1] ?? trimmedOriginalPath
13691379

1380+
// A segment is non-path if it starts with underscore AND the underscore is not escaped
13701381
node.isNonPath =
1371-
lastRouteSegment.startsWith('_') ||
1382+
isSegmentPathless(lastRouteSegment, lastOriginalSegment) ||
13721383
split.every((part) => this.routeGroupPatternRegex.test(part))
13731384

1385+
// Use escape-aware functions to compute cleanedPath
13741386
node.cleanedPath = removeGroups(
1375-
removeUnderscores(removeLayoutSegments(node.path)) ?? '',
1387+
removeUnderscoresWithEscape(
1388+
removeLayoutSegmentsWithEscape(node.path, node.originalRoutePath),
1389+
node.originalRoutePath,
1390+
),
13761391
)
13771392

13781393
if (
@@ -1431,6 +1446,8 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
14311446
if (!node.isVirtual && isPathlessLayoutWithPath) {
14321447
const immediateParentPath =
14331448
removeLastSegmentFromPath(node.routePath) || '/'
1449+
const immediateParentOriginalPath =
1450+
removeLastSegmentFromPath(node.originalRoutePath) || '/'
14341451
let searchPath = immediateParentPath
14351452

14361453
// Find nearest real (non-virtual, non-index) parent
@@ -1442,8 +1459,19 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
14421459
node.routePath?.replace(candidate.routePath ?? '', '') || '/'
14431460
const pathRelativeToParent =
14441461
immediateParentPath.replace(candidate.routePath ?? '', '') || '/'
1462+
const originalPathRelativeToParent =
1463+
immediateParentOriginalPath.replace(
1464+
candidate.originalRoutePath ?? '',
1465+
'',
1466+
) || '/'
14451467
node.cleanedPath = removeGroups(
1446-
removeUnderscores(removeLayoutSegments(pathRelativeToParent)) ?? '',
1468+
removeUnderscoresWithEscape(
1469+
removeLayoutSegmentsWithEscape(
1470+
pathRelativeToParent,
1471+
originalPathRelativeToParent,
1472+
),
1473+
originalPathRelativeToParent,
1474+
),
14471475
)
14481476
break
14491477
}

0 commit comments

Comments
 (0)