Skip to content

Commit 16cf6a2

Browse files
authored
feat: warn on repeatable params being passed as scalars (#2879)
* test(resolver-fixed): return arrays from the repeatable test matcher * fix(matcher): warn when a repeatable param is not an array Repeatable params must be arrays. Pass [] or null to remove an optional one. * feat(experimental): warn when a repeatable param is not an array * feat(matcher): warn when an optional param is removed with an empty string Matches the experimental router. Use null instead. * docs(diagnostics): limit R0106 removal guidance to optional params * fix(matcher): check explicit params in relative locations * test: use codes * docs: up
1 parent 6bdcf9a commit 16cf6a2

9 files changed

Lines changed: 187 additions & 9 deletions

File tree

‎packages/docs/guide/essentials/navigation.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ When building a string path or an object with `path`, provide an encoded path. U
6767
<RouterLink :to="{ name: 'user', params: { username } }">User</RouterLink>
6868
```
6969

70-
When specifying `params`, make sure to either provide a `string` or `number` (or an array of these for [repeatable params](./route-matching-syntax.md#Repeatable-params)). **Any other type (like objects, booleans, etc) will be automatically stringified**. For [optional params](./route-matching-syntax.md#Optional-parameters), you can provide an empty string (`""`) or `null` as the value to remove it.
70+
When specifying `params`, provide a `string` or `number` for a regular param. For [repeatable params](./route-matching-syntax.md#Repeatable-params), always provide an array, even when it has one item. To remove an optional repeatable param, provide an empty array (`[]`) or `null`. **Any other type (like objects or booleans) will be automatically stringified**. For other [optional params](./route-matching-syntax.md#Optional-parameters), provide `null` to remove it.
7171

7272
Since the prop `to` accepts the same kind of object as `router.push`, the exact same rules apply to both of them.
7373

‎packages/docs/zh/guide/essentials/navigation.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ router.push({ path: '/user', params: { username } }) // -> /user
6767
<RouterLink :to="{ name: 'user', params: { username } }">User</RouterLink>
6868
```
6969

70-
当指定 `params` 时,可提供 `string` 或 `number` 参数(或者对于[可重复的参数](./route-matching-syntax.md#repeatable-params)可提供一个数组)。**任何其他类型(如对象、布尔等)都将被自动字符串化**。对于[可选参数](./route-matching-syntax.md#repeatable-params),你可以提供一个空字符串(`""`)或 `null` 来移除它。
70+
当指定 `params` 时,普通参数可提供 `string` 或 `number`。对于[可重复的参数](./route-matching-syntax.md#可重复的参数),请始终提供一个数组,即使它只有一项。要移除一个可选的可重复参数,可提供一个空数组(`[]`)或 `null`。**任何其他类型(如对象、布尔等)都将被自动字符串化**。对于其他[可选参数](./route-matching-syntax.md#可选参数),提供 `null` 来移除它。
7171

7272
由于属性 `to` 与 `router.push` 接受的对象种类相同,所以两者的规则完全相同。
7373

‎packages/router/__tests__/matcher/resolve.spec.ts‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -618,14 +618,47 @@ describe('RouterMatcher.resolve', () => {
618618
{ name: 'a', params: { p: ['b', 'c', 'd'] } },
619619
{ name: 'a', path: '/a/b/c/d', params: { p: ['b', 'c', 'd'] } }
620620
)
621+
622+
expect('VUE_ROUTER_R0106').not.toHaveBeenWarned()
621623
})
622624

623-
it('resolves single params for a repeatable params', () => {
625+
it('warns when a repeatable param is provided as a scalar', () => {
624626
assertRecordMatch(
625627
{ path: '/a/:p+', name: 'a', components },
626628
{ name: 'a', params: { p: 'b' } },
627629
{ name: 'a', path: '/a/b', params: { p: 'b' } }
628630
)
631+
632+
expect('VUE_ROUTER_R0106').toHaveBeenWarned()
633+
})
634+
635+
it('warns when an optional repeatable param is removed with an empty string', () => {
636+
assertRecordMatch(
637+
{ path: '/a/:p*', name: 'a', components },
638+
{ name: 'a', params: { p: '' } },
639+
{ name: 'a', path: '/a', params: { p: '' } }
640+
)
641+
642+
expect('VUE_ROUTER_R0122').toHaveBeenWarned()
643+
})
644+
645+
it('does not warn when an optional repeatable param is empty or omitted', () => {
646+
const matcher = createRouterMatcher(
647+
[{ path: '/a/:p*', name: 'a', components }],
648+
{}
649+
)
650+
expect(
651+
matcher.resolve(
652+
{ name: 'a', params: { p: [] } },
653+
START_LOCATION_NORMALIZED
654+
).path
655+
).toBe('/a')
656+
expect(
657+
matcher.resolve({ name: 'a', params: {} }, START_LOCATION_NORMALIZED)
658+
.path
659+
).toBe('/a')
660+
661+
expect('VUE_ROUTER_R0106').not.toHaveBeenWarned()
629662
})
630663

631664
it('keeps repeated params as a single one when provided through path', () => {
@@ -937,6 +970,7 @@ describe('RouterMatcher.resolve', () => {
937970
name: undefined,
938971
}
939972
)
973+
expect('VUE_ROUTER_R0122').toHaveBeenWarned()
940974
})
941975

942976
it('resolves root path with optional params', () => {
@@ -989,6 +1023,60 @@ describe('RouterMatcher.resolve', () => {
9891023
)
9901024
})
9911025

1026+
it('warns when a repeatable param is provided as a scalar', () => {
1027+
const record = { path: '/a/:p+', name: 'a', components }
1028+
assertRecordMatch(
1029+
record,
1030+
{ params: { p: 'b' } },
1031+
{ name: 'a', path: '/a/b', params: { p: 'b' } },
1032+
{
1033+
path: '/a/c',
1034+
name: 'a',
1035+
params: { p: ['c'] },
1036+
matched: [record] as any,
1037+
meta: {},
1038+
}
1039+
)
1040+
1041+
expect('VUE_ROUTER_R0106').toHaveBeenWarned()
1042+
})
1043+
1044+
it('warns when an optional param is removed with an empty string', () => {
1045+
const record = { path: '/a/:p?', name: 'a', components }
1046+
assertRecordMatch(
1047+
record,
1048+
{ params: { p: '' } },
1049+
{ name: 'a', path: '/a', params: { p: '' } },
1050+
{
1051+
path: '/a/c',
1052+
name: 'a',
1053+
params: { p: 'c' },
1054+
matched: [record] as any,
1055+
meta: {},
1056+
}
1057+
)
1058+
1059+
expect('VUE_ROUTER_R0122').toHaveBeenWarned()
1060+
})
1061+
1062+
it('does not warn for params inherited from the current location', () => {
1063+
const record = { path: '/a/:p+', name: 'a', components }
1064+
assertRecordMatch(
1065+
record,
1066+
{},
1067+
{ name: 'a', path: '/a/c', params: { p: 'c' } },
1068+
{
1069+
path: '/a/c',
1070+
name: 'a',
1071+
params: { p: 'c' },
1072+
matched: [record] as any,
1073+
meta: {},
1074+
}
1075+
)
1076+
1077+
expect('VUE_ROUTER_R0106').not.toHaveBeenWarned()
1078+
})
1079+
9921080
it('replace params even with no name', () => {
9931081
const record = { path: '/users/:id/m/:role', components }
9941082
assertRecordMatch(

‎packages/router/__tests__/router.spec.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,7 @@ describe('Router', () => {
393393
const { router } = await newRouter()
394394
const route1 = router.resolve({ name: 'optional', params: { p: '' } })
395395
expect(route1.params).toEqual({ p: '' })
396+
expect('VUE_ROUTER_R0122').toHaveBeenWarned()
396397
})
397398

398399
it('navigates to same route record but different query', async () => {
@@ -446,6 +447,13 @@ describe('Router', () => {
446447
).not.toThrow()
447448
})
448449

450+
it('removes an optional repeatable param with null without warning', async () => {
451+
const { router } = await newRouter()
452+
router.addRoute({ path: '/r/:r*', name: 'r', component: components.Bar })
453+
expect(router.resolve({ name: 'r', params: { r: null } }).path).toBe('/r')
454+
expect('VUE_ROUTER_R0106').not.toHaveBeenWarned()
455+
})
456+
449457
it('fails with arrays for non repeatable params', async () => {
450458
const { router } = await newRouter()
451459
router.addRoute({ path: '/r1/:r', name: 'r1', component: components.Bar })

‎packages/router/src/diagnostics.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export const diagnostics = /*#__PURE__*/ defineDiagnostics({
2626
// docsBase: code => `https://router.vuejs.org/errors/${code.toLowerCase()}`,
2727
reporters: [/*#__PURE__*/ createConsoleReporter()],
2828
codes: {
29-
// --- experimental/route-resolver/matchers/matcher-pattern.ts ---
29+
// --- experimental/route-resolver/matchers/matcher-pattern.ts, matcher/index.ts ---
3030
VUE_ROUTER_R0122: {
3131
why: (p: { param: string; value: string }) =>
3232
`The optional path param "${p.param}" is being removed with ${p.value}.`,
@@ -337,6 +337,12 @@ export const diagnostics = /*#__PURE__*/ defineDiagnostics({
337337
`Finding ancestor route "${p.ancestor}" failed for "${p.record}"`,
338338
fix: 'Report a reproduction at https://github.com/vuejs/router/issues/new/choose.',
339339
},
340+
VUE_ROUTER_R0106: {
341+
why: (p: { name: string }) =>
342+
`Repeatable param "${p.name}" was provided without an array.`,
343+
fix: (p: { name: string }) =>
344+
`Pass it as an array, even when it has one item: { ${JSON.stringify(p.name)}: [value] }. If the param is optional (e.g. ":${p.name}*"), pass an empty array or null to remove it.`,
345+
},
340346

341347
// --- history/hash.ts ---
342348
VUE_ROUTER_R0110: {

‎packages/router/src/experimental/param-diagnostics.spec.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,40 @@ describe('ignored query param diagnostics', () => {
170170
if (__DEV__) expect('VUE_ROUTER_R0123').toHaveBeenWarnedTimes(1)
171171
})
172172
})
173+
174+
describe('repeatable param diagnostics', () => {
175+
function resolver(subsegment = false) {
176+
return createFixedResolver([
177+
{
178+
name: 'repeat',
179+
path: new MatcherPatternPathDynamic(
180+
subsegment ? /^\/repeat\/pre(.+)?$/ : /^\/repeat(?:\/(.+))?$/,
181+
{ p: [undefined, true, true] },
182+
subsegment ? ['repeat', ['pre', 1]] : ['repeat', 1]
183+
),
184+
},
185+
])
186+
}
187+
188+
it.each([false, true])('warns for a scalar (subsegment: %s)', subsegment => {
189+
expect(
190+
resolver(subsegment).resolve({ name: 'repeat', params: { p: 'a' } })
191+
.params
192+
).toEqual({ p: ['a'] })
193+
if (__DEV__) expect('VUE_ROUTER_R0106').toHaveBeenWarnedTimes(1)
194+
})
195+
196+
it('does not warn for arrays, null, or omitted params', () => {
197+
const routes = resolver()
198+
expect(
199+
routes.resolve({ name: 'repeat', params: { p: ['a', 'b'] } }).path
200+
).toBe('/repeat/a/b')
201+
expect(routes.resolve({ name: 'repeat', params: { p: [] } }).path).toBe(
202+
'/repeat'
203+
)
204+
expect(routes.resolve({ name: 'repeat', params: { p: null } }).path).toBe(
205+
'/repeat'
206+
)
207+
expect(routes.resolve({ name: 'repeat', params: {} }).path).toBe('/repeat')
208+
})
209+
})

‎packages/router/src/experimental/route-resolver/matchers/matcher-pattern.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ export class MatcherPatternPathDynamic<
240240
string,
241241
MatcherPatternPathDynamic_ParamOptions<any, any>
242242
>)[keyof TParamsOptions][0]
243+
let repeatable: boolean | undefined
243244
let optional: boolean | undefined
244245
let value: ReturnType<NonNullable<ParamParser['set']>> | undefined
245246
const path =
@@ -252,7 +253,7 @@ export class MatcherPatternPathDynamic<
252253
// path param
253254
} else if (typeof part === 'number') {
254255
paramName = this.paramsKeys[paramIndex++]
255-
;[parser /* repeatable */, , optional] = this.params[paramName]
256+
;[parser, repeatable, optional] = this.params[paramName]
256257
value = (parser?.set || identityFn)(params[paramName])
257258

258259
if (__DEV__ && optional && Object.hasOwn(params, paramName)) {
@@ -263,6 +264,10 @@ export class MatcherPatternPathDynamic<
263264
)
264265
}
265266

267+
if (__DEV__ && repeatable && value && !Array.isArray(value)) {
268+
diagnostics.VUE_ROUTER_R0106({ name: String(paramName) })
269+
}
270+
266271
// non optional repeatable params cannot be empty
267272
if (Array.isArray(value) && !value.length && !optional) {
268273
// read the flag here so prod code does not keep it
@@ -285,7 +290,7 @@ export class MatcherPatternPathDynamic<
285290
}
286291

287292
paramName = this.paramsKeys[paramIndex++]
288-
;[parser /* repeatable */, , optional] = this.params[paramName]
293+
;[parser, repeatable, optional] = this.params[paramName]
289294
value = (parser?.set || identityFn)(params[paramName])
290295

291296
if (__DEV__ && optional && Object.hasOwn(params, paramName)) {
@@ -296,6 +301,10 @@ export class MatcherPatternPathDynamic<
296301
)
297302
}
298303

304+
if (__DEV__ && repeatable && value && !Array.isArray(value)) {
305+
diagnostics.VUE_ROUTER_R0106({ name: String(paramName) })
306+
}
307+
299308
// a repeatable param in a sub segment joins its values with `/`
300309
// so file-based routes like `rep.[ids]+` (sub segment
301310
// ['rep/', 1]) and `set.[ids]+.other` round-trip correctly

‎packages/router/src/experimental/route-resolver/resolver-fixed.spec.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,7 @@ const REPEATABLE_PARAM_MATCHER: MatcherPatternPath<{ p: string | string[] }> = {
7171
match(path) {
7272
const match = path.match(/^\/a\/(.+)$/)
7373
if (!match) miss()
74-
const segments = match[1].split('/')
75-
return { p: segments.length === 1 ? segments[0] : segments }
74+
return { p: match[1].split('/') }
7675
},
7776
build({ p }) {
7877
const segments = Array.isArray(p) ? p : [p]
@@ -1258,7 +1257,7 @@ describe('fixed resolver', () => {
12581257
).toMatchObject({
12591258
name: 'repeatable',
12601259
path: '/a/b',
1261-
params: { p: 'b' },
1260+
params: { p: ['b'] },
12621261
})
12631262
})
12641263

@@ -1271,6 +1270,10 @@ describe('fixed resolver', () => {
12711270
name: 'repeatable',
12721271
params: { p: ['b', 'c'] },
12731272
})
1273+
expect(resolver.resolve({ path: '/a/b' })).toMatchObject({
1274+
name: 'repeatable',
1275+
params: { p: ['b'] },
1276+
})
12741277
})
12751278
})
12761279

‎packages/router/src/matcher/index.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,8 @@ export function createRouterMatcher(
278278
: '',
279279
})
280280
}
281+
282+
checkParamValues(matcher, location.params)
281283
}
282284

283285
name = matcher.record.name
@@ -340,6 +342,7 @@ export function createRouterMatcher(
340342
location,
341343
currentLocation,
342344
})
345+
if (__DEV__) checkParamValues(matcher, location.params)
343346
name = matcher.record.name
344347
// since we are navigating to the same location, we don't need to pick the
345348
// params like when `name` is provided
@@ -565,6 +568,30 @@ function checkSameNameAsAncestor(
565568
}
566569
}
567570

571+
/**
572+
* Warns about explicit param values that are probably mistakes.
573+
*
574+
* @param matcher - matcher of the resolved location
575+
* @param params - params explicitly passed in the location
576+
*/
577+
function checkParamValues(
578+
matcher: RouteRecordMatcher,
579+
params: MatcherLocation['params'] | undefined
580+
) {
581+
if (!params) return
582+
for (const key of matcher.keys) {
583+
const value = params[key.name]
584+
if (key.optional && value === '') {
585+
diagnostics.VUE_ROUTER_R0122({
586+
param: key.name,
587+
value: 'an empty string',
588+
})
589+
} else if (key.repeatable && value != null && !Array.isArray(value)) {
590+
diagnostics.VUE_ROUTER_R0106({ name: key.name })
591+
}
592+
}
593+
}
594+
568595
function checkMissingParamsInAbsolutePath(
569596
record: RouteRecordMatcher,
570597
parent: RouteRecordMatcher

0 commit comments

Comments
 (0)