forked from vuejs/router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
583 lines (521 loc) · 17.6 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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
import {
RouteRecordRaw,
MatcherLocationRaw,
MatcherLocation,
isRouteName,
RouteRecordName,
_RouteRecordProps,
} from '../types'
import { createRouterError, ErrorTypes, MatcherError } from '../errors'
import {
createRouteRecordCacheKey,
createRouteRecordMatcher,
RouteRecordMatcher,
} from './pathMatcher'
import { RouteRecord, RouteRecordNormalized } from './types'
import type {
PathParams,
PathParserOptions,
_PathParserOptions,
} from './pathParserRanker'
import { comparePathParserScore } from './pathParserRanker'
import { warn } from '../warning'
import { assign, noop } from '../utils'
/**
* Internal RouterMatcher
*
* @internal
*/
export interface RouterMatcher {
addRoute: (record: RouteRecordRaw, parent?: RouteRecordMatcher) => () => void
removeRoute: {
(matcher: RouteRecordMatcher): void
(name: RouteRecordName): void
}
getRoutes: () => RouteRecordMatcher[]
getRecordMatcher: (name: RouteRecordName) => RouteRecordMatcher | undefined
/**
* Resolves a location. Gives access to the route record that corresponds to the actual path as well as filling the corresponding params objects
*
* @param location - MatcherLocationRaw to resolve to a url
* @param currentLocation - MatcherLocation of the current location
*/
resolve: (
location: MatcherLocationRaw,
currentLocation: MatcherLocation
) => MatcherLocation
}
/**
* Creates a Router Matcher.
*
* @internal
* @param routes - array of initial routes
* @param globalOptions - global route options
*/
export function createRouterMatcher(
routes: Readonly<RouteRecordRaw[]>,
globalOptions: PathParserOptions
): RouterMatcher {
// normalized ordered array of matchers
const matchers: RouteRecordMatcher[] = []
const matcherMap = new Map<RouteRecordName, RouteRecordMatcher>()
let restoreSort = globalOptions.sortCache != null
globalOptions = mergeOptions(
{
strict: false,
end: true,
sensitive: false,
sortCache: undefined,
} as PathParserOptions,
globalOptions
)
function getRecordMatcher(name: RouteRecordName) {
return matcherMap.get(name)
}
function addRoute(
record: RouteRecordRaw,
parent?: RouteRecordMatcher,
originalRecord?: RouteRecordMatcher
) {
// used later on to remove by name
const isRootAdd = !originalRecord
const mainNormalizedRecord = normalizeRouteRecord(record)
if (__DEV__) {
checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent)
}
// we might be the child of an alias
mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record
const options: PathParserOptions = mergeOptions(globalOptions, record)
// generate an array of records to correctly handle aliases
const normalizedRecords: (typeof mainNormalizedRecord)[] = [
mainNormalizedRecord,
]
if ('alias' in record) {
const aliases =
typeof record.alias === 'string' ? [record.alias] : record.alias!
for (const alias of aliases) {
normalizedRecords.push(
assign({}, mainNormalizedRecord, {
// this allows us to hold a copy of the `components` option
// so that async components cache is hold on the original record
components: originalRecord
? originalRecord.record.components
: mainNormalizedRecord.components,
path: alias,
// we might be the child of an alias
aliasOf: originalRecord
? originalRecord.record
: mainNormalizedRecord,
// the aliases are always of the same kind as the original since they
// are defined on the same record
}) as typeof mainNormalizedRecord
)
}
}
let matcher: RouteRecordMatcher
let originalMatcher: RouteRecordMatcher | undefined
for (const normalizedRecord of normalizedRecords) {
const { path } = normalizedRecord
// Build up the path for nested routes if the child isn't an absolute
// route. Only add the / delimiter if the child path isn't empty and if the
// parent path doesn't have a trailing slash
if (parent && path[0] !== '/') {
const parentPath = parent.record.path
const connectingSlash =
parentPath[parentPath.length - 1] === '/' ? '' : '/'
normalizedRecord.path =
parent.record.path + (path && connectingSlash + path)
}
if (__DEV__ && normalizedRecord.path === '*') {
throw new Error(
'Catch all routes ("*") must now be defined using a param with a custom regexp.\n' +
'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.'
)
}
// create the object beforehand, so it can be passed to children
matcher = createRouteRecordMatcher(normalizedRecord, parent, options)
if (__DEV__ && parent && path[0] === '/')
checkMissingParamsInAbsolutePath(matcher, parent)
// if we are an alias we must tell the original record that we exist,
// so we can be removed
if (originalRecord) {
originalRecord.alias.push(matcher)
if (__DEV__) {
checkSameParams(originalRecord, matcher)
}
} else {
// otherwise, the first record is the original and others are aliases
originalMatcher = originalMatcher || matcher
if (originalMatcher !== matcher) originalMatcher.alias.push(matcher)
// remove the route if named and only for the top record (avoid in nested calls)
// this works because the original record is the first one
if (isRootAdd && record.name && !isAliasRecord(matcher))
removeRoute(record.name)
}
if (mainNormalizedRecord.children) {
const children = mainNormalizedRecord.children
for (let i = 0; i < children.length; i++) {
addRoute(
children[i],
matcher,
originalRecord && originalRecord.children[i]
)
}
}
// if there was no original record, then the first one was not an alias and all
// other aliases (if any) need to reference this record when adding children
originalRecord = originalRecord || matcher
// TODO: add normalized records for more flexibility
// if (parent && isAliasRecord(originalRecord)) {
// parent.children.push(originalRecord)
// }
// Avoid adding a record that doesn't display anything. This allows passing through records without a component to
// not be reached and pass through the catch all route
if (
(matcher.record.components &&
Object.keys(matcher.record.components).length) ||
matcher.record.name ||
matcher.record.redirect
) {
insertMatcher(matcher)
}
}
return originalMatcher
? () => {
// since other matchers are aliases, they should be removed by the original matcher
removeRoute(originalMatcher!)
}
: noop
}
function removeRoute(matcherRef: RouteRecordName | RouteRecordMatcher) {
if (isRouteName(matcherRef)) {
const matcher = matcherMap.get(matcherRef)
if (matcher) {
matcherMap.delete(matcherRef)
matchers.splice(matchers.indexOf(matcher), 1)
matcher.children.forEach(removeRoute)
matcher.alias.forEach(removeRoute)
}
} else {
const index = matchers.indexOf(matcherRef)
if (index > -1) {
matchers.splice(index, 1)
if (matcherRef.record.name) matcherMap.delete(matcherRef.record.name)
matcherRef.children.forEach(removeRoute)
matcherRef.alias.forEach(removeRoute)
}
}
}
function getRoutes() {
return matchers
}
function insertMatcher(matcher: RouteRecordMatcher) {
if (restoreSort) {
matchers.push(matcher)
} else {
let i = 0
while (
i < matchers.length &&
comparePathParserScore(matcher, matchers[i]) >= 0 &&
// Adding children with empty path should still appear before the parent
// https://github.com/vuejs/router/issues/1124
(matcher.record.path !== matchers[i].record.path ||
!isRecordChildOf(matcher, matchers[i]))
)
i++
matchers.splice(i, 0, matcher)
}
// only add the original record to the name map
if (matcher.record.name && !isAliasRecord(matcher))
matcherMap.set(matcher.record.name, matcher)
}
function resolve(
location: Readonly<MatcherLocationRaw>,
currentLocation: Readonly<MatcherLocation>
): MatcherLocation {
let matcher: RouteRecordMatcher | undefined
let params: PathParams = {}
let path: MatcherLocation['path']
let name: MatcherLocation['name']
if ('name' in location && location.name) {
matcher = matcherMap.get(location.name)
if (!matcher)
throw createRouterError<MatcherError>(ErrorTypes.MATCHER_NOT_FOUND, {
location,
})
// warn if the user is passing invalid params so they can debug it better when they get removed
if (__DEV__) {
const invalidParams: string[] = Object.keys(
location.params || {}
).filter(paramName => !matcher!.keys.find(k => k.name === paramName))
if (invalidParams.length) {
warn(
`Discarded invalid param(s) "${invalidParams.join(
'", "'
)}" when navigating. See https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.`
)
}
}
name = matcher.record.name
params = assign(
// paramsFromLocation is a new object
paramsFromLocation(
currentLocation.params,
// only keep params that exist in the resolved location
// TODO: only keep optional params coming from a parent record
matcher.keys.filter(k => !k.optional).map(k => k.name)
),
// discard any existing params in the current location that do not exist here
// #1497 this ensures better active/exact matching
location.params &&
paramsFromLocation(
location.params,
matcher.keys.map(k => k.name)
)
)
// throws if cannot be stringified
path = matcher.stringify(params)
} else if (location.path != null) {
// no need to resolve the path with the matcher as it was provided
// this also allows the user to control the encoding
path = location.path
if (__DEV__ && !path.startsWith('/')) {
warn(
`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://github.com/vuejs/router/issues/new/choose.`
)
}
matcher = matchers.find(m => m.re.test(path))
// matcher should have a value after the loop
if (matcher) {
// we know the matcher works because we tested the regexp
params = matcher.parse(path)!
name = matcher.record.name
}
// location is a relative path
} else {
// match by name or path of current route
matcher = currentLocation.name
? matcherMap.get(currentLocation.name)
: matchers.find(m => m.re.test(currentLocation.path))
if (!matcher)
throw createRouterError<MatcherError>(ErrorTypes.MATCHER_NOT_FOUND, {
location,
currentLocation,
})
name = matcher.record.name
// since we are navigating to the same location, we don't need to pick the
// params like when `name` is provided
params = assign({}, currentLocation.params, location.params)
path = matcher.stringify(params)
}
const matched: MatcherLocation['matched'] = []
let parentMatcher: RouteRecordMatcher | undefined = matcher
while (parentMatcher) {
// reversed order so parents are at the beginning
matched.unshift(parentMatcher.record)
parentMatcher = parentMatcher.parent
}
return {
name,
path,
params,
matched,
meta: mergeMetaFields(matched),
}
}
// add initial routes
routes.forEach(route => addRoute(route))
// restore matcher order from cache
if (globalOptions.sortCache != null) {
try {
matchers.sort(
(a, b) =>
globalOptions!.sortCache![a.cacheKey!] -
globalOptions!.sortCache![b.cacheKey!]
)
for (const entry of matchers) {
delete entry.cacheKey
}
} catch {
console.log('Restore failure.')
}
}
restoreSort = false
return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher }
}
/**
* Creates a router matcher sort cache
*
* @internal
*/
export function createRouterMatcherSortCache(
records: RouteRecord[]
): Record<string, number> {
const sortCache: Record<string, number> = {}
for (let i = 0; i < records.length; i++) {
sortCache[createRouteRecordCacheKey(records[i])] = i
}
return sortCache
}
function paramsFromLocation(
params: MatcherLocation['params'],
keys: string[]
): MatcherLocation['params'] {
const newParams = {} as MatcherLocation['params']
for (const key of keys) {
if (key in params) newParams[key] = params[key]
}
return newParams
}
/**
* Normalizes a RouteRecordRaw. Creates a copy
*
* @param record
* @returns the normalized version
*/
export function normalizeRouteRecord(
record: RouteRecordRaw
): RouteRecordNormalized {
return {
path: record.path,
redirect: record.redirect,
name: record.name,
meta: record.meta || {},
aliasOf: undefined,
beforeEnter: record.beforeEnter,
props: normalizeRecordProps(record),
children: record.children || [],
instances: {},
leaveGuards: new Set(),
updateGuards: new Set(),
enterCallbacks: {},
components:
'components' in record
? record.components || null
: record.component && { default: record.component },
}
}
/**
* Normalize the optional `props` in a record to always be an object similar to
* components. Also accept a boolean for components.
* @param record
*/
function normalizeRecordProps(
record: RouteRecordRaw
): Record<string, _RouteRecordProps> {
const propsObject = {} as Record<string, _RouteRecordProps>
// props does not exist on redirect records, but we can set false directly
const props = record.props || false
if ('component' in record) {
propsObject.default = props
} else {
// NOTE: we could also allow a function to be applied to every component.
// Would need user feedback for use cases
for (const name in record.components)
propsObject[name] = typeof props === 'object' ? props[name] : props
}
return propsObject
}
/**
* Checks if a record or any of its parent is an alias
* @param record
*/
function isAliasRecord(record: RouteRecordMatcher | undefined): boolean {
while (record) {
if (record.record.aliasOf) return true
record = record.parent
}
return false
}
/**
* Merge meta fields of an array of records
*
* @param matched - array of matched records
*/
function mergeMetaFields(matched: MatcherLocation['matched']) {
return matched.reduce(
(meta, record) => assign(meta, record.meta),
{} as MatcherLocation['meta']
)
}
function mergeOptions<T extends object>(
defaults: T,
partialOptions: Partial<T>
): T {
const options = {} as T
for (const key in defaults) {
options[key] = key in partialOptions ? partialOptions[key]! : defaults[key]
}
return options
}
type ParamKey = RouteRecordMatcher['keys'][number]
function isSameParam(a: ParamKey, b: ParamKey): boolean {
return (
a.name === b.name &&
a.optional === b.optional &&
a.repeatable === b.repeatable
)
}
/**
* Check if a path and its alias have the same required params
*
* @param a - original record
* @param b - alias record
*/
function checkSameParams(a: RouteRecordMatcher, b: RouteRecordMatcher) {
for (const key of a.keys) {
if (!key.optional && !b.keys.find(isSameParam.bind(null, key)))
return warn(
`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`
)
}
for (const key of b.keys) {
if (!key.optional && !a.keys.find(isSameParam.bind(null, key)))
return warn(
`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`
)
}
}
/**
* A route with a name and a child with an empty path without a name should warn when adding the route
*
* @param mainNormalizedRecord - RouteRecordNormalized
* @param parent - RouteRecordMatcher
*/
function checkChildMissingNameWithEmptyPath(
mainNormalizedRecord: RouteRecordNormalized,
parent?: RouteRecordMatcher
) {
if (
parent &&
parent.record.name &&
!mainNormalizedRecord.name &&
!mainNormalizedRecord.path
) {
warn(
`The route named "${String(
parent.record.name
)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`
)
}
}
function checkMissingParamsInAbsolutePath(
record: RouteRecordMatcher,
parent: RouteRecordMatcher
) {
for (const key of parent.keys) {
if (!record.keys.find(isSameParam.bind(null, key)))
return warn(
`Absolute path "${record.record.path}" must have the exact same param named "${key.name}" as its parent "${parent.record.path}".`
)
}
}
function isRecordChildOf(
record: RouteRecordMatcher,
parent: RouteRecordMatcher
): boolean {
return parent.children.some(
child => child === record || isRecordChildOf(record, child)
)
}
export type { PathParserOptions, _PathParserOptions }