/
utils.ts
209 lines (182 loc) · 5.48 KB
/
utils.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
import { TreeNode } from './tree'
import type { RouteRecordOverride, TreeRouteParam } from './treeNodeValue'
import { pascalCase } from 'scule'
export type Awaitable<T> = T | PromiseLike<T>
export type LiteralStringUnion<LiteralType, BaseType extends string = string> =
| LiteralType
| (BaseType & Record<never, never>)
export function logTree(tree: TreeNode, log: (str: string) => any) {
log(printTree(tree))
}
const MAX_LEVEL = 1000
function printTree(
tree: TreeNode | TreeNode['children'],
level = 0,
parentPre = '',
treeStr = ''
): string {
// end of recursion
if (typeof tree !== 'object' || level >= MAX_LEVEL) return ''
if (tree instanceof Map) {
const total = tree.size
let index = 0
for (const [_key, child] of tree) {
const hasNext = index++ < total - 1
const { children } = child
treeStr += `${`${parentPre}${hasNext ? '├' : '└'}── `}${child}\n`
if (children) {
treeStr += printTree(
children,
level + 1,
`${parentPre}${hasNext ? '│' : ' '} `
)
}
}
} else {
const children = tree.children
treeStr = `${tree}\n`
if (children) {
treeStr += printTree(children, level + 1)
}
}
return treeStr
}
/**
* Typesafe alternative to Array.isArray
* https://github.com/microsoft/TypeScript/pull/48228
*/
export const isArray: (arg: ArrayLike<any> | any) => arg is ReadonlyArray<any> =
Array.isArray
export function trimExtension(path: string) {
const lastDot = path.lastIndexOf('.')
return lastDot < 0 ? path : path.slice(0, lastDot)
}
export function throttle(fn: () => void, wait: number, initialWait: number) {
let pendingExecutionTimeout: ReturnType<typeof setTimeout> | null = null
let pendingExecution = false
let executionTimeout: ReturnType<typeof setTimeout> | null = null
return () => {
if (pendingExecutionTimeout == null) {
pendingExecutionTimeout = setTimeout(() => {
pendingExecutionTimeout = null
if (pendingExecution) {
pendingExecution = false
fn()
}
}, wait)
executionTimeout = setTimeout(() => {
executionTimeout = null
fn()
}, initialWait)
} else if (executionTimeout == null) {
// we run the function recently, so we can skip it and add a pending execution
pendingExecution = true
}
}
}
const LEADING_SLASH_RE = /^\//
const TRAILING_SLASH_RE = /\/$/
export function joinPath(...paths: string[]): string {
let result = ''
for (const path of paths) {
result =
result.replace(TRAILING_SLASH_RE, '') +
// check path to avoid adding a trailing slash when joining an empty string
(path && '/' + path.replace(LEADING_SLASH_RE, ''))
}
return result
}
function paramToName({ paramName, modifier, isSplat }: TreeRouteParam) {
return `${isSplat ? '$' : ''}${
paramName.charAt(0).toUpperCase() + paramName.slice(1)
}${
modifier
// ? modifier === '+'
// ? 'OneOrMore'
// : modifier === '?'
// ? 'ZeroOrOne'
// : 'ZeroOrMore'
// : ''
}`
}
/**
* Creates a name based of the node path segments.
*
* @param node - the node to get the path from
* @param parent - the parent node
* @returns a route name
*/
export function getPascalCaseRouteName(node: TreeNode): string {
if (node.parent?.isRoot() && node.value.pathSegment === '') return 'Root'
let name = node.value.subSegments
.map((segment) => {
if (typeof segment === 'string') {
return pascalCase(segment)
}
// else it's a param
return paramToName(segment)
})
.join('')
if (node.value.filePaths.size && node.children.has('index')) {
name += 'Parent'
}
const parent = node.parent
return (
(parent && !parent.isRoot()
? getPascalCaseRouteName(parent).replace(/Parent$/, '')
: '') + name
)
}
/**
* Joins the path segments of a node into a name that corresponds to the filepath represented by the node.
*
* @param node - the node to get the path from
* @returns a route name
*/
export function getFileBasedRouteName(node: TreeNode): string {
if (!node.parent) return ''
return getFileBasedRouteName(node.parent) + '/' + node.value.rawSegment
}
export function mergeRouteRecordOverride(
a: RouteRecordOverride,
b: RouteRecordOverride
): RouteRecordOverride {
const merged: RouteRecordOverride = {}
const keys = [
...new Set<keyof RouteRecordOverride>([
...(Object.keys(a) as (keyof RouteRecordOverride)[]),
...(Object.keys(b) as (keyof RouteRecordOverride)[]),
]),
]
for (const key of keys) {
if (key === 'alias') {
merged[key] = [...(a[key] || []), ...(b[key] || [])]
} else if (key === 'meta') {
merged[key] = mergeDeep(a[key] || {}, b[key] || {})
} else {
// @ts-expect-error: TS cannot see it's the same key
merged[key] = b[key] ?? a[key]
}
}
return merged
}
function isObject(obj: any): obj is Record<any, any> {
return obj && typeof obj === 'object'
}
function mergeDeep(...objects: Array<Record<any, any>>): Record<any, any> {
return objects.reduce((prev, obj) => {
Object.keys(obj).forEach((key) => {
const pVal = prev[key]
const oVal = obj[key]
if (Array.isArray(pVal) && Array.isArray(oVal)) {
prev[key] = pVal.concat(...oVal)
} else if (isObject(pVal) && isObject(oVal)) {
prev[key] = mergeDeep(pVal, oVal)
} else {
prev[key] = oVal
}
})
return prev
}, {})
}
export const __DEV__ = process.env.NODE_ENV !== 'production'