// I copied this file from: // https://github.com/remix-run/v1-compat-utils/blob/main/packages/v1-route-convention/src/lib.ts import fs from "node:fs"; import path from "node:path"; import { DefineRoutesFunction } from "@react-router/remix-config-routes-adapter"; import { RouteManifest } from "node_modules/@react-router/remix-config-routes-adapter/dist/manifest"; let paramPrefixChar = "$" as const; let escapeStart = "[" as const; let escapeEnd = "]" as const; let optionalStart = "(" as const; let optionalEnd = ")" as const; let routeModuleExts = [".js", ".jsx", ".ts", ".tsx", ".md", ".mdx"]; function isRouteModuleFile(filename: string): boolean { return routeModuleExts.includes(path.extname(filename)); } function matchesIgnoredFilePattern(file: string, pattern: string): boolean { const normalizedFile = file.split(path.sep).join("/"); const normalizedPattern = pattern.split(path.sep).join("/"); if (normalizedPattern === "**/.*") { return normalizedFile.split("/").some((segment) => segment.startsWith(".")); } if (normalizedPattern.startsWith("**/*")) { return normalizedFile.endsWith(normalizedPattern.slice("**/*".length)); } if (normalizedPattern.endsWith("/**")) { const directory = normalizedPattern.slice(0, -"/**".length); return normalizedFile === directory || normalizedFile.startsWith(`${directory}/`); } return normalizedFile === normalizedPattern; } export type CreateRoutesFromFoldersOptions = { /** * The directory where your app lives. Defaults to `app`. * @default "app" */ appDirectory?: string; /** * A list of glob patterns to ignore when looking for route modules. * Defaults to `[]`. */ ignoredFilePatterns?: string[]; /** * The directory where your routes live. Defaults to `routes`. * This is relative to `appDirectory`. * @default "routes" */ routesDirectory?: string; }; /** * Defines routes using the filesystem convention in `apps/web/app/routes`. The rules are: * * - Route paths are derived from the file path. A `.` in the filename indicates * a `/` in the URL (a "nested" URL, but no route nesting). A `$` in the * filename indicates a dynamic URL segment. * - Subdirectories are used for nested routes. * * For example, a file named `apps/web/app/routes/gists/$username.tsx` creates a route * with a path of `gists/:username`. */ export function createRoutesFromFolders(defineRoutes: DefineRoutesFunction, options: CreateRoutesFromFoldersOptions = {}): RouteManifest { let { appDirectory = "app", ignoredFilePatterns = [], routesDirectory = "routes" } = options; let appRoutesDirectory = path.join(appDirectory, routesDirectory); let files: { [routeId: string]: string } = {}; // First, find all route modules in apps/web/app/routes visitFiles(appRoutesDirectory, (file) => { if (ignoredFilePatterns.length > 0 && ignoredFilePatterns.some((pattern) => matchesIgnoredFilePattern(file, pattern))) { return; } if (isRouteModuleFile(file)) { let relativePath = path.join(routesDirectory, file); let routeId = createRouteId(relativePath); files[routeId] = relativePath; return; } throw new Error(`Invalid route module file: ${path.join(appRoutesDirectory, file)}`); }); let routeIds = Object.keys(files).sort(byLongestFirst); let parentRouteIds = getParentRouteIds(routeIds); let uniqueRoutes = new Map(); // Then, recurse through all routes using the public defineRoutes() API function defineNestedRoutes(defineRoute: DefineRouteFunction, parentId?: string): void { let childRouteIds = routeIds.filter((id) => { if (!parentId && id === `${routesDirectory}/admin`) { return false; } return parentRouteIds[id] === parentId; }); for (let routeId of childRouteIds) { let routePath: string | undefined = createRoutePath(routeId.slice((parentId || routesDirectory).length + 1)); // Index when the parent-relative path resolves to nothing and the final // segment is the index marker. Supports the v1 `index` filename and the // v2 flat `_index` filename. A flat `foo._index` (relative path "foo") is // NOT an index — it is the leaf route at `/foo`. let isIndexRoute = routePath === undefined && /(?:^|[/.])_?index$/.test(routeId); let fullPath = createRoutePath(routeId.slice(routesDirectory.length + 1)); fullPath = promoteTenantAppRoutePath(fullPath); routePath = promoteTenantAppRoutePath(routePath); let uniqueRouteId = (fullPath || "") + (isIndexRoute ? "?index" : ""); let isPathlessLayoutRoute = routeId.split("/").pop()?.startsWith("__") === true; /** * We do not try to detect path collisions for pathless layout route * files because, by definition, they create the potential for route * collisions _at that level in the tree_. * * Consider example where a user may want multiple pathless layout routes * for different subfolders * * routes/ * account.tsx * account/ * __public/ * login.tsx * perks.tsx * __private/ * orders.tsx * profile.tsx * __public.tsx * __private.tsx * * In order to support both a public and private layout for `/account/*` * URLs, we are creating a mutually exclusive set of URLs beneath 2 * separate pathless layout routes. In this case, the route paths for * both account/__public.tsx and account/__private.tsx is the same * (/account), but we're again not expecting to match at that level. * * By only ignoring this check when the final portion of the filename is * pathless, we will still detect path collisions such as: * * routes/parent/__pathless/foo.tsx * routes/parent/__pathless2/foo.tsx * * and * * routes/parent/__pathless/index.tsx * routes/parent/__pathless2/index.tsx */ if (uniqueRouteId && !isPathlessLayoutRoute) { if (uniqueRoutes.has(uniqueRouteId)) { throw new Error( `Path ${JSON.stringify(fullPath || "/")} defined by route ` + `${JSON.stringify(routeId)} conflicts with route ` + `${JSON.stringify(uniqueRoutes.get(uniqueRouteId))}` ); } else { uniqueRoutes.set(uniqueRouteId, routeId); } } if (isIndexRoute) { let invalidChildRoutes = routeIds.filter((id) => parentRouteIds[id] === routeId); if (invalidChildRoutes.length > 0) { throw new Error(`Child routes are not allowed in index routes. Please remove child routes of ${routeId}`); } defineRoute(routePath, files[routeId], { index: true, id: routeId }); } else { defineRoute(routePath, files[routeId], { id: routeId }, () => { defineNestedRoutes(defineRoute, routeId); }); } } } function defineAdminHostRoutes(defineRoute: DefineRouteFunction): void { const adminRouteId = `${routesDirectory}/admin`; if (!files[adminRouteId]) { return; } defineRoute(undefined, files[adminRouteId], { id: getAdminHostRouteId(adminRouteId) }, () => { defineAdminHostChildRoutes(defineRoute, adminRouteId); }); } function defineAdminHostChildRoutes(defineRoute: DefineRouteFunction, parentId: string): void { let childRouteIds = routeIds.filter((id) => { return parentRouteIds[id] === parentId && shouldCreateAdminHostRoute(id); }); for (let routeId of childRouteIds) { const routePath = createAdminHostRoutePath(routeId, parentId); // Index when the parent-relative path resolves to nothing and the final // segment is the index marker. Supports the v1 `index` filename and the // v2 flat `_index` filename. A flat `foo._index` (relative path "foo") is // NOT an index — it is the leaf route at `/foo`. let isIndexRoute = routePath === undefined && /(?:^|[/.])_?index$/.test(routeId); if (isIndexRoute) { defineRoute(routePath, files[routeId], { index: true, id: getAdminHostRouteId(routeId) }); } else { defineRoute(routePath, files[routeId], { id: getAdminHostRouteId(routeId) }, () => { defineAdminHostChildRoutes(defineRoute, routeId); }); } } } return defineRoutes((defineRoute) => { defineAdminHostRoutes(defineRoute); defineNestedRoutes(defineRoute); }); } // Mirrors Remix v1 route-id parsing; covered by v1-route-convention tests so // route migration changes fail before runtime. export function createRoutePath(partialRouteId: string): string | undefined { let result = ""; let rawSegmentBuffer = ""; let inEscapeSequence = 0; let inOptionalSegment = 0; let optionalSegmentIndex = null; let skipSegment = false; for (let i = 0; i < partialRouteId.length; i++) { let char = partialRouteId.charAt(i); let prevChar = i > 0 ? partialRouteId.charAt(i - 1) : undefined; let nextChar = i < partialRouteId.length - 1 ? partialRouteId.charAt(i + 1) : undefined; function isNewEscapeSequence() { return !inEscapeSequence && char === escapeStart && prevChar !== escapeStart; } function isCloseEscapeSequence() { return inEscapeSequence && char === escapeEnd && nextChar !== escapeEnd; } function isStartOfLayoutSegment() { return char === "_" && nextChar === "_" && !rawSegmentBuffer; } function isNewOptionalSegment() { return ( char === optionalStart && prevChar !== optionalStart && (isSegmentSeparator(prevChar) || prevChar === undefined) && !inOptionalSegment && !inEscapeSequence ); } function isCloseOptionalSegment() { return ( char === optionalEnd && nextChar !== optionalEnd && (isSegmentSeparator(nextChar) || nextChar === undefined) && inOptionalSegment && !inEscapeSequence ); } if (skipSegment) { if (isSegmentSeparator(char)) { skipSegment = false; } continue; } if (isNewEscapeSequence()) { inEscapeSequence++; continue; } if (isCloseEscapeSequence()) { inEscapeSequence--; continue; } if (isNewOptionalSegment()) { inOptionalSegment++; optionalSegmentIndex = result.length; result += optionalStart; continue; } if (isCloseOptionalSegment()) { if (optionalSegmentIndex !== null) { result = result.slice(0, optionalSegmentIndex) + result.slice(optionalSegmentIndex + 1); } optionalSegmentIndex = null; inOptionalSegment--; result += "?"; continue; } if (inEscapeSequence) { result += char; continue; } if (isSegmentSeparator(char)) { if ((rawSegmentBuffer === "index" || rawSegmentBuffer === "_index") && result.endsWith("index")) { result = result.replace(/\/?_?index$/, ""); } else { result += "/"; } rawSegmentBuffer = ""; inOptionalSegment = 0; optionalSegmentIndex = null; continue; } if (isStartOfLayoutSegment()) { skipSegment = true; continue; } rawSegmentBuffer += char; if (char === paramPrefixChar) { if (nextChar === optionalEnd) { throw new Error(`Invalid route path: ${partialRouteId}. Splat route $ is already optional`); } result += typeof nextChar === "undefined" ? "*" : ":"; continue; } result += char; } if ((rawSegmentBuffer === "index" || rawSegmentBuffer === "_index") && result.endsWith("index")) { result = result.replace(/\/?_?index$/, ""); } else { result = result.replace(/\/$/, ""); } if ((rawSegmentBuffer === "index" || rawSegmentBuffer === "_index") && result.endsWith("index?")) { throw new Error(`Invalid route path: ${partialRouteId}. Make index route optional by using (index)`); } return result || undefined; } function isSegmentSeparator(checkChar: string | undefined) { if (!checkChar) return false; return ["/", ".", path.win32.sep].includes(checkChar); } function promoteTenantAppRoutePath(routePath: string | undefined): string | undefined { if (routePath === "app/:tenant") { return ":tenant"; } if (routePath?.startsWith("app/:tenant/")) { return routePath.replace(/^app\/:tenant\//, ":tenant/"); } return routePath; } function getAdminHostRouteId(routeId: string): string { return `${routeId}.__host`; } function shouldCreateAdminHostRoute(routeId: string): boolean { if (!routeId.startsWith("routes/admin/")) { return false; } const canonicalPath = createRoutePath(routeId.slice("routes/admin/".length)); if (!canonicalPath) { return true; } return !["404", "dashboard", "mfa-challenge"].includes(canonicalPath); } function createAdminHostRoutePath(routeId: string, parentId: string): string | undefined { if (routeId === "routes/admin/settings") { return undefined; } if (parentId === "routes/admin/settings") { return createRoutePath(routeId.slice("routes/admin/".length)); } return createRoutePath(routeId.slice(parentId.length + 1)); } function addPromotedTenantDescendantRouteIds(routeIds: string[]): string[] { const routeIdSet = new Set(routeIds); for (const routeId of routeIds) { if (!routeId.startsWith("routes/app.$tenant/")) { continue; } const segments = routeId.split("/"); for (let index = segments.length - 1; index > 1; index--) { routeIdSet.add(segments.slice(0, index).join("/")); } } return [...routeIdSet].sort(byLongestFirst); } function getParentRouteIds(routeIds: string[]): Record { return routeIds.reduce>( (parentRouteIds, childRouteId) => ({ ...parentRouteIds, [childRouteId]: routeIds.find((id) => childRouteId.startsWith(`${id}/`)), }), {} ); } function byLongestFirst(a: string, b: string): number { return b.length - a.length; } function visitFiles(dir: string, visitor: (file: string) => void, baseDir = dir): void { for (let filename of fs.readdirSync(dir)) { let file = path.resolve(dir, filename); let stat = fs.lstatSync(file); if (stat.isDirectory()) { visitFiles(file, visitor, baseDir); } else if (stat.isFile()) { visitor(path.relative(baseDir, file)); } } } /* eslint no-loop-func: "off", */ function createRouteId(file: string) { return normalizeSlashes(stripFileExtension(file)); } function normalizeSlashes(file: string) { return file.split(path.win32.sep).join("/"); } function stripFileExtension(file: string) { return file.replace(/\.[a-z0-9]+$/i, ""); } interface DefineRouteOptions { /** * Should be `true` if the route `path` is case-sensitive. Defaults to * `false`. */ caseSensitive?: boolean; /** * Should be `true` if this is an index route that does not allow child routes. */ index?: boolean; /** * An optional unique id string for this route. Use this if you need to aggregate * two or more routes with the same route file. */ id?: string; } interface DefineRouteChildren { (): void; } interface DefineRouteFunction { ( /** * The path this route uses to match the URL pathname. */ path: string | undefined, /** * The path to the file that exports the React component rendered by this * route as its default export, relative to the `app` directory. */ file: string, /** * Options for defining routes, or a function for defining child routes. */ optionsOrChildren?: DefineRouteOptions | DefineRouteChildren, /** * A function for defining child routes. */ children?: DefineRouteChildren ): void; }