-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathgenerateFilePathToRouteNamesMap.ts
55 lines (50 loc) · 1.49 KB
/
generateFilePathToRouteNamesMap.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
import { relative } from 'node:path'
import type { TreeNode } from '../core/tree'
export function generateFilePathToRouteNamesMap(
node: TreeNode,
options: { root: string }
): string {
if (node.isRoot()) {
return `export interface FilePathToRouteNamesMap {
${node
.getSortedChildren()
.map((child) => generateFilePathToRouteNamesMap(child, options))
.join('')}}`
}
function getRelativeFilePath(file: string) {
return relative(options.root, file)
}
const routeNamesUnion = recursiveGetRouteNames(node)
.map((name) => `'${name}'`)
.join(' | ')
return (
// if the node has a filePath, it's a component, it has a routeName and it should be
// referenced in the FilePathToRouteNamesMap otherwise it should be skipped
// TODO: can we use `RouteNameWithChildren` from https://github.com/vuejs/router/pull/2475 here if merged?
Array.from(
node.value.components
.values()
.map(
(file) => ` '${getRelativeFilePath(file)}': ${routeNamesUnion},\n`
)
).join('') +
(node.children.size > 0
? node
.getSortedChildren()
.map((child) => generateFilePathToRouteNamesMap(child, options))
.join('\n')
: '')
)
}
/**
* Gets the name of the provided node and all of its children
*/
function recursiveGetRouteNames(node: TreeNode): TreeNode['name'][] {
return [
node.name,
...node
.getSortedChildren()
.values()
.map((child) => recursiveGetRouteNames(child)),
].flat()
}