-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
81 lines (63 loc) · 2.13 KB
/
index.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
type ContextT = ReturnType<typeof require.context>
type RouterTreeT = {
[key: string]: RouterTreeT
[routeRecordKey]: import('vue-router').RouteRecordRaw
}
const routeRecordKey: unique symbol = Symbol('RouteRecord')
export const buildPages = (
weakContext: ContextT,
persistentContext: ContextT,
{
prependPath = '/',
getName = (path) => weakContext.resolve(path),
}: {
prependPath?: string
getName?(
path: ReturnType<(typeof weakContext)['keys']>[number]
): import('vue-router').RouteRecordName
} = {}
) => {
const routerTree = {} as RouterTreeT
const keys = weakContext.keys()
keys.forEach((it) => {
const path = it.slice(2).split('.').slice(0, -1).join('').split('/')
deepSet(routerTree, [...path, routeRecordKey], {
name: getName(it),
component: () => persistentContext(it),
})
})
const routes = traverseTree(routerTree, prependPath)
// vue router is kinda weird forcing routes to start with '/'
return routes.map((it) => Object.assign(it, { path: '/' + it.path }))
}
function traverseTree(tree: RouterTreeT, path: string) {
const names = Object.getOwnPropertyNames(tree)
const routeRecord = tree[routeRecordKey]
const result: import('vue-router').RouteRecordRaw[] = []
let currentRoute: import('vue-router').RouteRecordRaw[] = result
if (routeRecord) {
result.push(routeRecord)
routeRecord.path = path
routeRecord.children = []
currentRoute = routeRecord.children
}
names.forEach((it) => {
currentRoute.push(...traverseTree(tree[it], getRoutePath(path, it)))
})
return result
}
function getRoutePath(path: string, lastSegment: string) {
var path = path.endsWith('/') ? path.slice(0, -1) : path
var lastSegment =
lastSegment === 'index'
? ''
: lastSegment.startsWith('_')
? `:${lastSegment.slice(1)}`
: `${lastSegment}`
return path === '' ? lastSegment : `${path}/${lastSegment}`
}
function deepSet(obj: Record<PropertyKey, unknown>, path: PropertyKey[], value: unknown) {
path.slice(0, -1).reduce((acc, key) => (acc && acc[key]) || ((acc[key] = {}), acc[key]), obj)[
path.slice(-1)[0]
] = value
}