-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathflat-routes.ts
343 lines (298 loc) · 9.58 KB
/
flat-routes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import path from "node:path";
import fg from "fast-glob";
import type { ConfigRoute, DefineRouteFunction, RouteManifest } from "./routes";
import { createRouteId, defineRoutes } from "./routes";
import {
escapeEnd,
escapeStart,
isSegmentSeparator,
optionalEnd,
optionalStart,
paramPrefixChar,
routeModuleExts,
} from "./routesConvention";
export function flatRoutes(
appDirectory: string,
ignoredFilePatterns?: string[]
): RouteManifest {
let extensions = routeModuleExts.join(",");
let routePaths = fg.sync(`**/*{${extensions}}`, {
absolute: true,
cwd: path.join(appDirectory, "routes"),
ignore: ignoredFilePatterns,
});
// fast-glob will return posix paths even on windows
// convert posix to os specific paths
let routePathsForOS = routePaths.map((routePath) => {
return path.join(...routePath.split(path.posix.sep));
});
return flatRoutesUniversal(appDirectory, routePathsForOS);
}
interface RouteInfo extends ConfigRoute {
name: string;
segments: string[];
}
/**
* Create route configs from a list of routes using the flat routes conventions.
* @param {string} appDirectory - The absolute root directory the routes were looked up from.
* @param {string[]} routePaths - The absolute route paths.
* @param {string} [prefix=routes] - The prefix to strip off of the routes.
*/
export function flatRoutesUniversal(
appDirectory: string,
routePaths: string[],
prefix: string = "routes"
): RouteManifest {
let routeMap = getRouteMap(appDirectory, routePaths, prefix);
let uniqueRoutes = new Map<string, string>();
function defineNestedRoutes(
defineRoute: DefineRouteFunction,
parentId?: string
): void {
let childRoutes = Array.from(routeMap.values()).filter(
(routeInfo) => routeInfo.parentId === parentId
);
let parentRoute = parentId ? routeMap.get(parentId) : undefined;
let parentRoutePath = parentRoute?.path ?? "/";
for (let childRoute of childRoutes) {
let routePath = childRoute.path?.slice(parentRoutePath.length) ?? "";
// remove leading slash
routePath = routePath.replace(/^\//, "");
let index = childRoute.index;
let fullPath = childRoute.path;
let uniqueRouteId = (fullPath || "") + (index ? "?index" : "");
if (uniqueRouteId) {
let conflict = uniqueRoutes.get(uniqueRouteId);
if (conflict) {
throw new Error(
`Path ${JSON.stringify(fullPath)} defined by route ${JSON.stringify(
childRoute.id
)} conflicts with route ${JSON.stringify(conflict)}`
);
}
uniqueRoutes.set(uniqueRouteId, childRoute.id);
}
if (index) {
let invalidChildRoutes = Object.values(routeMap).filter(
(routeInfo) => routeInfo.parentId === childRoute.id
);
if (invalidChildRoutes.length > 0) {
throw new Error(
`Child routes are not allowed in index routes. Please remove child routes of ${childRoute.id}`
);
}
defineRoute(routePath, routeMap.get(childRoute.id!)!.file, {
index: true,
});
} else {
defineRoute(routePath, routeMap.get(childRoute.id!)!.file, () => {
defineNestedRoutes(defineRoute, childRoute.id);
});
}
}
}
let routes = defineRoutes(defineNestedRoutes);
return routes;
}
export function isIndexRoute(routeId: string) {
let isFlatFile = !routeId.includes(path.posix.sep);
return isFlatFile ? routeId.endsWith("_index") : /\/index$/.test(routeId);
}
type State =
| // normal path segment normal character concatenation until we hit a special character or the end of the segment (i.e. `/`, `.`, '\')
"NORMAL"
// we hit a `[` and are now in an escape sequence until we hit a `]` - take characters literally and skip isSegmentSeparator checks
| "ESCAPE"
// we hit a `(` and are now in an optional segment until we hit a `)` or an escape sequence
| "OPTIONAL"
// we previously were in a optional segment and hit a `[` and are now in an escape sequence until we hit a `]` - take characters literally and skip isSegmentSeparator checks - afterwards go back to OPTIONAL state
| "OPTIONAL_ESCAPE";
export function getRouteSegments(routeId: string) {
let routeSegments: string[] = [];
let index = 0;
let routeSegment = "";
let rawRouteSegment = "";
let state: State = "NORMAL";
let pushRouteSegment = (routeSegment: string) => {
if (!routeSegment) return;
let notSupportedInRR = (segment: string, char: string) => {
throw new Error(
`Route segment "${segment}" for "${routeId}" cannot contain "${char}".\n` +
`If this is something you need, upvote this proposal for React Router https://github.com/remix-run/react-router/discussions/9822.`
);
};
if (rawRouteSegment.includes("*")) {
return notSupportedInRR(rawRouteSegment, "*");
}
if (rawRouteSegment.includes(":")) {
return notSupportedInRR(rawRouteSegment, ":");
}
if (rawRouteSegment.includes("/")) {
return notSupportedInRR(routeSegment, "/");
}
routeSegments.push(routeSegment);
};
while (index < routeId.length) {
let char = routeId[index];
index++; //advance to next char
switch (state) {
case "NORMAL": {
if (isSegmentSeparator(char)) {
pushRouteSegment(routeSegment);
routeSegment = "";
rawRouteSegment = "";
state = "NORMAL";
break;
}
if (char === escapeStart) {
state = "ESCAPE";
break;
}
if (char === optionalStart) {
state = "OPTIONAL";
break;
}
if (!routeSegment && char == paramPrefixChar) {
if (index === routeId.length) {
routeSegment += "*";
rawRouteSegment += char;
} else {
routeSegment += ":";
rawRouteSegment += char;
}
break;
}
routeSegment += char;
rawRouteSegment += char;
break;
}
case "ESCAPE": {
if (char === escapeEnd) {
state = "NORMAL";
break;
}
routeSegment += char;
rawRouteSegment += char;
break;
}
case "OPTIONAL": {
if (char === optionalEnd) {
routeSegment += "?";
rawRouteSegment += "?";
state = "NORMAL";
break;
}
if (char === escapeStart) {
state = "OPTIONAL_ESCAPE";
break;
}
if (!routeSegment && char === paramPrefixChar) {
if (index === routeId.length) {
routeSegment += "*";
rawRouteSegment += char;
} else {
routeSegment += ":";
rawRouteSegment += char;
}
break;
}
routeSegment += char;
rawRouteSegment += char;
break;
}
case "OPTIONAL_ESCAPE": {
if (char === escapeEnd) {
state = "OPTIONAL";
break;
}
routeSegment += char;
rawRouteSegment += char;
break;
}
}
}
// process remaining segment
pushRouteSegment(routeSegment);
return routeSegments;
}
function findParentRouteId(
routeInfo: RouteInfo,
nameMap: Map<string, RouteInfo>
) {
let parentName = routeInfo.segments.slice(0, -1).join("/");
while (parentName) {
let parentRoute = nameMap.get(parentName);
if (parentRoute) return parentRoute.id;
parentName = parentName.substring(0, parentName.lastIndexOf("/"));
}
return undefined;
}
function getRouteInfo(
appDirectory: string,
routeDirectory: string,
filePath: string
): RouteInfo {
let filePathWithoutApp = filePath.slice(appDirectory.length + 1);
let routeId = createRouteId(filePathWithoutApp);
let routeIdWithoutRoutes = routeId.slice(routeDirectory.length + 1);
let index = isIndexRoute(routeIdWithoutRoutes);
let routeSegments = getRouteSegments(routeIdWithoutRoutes);
let routePath = createRoutePath(routeSegments, index);
return {
id: routeIdWithoutRoutes,
path: routePath,
file: filePathWithoutApp,
name: routeSegments.join("/"),
segments: routeSegments,
index,
};
}
export function createRoutePath(routeSegments: string[], isIndex: boolean) {
let result = "";
if (isIndex) {
routeSegments = routeSegments.slice(0, -1);
}
for (let segment of routeSegments) {
// skip pathless layout segments
if (segment.startsWith("_")) {
continue;
}
// remove trailing slash
if (segment.endsWith("_")) {
segment = segment.slice(0, -1);
}
result += `/${segment}`;
}
return result || undefined;
}
function getRouteMap(
appDirectory: string,
routePaths: string[],
prefix: string = "routes"
) {
let routeMap = new Map<string, RouteInfo>();
let nameMap = new Map<string, RouteInfo>();
for (let routePath of routePaths) {
let routesDirectory = path.join(appDirectory, prefix);
let pathWithoutAppRoutes = routePath.slice(routesDirectory.length + 1);
if (isRouteModuleFile(pathWithoutAppRoutes)) {
let routeInfo = getRouteInfo(appDirectory, prefix, routePath);
routeMap.set(routeInfo.id, routeInfo);
nameMap.set(routeInfo.name, routeInfo);
}
}
// update parentIds for all routes
for (let routeInfo of routeMap.values()) {
let parentId = findParentRouteId(routeInfo, nameMap);
routeInfo.parentId = parentId;
}
return routeMap;
}
function isRouteModuleFile(filepath: string) {
// flat files only need correct extension
let isFlatFile = !filepath.includes(path.sep);
if (isFlatFile) {
return routeModuleExts.includes(path.extname(filepath));
}
return isIndexRoute(createRouteId(filepath));
}