Skip to content

Commit 2017a6d

Browse files
committed
Add vue/valid-define-emits rule
1 parent 9c8f293 commit 2017a6d

File tree

6 files changed

+474
-11
lines changed

6 files changed

+474
-11
lines changed

Diff for: docs/rules/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ For example:
331331
| [vue/v-for-delimiter-style](./v-for-delimiter-style.md) | enforce `v-for` directive's delimiter style | :wrench: |
332332
| [vue/v-on-event-hyphenation](./v-on-event-hyphenation.md) | enforce v-on event naming style on custom components in template | :wrench: |
333333
| [vue/v-on-function-call](./v-on-function-call.md) | enforce or forbid parentheses after method calls without arguments in `v-on` directives | :wrench: |
334+
| [vue/valid-define-emits](./valid-define-emits.md) | enforce valid `defineEmits` compiler macro | |
334335
| [vue/valid-next-tick](./valid-next-tick.md) | enforce valid `nextTick` function calls | :wrench: |
335336

336337
### Extension Rules

Diff for: docs/rules/valid-define-emits.md

+133
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
---
2+
pageClass: rule-details
3+
sidebarDepth: 0
4+
title: vue/valid-define-emits
5+
description: enforce valid `defineEmits` compiler macro
6+
---
7+
# vue/valid-define-emits
8+
9+
> enforce valid `defineEmits` compiler macro
10+
11+
- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> ***This rule has not been released yet.*** </badge>
12+
13+
This rule checks whether `defineEmits` compiler macro is valid.
14+
15+
## :book: Rule Details
16+
17+
This rule reports `defineEmits` compiler macros in the following cases:
18+
19+
- `defineEmits` are referencing locally declared variables.
20+
- `defineEmits` has both a literal type and an argument. e.g. `defineEmits<(e: 'foo')=>void>(['bar'])`
21+
- `defineEmits` has been called multiple times.
22+
- Custom events are defined in both `defineEmits` and `export default {}`.
23+
- Custom events are not defined in either `defineEmits` or `export default {}`.
24+
25+
<eslint-code-block :rules="{'vue/valid-define-emits': ['error']}">
26+
27+
```vue
28+
<script setup>
29+
/* ✓ GOOD */
30+
defineEmits({ notify: null })
31+
</script>
32+
```
33+
34+
</eslint-code-block>
35+
36+
<eslint-code-block :rules="{'vue/valid-define-emits': ['error']}">
37+
38+
```vue
39+
<script setup>
40+
/* ✓ GOOD */
41+
defineEmits(['notify'])
42+
</script>
43+
```
44+
45+
</eslint-code-block>
46+
47+
```vue
48+
<script setup lang="ts">
49+
/* ✓ GOOD */
50+
defineEmits<(e: 'notify')=>void>()
51+
</script>
52+
```
53+
54+
<eslint-code-block :rules="{'vue/valid-define-emits': ['error']}">
55+
56+
```vue
57+
<script>
58+
const def = { notify: null }
59+
</script>
60+
<script setup>
61+
/* ✓ GOOD */
62+
defineEmits(def)
63+
</script>
64+
```
65+
66+
</eslint-code-block>
67+
68+
<eslint-code-block :rules="{'vue/valid-define-emits': ['error']}">
69+
70+
```vue
71+
<script setup>
72+
/* ✗ BAD */
73+
const def = { notify: null }
74+
defineEmits(def)
75+
</script>
76+
```
77+
78+
</eslint-code-block>
79+
80+
```vue
81+
<script setup lang="ts">
82+
/* ✗ BAD */
83+
defineEmits<(e: 'notify')=>void>({ submit: null })
84+
</script>
85+
```
86+
87+
<eslint-code-block :rules="{'vue/valid-define-emits': ['error']}">
88+
89+
```vue
90+
<script setup>
91+
/* ✗ BAD */
92+
defineEmits({ notify: null })
93+
defineEmits({ submit: null })
94+
</script>
95+
```
96+
97+
</eslint-code-block>
98+
99+
<eslint-code-block :rules="{'vue/valid-define-emits': ['error']}">
100+
101+
```vue
102+
<script>
103+
export default {
104+
emits: { notify: null }
105+
}
106+
</script>
107+
<script setup>
108+
/* ✗ BAD */
109+
defineEmits({ submit: null })
110+
</script>
111+
```
112+
113+
</eslint-code-block>
114+
115+
<eslint-code-block :rules="{'vue/valid-define-emits': ['error']}">
116+
117+
```vue
118+
<script setup>
119+
/* ✗ BAD */
120+
defineEmits()
121+
</script>
122+
```
123+
124+
</eslint-code-block>
125+
126+
## :wrench: Options
127+
128+
Nothing.
129+
130+
## :mag: Implementation
131+
132+
- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/valid-define-emits.js)
133+
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/valid-define-emits.js)

Diff for: lib/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ module.exports = {
171171
'v-on-function-call': require('./rules/v-on-function-call'),
172172
'v-on-style': require('./rules/v-on-style'),
173173
'v-slot-style': require('./rules/v-slot-style'),
174+
'valid-define-emits': require('./rules/valid-define-emits'),
174175
'valid-next-tick': require('./rules/valid-next-tick'),
175176
'valid-template-root': require('./rules/valid-template-root'),
176177
'valid-v-bind-sync': require('./rules/valid-v-bind-sync'),

Diff for: lib/rules/valid-define-emits.js

+144
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
/**
2+
* @author Yosuke Ota <https://github.com/ota-meshi>
3+
* See LICENSE file in root directory for full license.
4+
*/
5+
'use strict'
6+
7+
const { findVariable } = require('eslint-utils')
8+
const utils = require('../utils')
9+
10+
module.exports = {
11+
meta: {
12+
type: 'problem',
13+
docs: {
14+
description: 'enforce valid `defineEmits` compiler macro',
15+
// TODO Switch in the major version.
16+
// categories: ['vue3-essential'],
17+
categories: undefined,
18+
url: 'https://eslint.vuejs.org/rules/valid-define-emits.html'
19+
},
20+
fixable: null,
21+
schema: [],
22+
messages: {
23+
hasTypeAndArg: '`defineEmits` has both a type-only emit and an argument.',
24+
referencingLocally:
25+
'`defineEmits` are referencing locally declared variables.',
26+
multiple: '`defineEmits` has been called multiple times.',
27+
notDefined: 'Custom events are not defined.',
28+
definedInBoth:
29+
'Custom events are defined in both `defineEmits` and `export default {}`.'
30+
}
31+
},
32+
/** @param {RuleContext} context */
33+
create(context) {
34+
const scriptSetup = utils.getScriptSetupElement(context)
35+
if (!scriptSetup) {
36+
return {}
37+
}
38+
39+
/** @type {Set<Expression | SpreadElement>} */
40+
const emitsDefExpressions = new Set()
41+
let hasDefaultExport = false
42+
/** @type {CallExpression[]} */
43+
const defineEmitsNodes = []
44+
/** @type {CallExpression | null} */
45+
let emptyDefineEmits = null
46+
47+
return utils.compositingVisitors(
48+
utils.defineScriptSetupVisitor(context, {
49+
onDefineEmitsEnter(node) {
50+
defineEmitsNodes.push(node)
51+
52+
if (node.arguments.length >= 1) {
53+
if (node.typeParameters && node.typeParameters.params.length >= 1) {
54+
// `defineEmits` has both a literal type and an argument.
55+
context.report({
56+
node,
57+
messageId: 'hasTypeAndArg'
58+
})
59+
return
60+
}
61+
62+
emitsDefExpressions.add(node.arguments[0])
63+
} else {
64+
if (
65+
!node.typeParameters ||
66+
node.typeParameters.params.length === 0
67+
) {
68+
emptyDefineEmits = node
69+
}
70+
}
71+
},
72+
Identifier(node) {
73+
for (const def of emitsDefExpressions) {
74+
if (utils.inRange(def.range, node)) {
75+
const variable = findVariable(context.getScope(), node)
76+
if (
77+
variable &&
78+
variable.references.some((ref) => ref.identifier === node)
79+
) {
80+
if (
81+
variable.defs.length &&
82+
variable.defs.every((def) =>
83+
utils.inRange(scriptSetup.range, def.name)
84+
)
85+
) {
86+
//`defineEmits` are referencing locally declared variables.
87+
context.report({
88+
node,
89+
messageId: 'referencingLocally'
90+
})
91+
}
92+
}
93+
}
94+
}
95+
}
96+
}),
97+
utils.defineVueVisitor(context, {
98+
onVueObjectEnter(node, { type }) {
99+
if (type !== 'export' || utils.inRange(scriptSetup.range, node)) {
100+
return
101+
}
102+
103+
hasDefaultExport = Boolean(utils.findProperty(node, 'emits'))
104+
}
105+
}),
106+
{
107+
'Program:exit'() {
108+
if (!defineEmitsNodes.length) {
109+
return
110+
}
111+
if (defineEmitsNodes.length > 1) {
112+
// `defineEmits` has been called multiple times.
113+
for (const node of defineEmitsNodes) {
114+
context.report({
115+
node,
116+
messageId: 'multiple'
117+
})
118+
}
119+
return
120+
}
121+
if (emptyDefineEmits) {
122+
if (!hasDefaultExport) {
123+
// Custom events are not defined.
124+
context.report({
125+
node: emptyDefineEmits,
126+
messageId: 'notDefined'
127+
})
128+
}
129+
} else {
130+
if (hasDefaultExport) {
131+
// Custom events are defined in both `defineEmits` and `export default {}`.
132+
for (const node of defineEmitsNodes) {
133+
context.report({
134+
node,
135+
messageId: 'definedInBoth'
136+
})
137+
}
138+
}
139+
}
140+
}
141+
}
142+
)
143+
}
144+
}

Diff for: lib/utils/index.js

+39-11
Original file line numberDiff line numberDiff line change
@@ -1058,16 +1058,26 @@ module.exports = {
10581058
const hasEmitsEvent =
10591059
visitor.onDefineEmitsEnter || visitor.onDefineEmitsExit
10601060
if (hasPropsEvent || hasEmitsEvent) {
1061-
/** @type {ESNode | null} */
1062-
let nested = null
1063-
scriptSetupVisitor[':function, BlockStatement'] = (node) => {
1064-
if (!nested) {
1065-
nested = node
1061+
/** @type {Expression | null} */
1062+
let candidateMacro = null
1063+
/** @param {VariableDeclarator|ExpressionStatement} node */
1064+
scriptSetupVisitor[
1065+
'Program > VariableDeclaration > VariableDeclarator, Program > ExpressionStatement'
1066+
] = (node) => {
1067+
if (!candidateMacro) {
1068+
candidateMacro =
1069+
node.type === 'VariableDeclarator' ? node.init : node.expression
10661070
}
10671071
}
1068-
scriptSetupVisitor[':function, BlockStatement:exit'] = (node) => {
1069-
if (nested === node) {
1070-
nested = null
1072+
/** @param {VariableDeclarator|ExpressionStatement} node */
1073+
scriptSetupVisitor[
1074+
'Program > VariableDeclaration > VariableDeclarator, Program > ExpressionStatement:exit'
1075+
] = (node) => {
1076+
if (
1077+
candidateMacro ===
1078+
(node.type === 'VariableDeclarator' ? node.init : node.expression)
1079+
) {
1080+
candidateMacro = null
10711081
}
10721082
}
10731083
const definePropsMap = new Map()
@@ -1077,11 +1087,16 @@ module.exports = {
10771087
*/
10781088
scriptSetupVisitor.CallExpression = (node) => {
10791089
if (
1080-
!nested &&
1090+
candidateMacro &&
10811091
inScriptSetup(node) &&
10821092
node.callee.type === 'Identifier'
10831093
) {
1084-
if (hasPropsEvent && node.callee.name === 'defineProps') {
1094+
if (
1095+
hasPropsEvent &&
1096+
(candidateMacro === node ||
1097+
candidateMacro === getWithDefaults(node)) &&
1098+
node.callee.name === 'defineProps'
1099+
) {
10851100
/** @type {(ComponentArrayProp | ComponentObjectProp | ComponentTypeProp)[]} */
10861101
let props = []
10871102
if (node.arguments.length >= 1) {
@@ -1100,7 +1115,11 @@ module.exports = {
11001115
}
11011116
callVisitor('onDefinePropsEnter', node, props)
11021117
definePropsMap.set(node, props)
1103-
} else if (hasEmitsEvent && node.callee.name === 'defineEmits') {
1118+
} else if (
1119+
hasEmitsEvent &&
1120+
candidateMacro === node &&
1121+
node.callee.name === 'defineEmits'
1122+
) {
11041123
/** @type {(ComponentArrayEmit | ComponentObjectEmit | ComponentTypeEmit)[]} */
11051124
let emits = []
11061125
if (node.arguments.length >= 1) {
@@ -2400,6 +2419,15 @@ function hasWithDefaults(node) {
24002419
)
24012420
}
24022421

2422+
/**
2423+
* Get the withDefaults call node from given defineProps call node.
2424+
* @param {CallExpression} node The node of defineProps
2425+
* @returns {CallExpression | null}
2426+
*/
2427+
function getWithDefaults(node) {
2428+
return hasWithDefaults(node) ? node.parent : null
2429+
}
2430+
24032431
/**
24042432
* Get all props by looking at all component's properties
24052433
* @param {ObjectExpression|ArrayExpression} propsNode Object with props definition

0 commit comments

Comments
 (0)