-
-
Notifications
You must be signed in to change notification settings - Fork 681
/
Copy pathrequire-prop-types.js
126 lines (119 loc) · 3.11 KB
/
require-prop-types.js
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
/**
* @fileoverview Prop definitions should be detailed
* @author Armano
*/
'use strict'
const utils = require('../utils')
/**
* @typedef {import('../utils').ComponentProp} ComponentProp
*/
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'require type definitions in props',
categories: ['vue3-strongly-recommended', 'vue2-strongly-recommended'],
url: 'https://eslint.vuejs.org/rules/require-prop-types.html'
},
fixable: null,
schema: [],
messages: {
requireType: 'Prop "{{name}}" should define at least its type.'
}
},
/** @param {RuleContext} context */
create(context) {
/**
* @param {Expression} node
* @returns {boolean|null}
*/
function optionHasType(node) {
switch (node.type) {
case 'ObjectExpression': {
// foo: {
return objectHasType(node)
}
case 'ArrayExpression': {
// foo: [
return node.elements.length > 0
}
case 'FunctionExpression':
case 'ArrowFunctionExpression': {
return false
}
}
// Unknown
return null
}
/**
* @param {ObjectExpression} node
* @returns {boolean}
*/
function objectHasType(node) {
const typeProperty = node.properties.find(
(p) =>
p.type === 'Property' &&
utils.getStaticPropertyName(p) === 'type' &&
(p.value.type !== 'ArrayExpression' || p.value.elements.length > 0)
)
const validatorProperty = node.properties.find(
(p) =>
p.type === 'Property' &&
utils.getStaticPropertyName(p) === 'validator'
)
return Boolean(typeProperty || validatorProperty)
}
/**
* @param {ComponentProp} prop
*/
function checkProperty(prop) {
if (prop.type !== 'object' && prop.type !== 'array') {
return
}
const hasType =
prop.type === 'array' ? false : (optionHasType(prop.value) ?? true)
if (!hasType) {
const { node, propName } = prop
const name =
propName ||
(node.type === 'Identifier' && node.name) ||
'Unknown prop'
context.report({
node,
messageId: 'requireType',
data: {
name
}
})
}
}
return utils.compositingVisitors(
utils.defineScriptSetupVisitor(context, {
onDefinePropsEnter(_node, props) {
for (const prop of props) {
checkProperty(prop)
}
},
onDefineModelEnter(node, model) {
if (model.typeNode) return
if (model.options && (optionHasType(model.options) ?? true)) {
return
}
context.report({
node: model.options || node,
messageId: 'requireType',
data: {
name: model.name.modelName
}
})
}
}),
utils.executeOnVue(context, (obj) => {
const props = utils.getComponentPropsFromOptions(obj)
for (const prop of props) {
checkProperty(prop)
}
})
)
}
}