Open History to see the last commit
1import * as fsp from 'node:fs/promises'
2import path from 'node:path'
3import * as prettier from 'prettier'
4import { rootPathId } from './filesystem/physical/rootPathId'
5import type { Config } from './config'
6import type { ImportDeclaration, RouteNode } from './types'
7β
8export function multiSortBy<T>(
9 arr: Array<T>,
10 accessors: Array<(item: T) => any> = [(d) => d],
11): Array<T> {
12 return arr
13 .map((d, i) => [d, i] as const)
14 .sort(([a, ai], [b, bi]) => {
15 for (const accessor of accessors) {
16 const ao = accessor(a)
17 const bo = accessor(b)
18β
19 if (typeof ao === 'undefined') {
20 if (typeof bo === 'undefined') {
21 continue
22 }
23 return 1
24 }
25β
26 if (ao === bo) {
27 continue
28 }
29β
30 return ao > bo ? 1 : -1
31 }
32β
33 return ai - bi
34 })
35 .map(([d]) => d)
36}
37β
38export function cleanPath(path: string) {
39 // remove double slashes
40 return path.replace(/\/{2,}/g, '/')
41}
42β
43export function trimPathLeft(path: string) {
44 return path === '/' ? path : path.replace(/^\/{1,}/, '')
45}
46β
47export function removeLeadingSlash(path: string): string {
48 return path.replace(/^\//, '')
49}
50β
51export function removeTrailingSlash(s: string) {
52 return s.replace(/\/$/, '')
53}
54β
55const BRACKET_CONTENT_RE = /\[(.*?)\]/g
56const SPLIT_REGEX = /(?<!\[)\.(?!\])/g
57β
58export function determineInitialRoutePath(
59 routePath: string,
60 config?: Pick<Config, 'experimental' | 'routeToken' | 'indexToken'>,
61) {
62 const DISALLOWED_ESCAPE_CHARS = new Set([
63 '/',
64 '\\',
65 '?',
66 '#',
67 ':',
68 '*',
69 '<',
70 '>',
71 '|',
72 '!',
73 '$',
74 '%',
75 ])
76β
77 const originalRoutePath =
78 cleanPath(
79 `/${(cleanPath(routePath) || '').split(SPLIT_REGEX).join('/')}`,
80 ) || ''
81β
82 // check if the route path is a valid non-nested path,
83 // TODO with new major rename to reflect not experimental anymore
84 const isExperimentalNonNestedRoute = isValidNonNestedRoute(
85 originalRoutePath,
86 config,
87 )
88β
89 let cleanedRoutePath = routePath
90β
91 // we already identified the path as non-nested and can now remove the trailing underscores
92 // we need to do this now before we encounter any escaped trailing underscores
93 // this way we can be sure any remaining trailing underscores should remain
94 // TODO with new major we can remove check and always remove leading underscores
95 if (config?.experimental?.nonNestedRoutes) {
96 // we should leave trailing underscores if the route path is the root path
97 if (originalRoutePath !== `/${rootPathId}`) {
98 // remove trailing underscores on various path segments
99 cleanedRoutePath = removeTrailingUnderscores(
100 originalRoutePath,
101 config.routeToken,
102 )
103 }
104 }
105β
106 const parts = cleanedRoutePath.split(SPLIT_REGEX)
107β
108 // Escape any characters that in square brackets
109 // we keep the original path untouched
110 const escapedParts = parts.map((part) => {
111 // Check if any disallowed characters are used in brackets
112β
113 let match
114 while ((match = BRACKET_CONTENT_RE.exec(part)) !== null) {
115 const character = match[1]
116 if (character === undefined) continue
117 if (DISALLOWED_ESCAPE_CHARS.has(character)) {
118 console.error(
119 `Error: Disallowed character "${character}" found in square brackets in route path "${routePath}".\nYou cannot use any of the following characters in square brackets: ${Array.from(
120 DISALLOWED_ESCAPE_CHARS,
121 ).join(', ')}\nPlease remove and/or replace them.`,
122 )
123 process.exit(1)
124 }
125 }
126β
127 // Since this split segment is safe at this point, we can
128 // remove the brackets and replace them with the content inside
129 return part.replace(BRACKET_CONTENT_RE, '$1')
130 })
131β
132 // If the syntax for prefix/suffix is different, from the path
133 // matching internals of router-core, we'd perform those changes here
134 // on the `escapedParts` array before it is joined back together in
135 // `final`
136β
137 const final = cleanPath(`/${escapedParts.join('/')}`) || ''
138β
139 return {
140 routePath: final,
141 isExperimentalNonNestedRoute,
142 originalRoutePath,
143 }
144}
145β
146export function replaceBackslash(s: string) {
147 return s.replaceAll(/\\/gi, '/')
148}
149β
150export function routePathToVariable(routePath: string): string {
151 const toVariableSafeChar = (char: string): string => {
152 if (/[a-zA-Z0-9_]/.test(char)) {
153 return char // Keep alphanumeric characters and underscores as is
154 }
155β
156 // Replace special characters with meaningful text equivalents
157 switch (char) {
158 case '.':
159 return 'Dot'
160 case '-':
161 return 'Dash'
162 case '@':
163 return 'At'
164 case '(':
165 return '' // Removed since route groups use parentheses
166 case ')':
167 return '' // Removed since route groups use parentheses
168 case ' ':
169 return '' // Remove spaces
170 default:
171 return `Char${char.charCodeAt(0)}` // For any other characters
172 }
173 }
174β
175 return (
176 removeUnderscores(routePath)
177 ?.replace(/\/\$\//g, '/splat/')
178 .replace(/\$$/g, 'splat')
179 .replace(/\$\{\$\}/g, 'splat')
180 .replace(/\$/g, '')
181 .split(/[/-]/g)
182 .map((d, i) => (i > 0 ? capitalize(d) : d))
183 .join('')
184 .split('')
185 .map(toVariableSafeChar)
186 .join('')
187 // .replace(/([^a-zA-Z0-9]|[.])/gm, '')
188 .replace(/^(\d)/g, 'R$1') ?? ''
189 )
190}
191β
192export function removeUnderscores(s?: string) {
193 return s?.replaceAll(/(^_|_$)/gi, '').replaceAll(/(\/_|_\/)/gi, '/')
194}
195β
196function escapeRegExp(s: string): string {
197 return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
198}
199β
200export function removeLeadingUnderscores(s: string, routeToken: string) {
201 if (!s) return s
202β
203 const hasLeadingUnderscore = routeToken[0] === '_'
204β
205 const routeTokenToExclude = hasLeadingUnderscore
206 ? routeToken.slice(1)
207 : routeToken
208β
209 const escapedRouteToken = escapeRegExp(routeTokenToExclude)
210β
211 const leadingUnderscoreRegex = hasLeadingUnderscore
212 ? new RegExp(`(?<=^|\\/)_(?!${escapedRouteToken})`, 'g')
213 : new RegExp(`(?<=^|\\/)_`, 'g')
214β
215 return s.replaceAll(leadingUnderscoreRegex, '')
216}
217β
218export function removeTrailingUnderscores(s: string, routeToken: string) {
219 if (!s) return s
220β
221 const hasTrailingUnderscore = routeToken.slice(-1) === '_'
222β
223 const routeTokenToExclude = hasTrailingUnderscore
224 ? routeToken.slice(0, -1)
225 : routeToken
226β
227 const escapedRouteToken = escapeRegExp(routeTokenToExclude)
228β
229 const trailingUnderscoreRegex = hasTrailingUnderscore
230 ? new RegExp(`(?<!${escapedRouteToken})_(?=\\/|$)`, 'g')
231 : new RegExp(`_(?=\\/)|_$`, 'g')
232β
233 return s.replaceAll(trailingUnderscoreRegex, '')
234}
235β
236export function capitalize(s: string) {
237 if (typeof s !== 'string') return ''
238 return s.charAt(0).toUpperCase() + s.slice(1)
239}
240β
241export function removeExt(d: string, keepExtension: boolean = false) {
242 return keepExtension ? d : d.substring(0, d.lastIndexOf('.')) || d
243}
244β
245/**
246 * This function writes to a file if the content is different.
247 *
248 * @param filepath The path to the file
249 * @param content Original content
250 * @param incomingContent New content
251 * @param callbacks Callbacks to run before and after writing
252 * @returns Whether the file was written
253 */
254export async function writeIfDifferent(
255 filepath: string,
256 content: string,
257 incomingContent: string,
258 callbacks?: { beforeWrite?: () => void; afterWrite?: () => void },
259): Promise<boolean> {
260 if (content !== incomingContent) {
261 callbacks?.beforeWrite?.()
262 await fsp.writeFile(filepath, incomingContent)
263 callbacks?.afterWrite?.()
264 return true
265 }
266 return false
267}
268β
269/**
270 * This function formats the source code using the default formatter (Prettier).
271 *
272 * @param source The content to format
273 * @param config The configuration object
274 * @returns The formatted content
275 */
276export async function format(
277 source: string,
278 config: {
279 quoteStyle: 'single' | 'double'
280 semicolons: boolean
281 },
282): Promise<string> {
283 const prettierOptions: prettier.Config = {
284 semi: config.semicolons,
285 singleQuote: config.quoteStyle === 'single',
286 parser: 'typescript',
287 }
288 return prettier.format(source, prettierOptions)
289}
290β
291/**
292 * This function resets the regex index to 0 so that it can be reused
293 * without having to create a new regex object or worry about the last
294 * state when using the global flag.
295 *
296 * @param regex The regex object to reset
297 * @returns
298 */
299export function resetRegex(regex: RegExp) {
300 regex.lastIndex = 0
301 return
302}
303β
304/**
305 * This function checks if a file exists.
306 *
307 * @param file The path to the file
308 * @returns Whether the file exists
309 */
310export async function checkFileExists(file: string) {
311 try {
312 await fsp.access(file, fsp.constants.F_OK)
313 return true
314 } catch {
315 return false
316 }
317}
318β
319const possiblyNestedRouteGroupPatternRegex = /\([^/]+\)\/?/g
320export function removeGroups(s: string) {
321 return s.replace(possiblyNestedRouteGroupPatternRegex, '')
322}
323β
324/**
325 * Removes all segments from a given path that start with an underscore ('_').
326 *
327 * @param {string} routePath - The path from which to remove segments. Defaults to '/'.
328 * @returns {string} The path with all underscore-prefixed segments removed.
329 * @example
330 * removeLayoutSegments('/workspace/_auth/foo') // '/workspace/foo'
331 */
332export function removeLayoutSegments(routePath: string = '/'): string {
333 const segments = routePath.split('/')
334 const newSegments = segments.filter((segment) => !segment.startsWith('_'))
335 return newSegments.join('/')
336}
337β
338/**
339 * The `node.path` is used as the `id` in the route definition.
340 * This function checks if the given node has a parent and if so, it determines the correct path for the given node.
341 * @param node - The node to determine the path for.
342 * @returns The correct path for the given node.
343 */
344export function determineNodePath(node: RouteNode) {
345 return (node.path = node.parent
346 ? node.routePath?.replace(node.parent.routePath ?? '', '') || '/'
347 : node.routePath)
348}
349β
350/**
351 * Removes the last segment from a given path. Segments are considered to be separated by a '/'.
352 *
353 * @param {string} routePath - The path from which to remove the last segment. Defaults to '/'.
354 * @returns {string} The path with the last segment removed.
355 * @example
356 * removeLastSegmentFromPath('/workspace/_auth/foo') // '/workspace/_auth'
357 */
358export function removeLastSegmentFromPath(routePath: string = '/'): string {
359 const segments = routePath.split('/')
360 segments.pop() // Remove the last segment
361 return segments.join('/')
362}
363β
364export function hasParentRoute(
365 routes: Array<RouteNode>,
366 node: RouteNode,
367 routePathToCheck: string | undefined,
368 originalRoutePathToCheck?: string,
369): RouteNode | null {
370 const getNonNestedSegments = (routePath: string) => {
371 const regex = /_(?=\/|$)/g
372β
373 return [...routePath.matchAll(regex)]
374 .filter((match) => {
375 const beforeStr = routePath.substring(0, match.index)
376 const openBrackets = (beforeStr.match(/\[/g) || []).length
377 const closeBrackets = (beforeStr.match(/\]/g) || []).length
378 return openBrackets === closeBrackets
379 })
380 .map((match) => routePath.substring(0, match.index + 1))
381 .reverse()
382 }
383β
384 if (!routePathToCheck || routePathToCheck === '/') {
385 return null
386 }
387β
388 const sortedNodes = multiSortBy(routes, [
389 (d) => d.routePath!.length * -1,
390 (d) => d.variableName,
391 ]).filter((d) => d.routePath !== `/${rootPathId}`)
392β
393 const filteredNodes = node._isExperimentalNonNestedRoute
394 ? []
395 : [...sortedNodes]
396β
397 if (node._isExperimentalNonNestedRoute) {
398 const nonNestedSegments = getNonNestedSegments(
399 originalRoutePathToCheck ?? '',
400 )
401β
402 for (const route of sortedNodes) {
403 if (route.routePath === '/') continue
404β
405 if (
406 routePathToCheck.startsWith(`${route.routePath}/`) &&
407 route._isExperimentalNonNestedRoute &&
408 route.routePath !== routePathToCheck
409 ) {
410 return route
411 }
412β
413 if (
414 nonNestedSegments.find((seg) => seg === `${route.routePath}_`) ||
415 !(
416 route._fsRouteType === 'pathless_layout' ||
417 route._fsRouteType === 'layout' ||
418 route._fsRouteType === '__root'
419 )
420 ) {
421 continue
422 }
423β
424 filteredNodes.push(route)
425 }
426 }
427β
428 for (const route of filteredNodes) {
429 if (route.routePath === '/') continue
430β
431 if (
432 routePathToCheck.startsWith(`${route.routePath}/`) &&
433 route.routePath !== routePathToCheck
434 ) {
435 return route
436 }
437 }
438β
439 const segments = routePathToCheck.split('/')
440 segments.pop() // Remove the last segment
441 const parentRoutePath = segments.join('/')
442β
443 return hasParentRoute(routes, node, parentRoutePath, originalRoutePathToCheck)
444}
445β
446/**
447 * Gets the final variable name for a route
448 */
449export const getResolvedRouteNodeVariableName = (
450 routeNode: RouteNode,
451): string => {
452 return routeNode.children?.length
453 ? `${routeNode.variableName}RouteWithChildren`
454 : `${routeNode.variableName}Route`
455}
456β
457/**
458 * Checks if a given RouteNode is valid for augmenting it with typing based on conditions.
459 * Also asserts that the RouteNode is defined.
460 *
461 * @param routeNode - The RouteNode to check.
462 * @returns A boolean indicating whether the RouteNode is defined.
463 */
464export function isRouteNodeValidForAugmentation(
465 routeNode?: RouteNode,
466): routeNode is RouteNode {
467 if (!routeNode || routeNode.isVirtual) {
468 return false
469 }
470 return true
471}
472β
473/**
474 * Infers the path for use by TS
475 */
476export const inferPath = (routeNode: RouteNode): string => {
477 return routeNode.cleanedPath === '/'
478 ? routeNode.cleanedPath
479 : (routeNode.cleanedPath?.replace(/\/$/, '') ?? '')
480}
481β
482/**
483 * Infers the full path for use by TS
484 */
485export const inferFullPath = (
486 routeNode: RouteNode,
487 config?: Pick<Config, 'experimental' | 'routeToken'>,
488): string => {
489 // with new nonNestedPaths feature we can be sure any remaining trailing underscores are escaped and should remain
490 // TODO with new major we can remove check and only remove leading underscores
491 const fullPath = removeGroups(
492 (config?.experimental?.nonNestedRoutes
493 ? removeLayoutSegments(routeNode.routePath)
494 : removeUnderscores(removeLayoutSegments(routeNode.routePath))) ?? '',
495 )
496β
497 return routeNode.cleanedPath === '/' ? fullPath : fullPath.replace(/\/$/, '')
498}
499β
500/**
501 * Creates a map from fullPath to routeNode
502 */
503export const createRouteNodesByFullPath = (
504 routeNodes: Array<RouteNode>,
505 config?: Pick<Config, 'experimental' | 'routeToken'>,
506): Map<string, RouteNode> => {
507 return new Map(
508 routeNodes.map((routeNode) => [
509 inferFullPath(routeNode, config),
510 routeNode,
511 ]),
512 )
513}
514β
515/**
516 * Create a map from 'to' to a routeNode
517 */
518export const createRouteNodesByTo = (
519 routeNodes: Array<RouteNode>,
520 config?: Pick<Config, 'experimental' | 'routeToken'>,
521): Map<string, RouteNode> => {
522 return new Map(
523 dedupeBranchesAndIndexRoutes(routeNodes).map((routeNode) => [
524 inferTo(routeNode, config),
525 routeNode,
526 ]),
527 )
528}
529β
530/**
531 * Create a map from 'id' to a routeNode
532 */
533export const createRouteNodesById = (
534 routeNodes: Array<RouteNode>,
535): Map<string, RouteNode> => {
536 return new Map(
537 routeNodes.map((routeNode) => {
538 const id = routeNode.routePath ?? ''
539 return [id, routeNode]
540 }),
541 )
542}
543β
544/**
545 * Infers to path
546 */
547export const inferTo = (
548 routeNode: RouteNode,
549 config?: Pick<Config, 'experimental' | 'routeToken'>,
550): string => {
551 const fullPath = inferFullPath(routeNode, config)
552β
553 if (fullPath === '/') return fullPath
554β
555 return fullPath.replace(/\/$/, '')
556}
557β
558/**
559 * Dedupes branches and index routes
560 */
561export const dedupeBranchesAndIndexRoutes = (
562 routes: Array<RouteNode>,
563): Array<RouteNode> => {
564 return routes.filter((route) => {
565 if (route.children?.find((child) => child.cleanedPath === '/')) return false
566 return true
567 })
568}
569β
570function checkUnique<TElement>(routes: Array<TElement>, key: keyof TElement) {
571 // Check no two routes have the same `key`
572 // if they do, throw an error with the conflicting filePaths
573 const keys = routes.map((d) => d[key])
574 const uniqueKeys = new Set(keys)
575 if (keys.length !== uniqueKeys.size) {
576 const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i)
577 const conflictingFiles = routes.filter((d) =>
578 duplicateKeys.includes(d[key]),
579 )
580 return conflictingFiles
581 }
582 return undefined
583}
584β
585export function checkRouteFullPathUniqueness(
586 _routes: Array<RouteNode>,
587 config: Config,
588) {
589 const routes = _routes.map((d) => {
590 const inferredFullPath = inferFullPath(d, config)
591 return { ...d, inferredFullPath }
592 })
593β
594 const conflictingFiles = checkUnique(routes, 'inferredFullPath')
595β
596 if (conflictingFiles !== undefined) {
597 const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? 's' : ''}: ${conflictingFiles
598 .map((p) => `"${p.inferredFullPath}"`)
599 .join(', ')}.
600Please ensure each Route has a unique full path.
601Conflicting files: \n ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join('\n ')}\n`
602 throw new Error(errorMessage)
603 }
604}
605β
606export function buildRouteTreeConfig(
607 nodes: Array<RouteNode>,
608 disableTypes: boolean,
609 depth = 1,
610): Array<string> {
611 const children = nodes.map((node) => {
612 if (node._fsRouteType === '__root') {
613 return
614 }
615β
616 if (node._fsRouteType === 'pathless_layout' && !node.children?.length) {
617 return
618 }
619β
620 const route = `${node.variableName}`
621β
622 if (node.children?.length) {
623 const childConfigs = buildRouteTreeConfig(
624 node.children,
625 disableTypes,
626 depth + 1,
627 )
628β
629 const childrenDeclaration = disableTypes
630 ? ''
631 : `interface ${route}RouteChildren {
632 ${node.children
633 .map(
634 (child) =>
635 `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`,
636 )
637 .join(',')}
638}`
639β
640 const children = `const ${route}RouteChildren${disableTypes ? '' : `: ${route}RouteChildren`} = {
641 ${node.children
642 .map(
643 (child) =>
644 `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,
645 )
646 .join(',')}
647}`
648β
649 const routeWithChildren = `const ${route}RouteWithChildren = ${route}Route._addFileChildren(${route}RouteChildren)`
650β
651 return [
652 childConfigs.join('\n'),
653 childrenDeclaration,
654 children,
655 routeWithChildren,
656 ].join('\n\n')
657 }
658β
659 return undefined
660 })
661β
662 return children.filter((x) => x !== undefined)
663}
664β
665export function buildImportString(
666 importDeclaration: ImportDeclaration,
667): string {
668 const { source, specifiers, importKind } = importDeclaration
669 return specifiers.length
670 ? `import ${importKind === 'type' ? 'type ' : ''}{ ${specifiers.map((s) => (s.local ? `${s.imported} as ${s.local}` : s.imported)).join(', ')} } from '${source}'`
671 : ''
672}
673β
674export function lowerCaseFirstChar(value: string) {
675 if (!value[0]) {
676 return value
677 }
678β
679 return value[0].toLowerCase() + value.slice(1)
680}
681β
682export function mergeImportDeclarations(
683 imports: Array<ImportDeclaration>,
684): Array<ImportDeclaration> {
685 const merged: Record<string, ImportDeclaration> = {}
686β
687 for (const imp of imports) {
688 const key = `${imp.source}-${imp.importKind}`
689 if (!merged[key]) {
690 merged[key] = { ...imp, specifiers: [] }
691 }
692 for (const specifier of imp.specifiers) {
693 // check if the specifier already exists in the merged import
694 if (
695 !merged[key].specifiers.some(
696 (existing) =>
697 existing.imported === specifier.imported &&
698 existing.local === specifier.local,
699 )
700 ) {
701 merged[key].specifiers.push(specifier)
702 }
703 }
704 }
705β
706 return Object.values(merged)
707}
708β
709export const findParent = (node: RouteNode | undefined): string => {
710 if (!node) {
711 return `rootRouteImport`
712 }
713 if (node.parent) {
714 if (node.isVirtualParentRequired) {
715 return `${node.parent.variableName}Route`
716 } else {
717 return `${node.parent.variableName}Route`
718 }
719 }
720 return findParent(node.parent)
721}
722β
723export function buildFileRoutesByPathInterface(opts: {
724 routeNodes: Array<RouteNode>
725 module: string
726 interfaceName: string
727 config?: Pick<Config, 'experimental' | 'routeToken'>
728}): string {
729 return `declare module '${opts.module}' {
730 interface ${opts.interfaceName} {
731 ${opts.routeNodes
732 .map((routeNode) => {
733 const filePathId = routeNode.routePath
734 const preloaderRoute = `typeof ${routeNode.variableName}RouteImport`
735β
736 const parent = findParent(routeNode)
737β
738 return `'${filePathId}': {
739 id: '${filePathId}'
740 path: '${inferPath(routeNode)}'
741 fullPath: '${inferFullPath(routeNode, opts.config)}'
742 preLoaderRoute: ${preloaderRoute}
743 parentRoute: typeof ${parent}
744 }`
745 })
746 .join('\n')}
747 }
748}`
749}
750β
751export function getImportPath(
752 node: RouteNode,
753 config: Config,
754 generatedRouteTreePath: string,
755): string {
756 return replaceBackslash(
757 removeExt(
758 path.relative(
759 path.dirname(generatedRouteTreePath),
760 path.resolve(config.routesDirectory, node.filePath),
761 ),
762 config.addExtensions,
763 ),
764 )
765}
766β
767export function getImportForRouteNode(
768 node: RouteNode,
769 config: Config,
770 generatedRouteTreePath: string,
771 root: string,
772): ImportDeclaration {
773 let source = ''
774 if (config.importRoutesUsingAbsolutePaths) {
775 source = replaceBackslash(
776 removeExt(
777 path.resolve(root, config.routesDirectory, node.filePath),
778 config.addExtensions,
779 ),
780 )
781 } else {
782 source = `./${getImportPath(node, config, generatedRouteTreePath)}`
783 }
784 return {
785 source,
786 specifiers: [
787 {
788 imported: 'Route',
789 local: `${node.variableName}RouteImport`,
790 },
791 ],
792 } satisfies ImportDeclaration
793}
794β
795/**
796 * Used to validate if a route is a pathless layout route
797 * @param normalizedRoutePath Normalized route path, i.e `/foo/_layout/route.tsx` and `/foo._layout.route.tsx` to `/foo/_layout/route`
798 * @param config The `router-generator` configuration object
799 * @returns Boolean indicating if the route is a pathless layout route
800 */
801export function isValidNonNestedRoute(
802 normalizedRoutePath: string,
803 config?: Pick<Config, 'experimental' | 'routeToken' | 'indexToken'>,
804): boolean {
805 if (!config?.experimental?.nonNestedRoutes) {
806 return false
807 }
808β
809 const segments = normalizedRoutePath.split('/').filter(Boolean)
810β
811 if (segments.length === 0) {
812 return false
813 }
814β
815 const lastRouteSegment = segments[segments.length - 1]!
816β
817 // If segment === __root, then exit as false
818 if (lastRouteSegment === rootPathId) {
819 return false
820 }
821β
822 if (
823 lastRouteSegment !== config.indexToken &&
824 lastRouteSegment !== config.routeToken &&
825 lastRouteSegment.endsWith('_')
826 ) {
827 return true
828 }
829β
830 for (const segment of segments.slice(0, -1).reverse()) {
831 if (segment === config.routeToken) {
832 return false
833 }
834β
835 if (segment.endsWith('_')) {
836 return true
837 }
838 }
839β
840 return false
841}