liusuyi
2023-04-24 4737f1e038743ced243c9e52423404d9034d6107
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
/**
 * @fileoverview disallow mutation component props
 * @author 2018 Armano
 */
'use strict'
 
const utils = require('../utils')
const { findVariable } = require('eslint-utils')
 
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
 
module.exports = {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'disallow mutation of component props',
      categories: ['vue3-essential', 'essential'],
      url: 'https://eslint.vuejs.org/rules/no-mutating-props.html'
    },
    fixable: null, // or "code" or "whitespace"
    schema: [
      // fill in your schema
    ]
  },
  /** @param {RuleContext} context */
  create(context) {
    /** @type {Map<ObjectExpression, Set<string>>} */
    const propsMap = new Map()
    /** @type { { type: 'export' | 'mark' | 'definition', object: ObjectExpression } | null } */
    let vueObjectData = null
 
    /**
     * @param {ASTNode} node
     * @param {string} name
     */
    function report(node, name) {
      context.report({
        node,
        message: 'Unexpected mutation of "{{key}}" prop.',
        data: {
          key: name
        }
      })
    }
 
    /**
     * @param {ASTNode} node
     * @returns {VExpressionContainer}
     */
    function getVExpressionContainer(node) {
      let n = node
      while (n.type !== 'VExpressionContainer') {
        n = /** @type {ASTNode} */ (n.parent)
      }
      return n
    }
    /**
     * @param {MemberExpression|AssignmentProperty} node
     * @returns {string}
     */
    function getPropertyNameText(node) {
      const name = utils.getStaticPropertyName(node)
      if (name) {
        return name
      }
      if (node.computed) {
        const expr = node.type === 'Property' ? node.key : node.property
        const str = context.getSourceCode().getText(expr)
        return `[${str}]`
      }
      return '?unknown?'
    }
    /**
     * @param {ASTNode} node
     * @returns {node is Identifier}
     */
    function isVmReference(node) {
      if (node.type !== 'Identifier') {
        return false
      }
      const parent = node.parent
      if (parent.type === 'MemberExpression') {
        if (parent.property === node) {
          // foo.id
          return false
        }
      } else if (parent.type === 'Property') {
        // {id: foo}
        if (parent.key === node && !parent.computed) {
          return false
        }
      }
 
      const exprContainer = getVExpressionContainer(node)
 
      for (const reference of exprContainer.references) {
        if (reference.variable != null) {
          // Not vm reference
          continue
        }
        if (reference.id === node) {
          return true
        }
      }
      return false
    }
 
    /**
     * @param {MemberExpression|Identifier} props
     * @param {string} name
     */
    function verifyMutating(props, name) {
      const invalid = utils.findMutating(props)
      if (invalid) {
        report(invalid.node, name)
      }
    }
 
    /**
     * @param {Pattern} param
     * @param {string[]} path
     * @returns {Generator<{ node: Identifier, path: string[] }>}
     */
    function* iterateParamProperties(param, path) {
      if (!param) {
        return
      }
      if (param.type === 'Identifier') {
        yield {
          node: param,
          path
        }
      } else if (param.type === 'RestElement') {
        yield* iterateParamProperties(param.argument, path)
      } else if (param.type === 'AssignmentPattern') {
        yield* iterateParamProperties(param.left, path)
      } else if (param.type === 'ObjectPattern') {
        for (const prop of param.properties) {
          if (prop.type === 'Property') {
            const name = getPropertyNameText(prop)
            yield* iterateParamProperties(prop.value, [...path, name])
          } else if (prop.type === 'RestElement') {
            yield* iterateParamProperties(prop.argument, path)
          }
        }
      } else if (param.type === 'ArrayPattern') {
        for (let index = 0; index < param.elements.length; index++) {
          const element = param.elements[index]
          yield* iterateParamProperties(element, [...path, `${index}`])
        }
      }
    }
 
    return Object.assign(
      {},
      utils.defineVueVisitor(context, {
        onVueObjectEnter(node) {
          propsMap.set(
            node,
            new Set(
              utils
                .getComponentProps(node)
                .map((p) => p.propName)
                .filter(utils.isDef)
            )
          )
        },
        onVueObjectExit(node, { type }) {
          if (
            (!vueObjectData || vueObjectData.type !== 'export') &&
            type !== 'instance'
          ) {
            vueObjectData = {
              type,
              object: node
            }
          }
        },
        onSetupFunctionEnter(node) {
          const propsParam = node.params[0]
          if (!propsParam) {
            // no arguments
            return
          }
          if (
            propsParam.type === 'RestElement' ||
            propsParam.type === 'ArrayPattern'
          ) {
            // cannot check
            return
          }
          for (const { node: prop, path } of iterateParamProperties(
            propsParam,
            []
          )) {
            const variable = findVariable(context.getScope(), prop)
            if (!variable) {
              continue
            }
 
            for (const reference of variable.references) {
              if (!reference.isRead()) {
                continue
              }
              const id = reference.identifier
 
              const invalid = utils.findMutating(id)
              if (!invalid) {
                continue
              }
              let name
              if (path.length === 0) {
                if (invalid.pathNodes.length === 0) {
                  continue
                }
                const mem = invalid.pathNodes[0]
                name = getPropertyNameText(mem)
              } else {
                if (invalid.pathNodes.length === 0 && invalid.kind !== 'call') {
                  continue
                }
                name = path[0]
              }
 
              report(invalid.node, name)
            }
          }
        },
        /** @param {(Identifier | ThisExpression) & { parent: MemberExpression } } node */
        'MemberExpression > :matches(Identifier, ThisExpression)'(
          node,
          { node: vueNode }
        ) {
          if (!utils.isThis(node, context)) {
            return
          }
          const mem = node.parent
          if (mem.object !== node) {
            return
          }
          const name = utils.getStaticPropertyName(mem)
          if (
            name &&
            /** @type {Set<string>} */ (propsMap.get(vueNode)).has(name)
          ) {
            verifyMutating(mem, name)
          }
        }
      }),
      utils.defineTemplateBodyVisitor(context, {
        /** @param {ThisExpression & { parent: MemberExpression } } node */
        'VExpressionContainer MemberExpression > ThisExpression'(node) {
          if (!vueObjectData) {
            return
          }
          const mem = node.parent
          if (mem.object !== node) {
            return
          }
          const name = utils.getStaticPropertyName(mem)
          if (
            name &&
            /** @type {Set<string>} */ (propsMap.get(vueObjectData.object)).has(
              name
            )
          ) {
            verifyMutating(mem, name)
          }
        },
        /** @param {Identifier } node */
        'VExpressionContainer Identifier'(node) {
          if (!vueObjectData) {
            return
          }
          if (!isVmReference(node)) {
            return
          }
          const name = node.name
          if (
            name &&
            /** @type {Set<string>} */ (propsMap.get(vueObjectData.object)).has(
              name
            )
          ) {
            verifyMutating(node, name)
          }
        },
        /** @param {ESNode} node */
        "VAttribute[directive=true][key.name.name='model'] VExpressionContainer > *"(
          node
        ) {
          if (!vueObjectData) {
            return
          }
          const nodes = utils.getMemberChaining(node)
          const first = nodes[0]
          let name
          if (isVmReference(first)) {
            name = first.name
          } else if (first.type === 'ThisExpression') {
            const mem = nodes[1]
            if (!mem) {
              return
            }
            name = utils.getStaticPropertyName(mem)
          } else {
            return
          }
          if (
            name &&
            /** @type {Set<string>} */ (propsMap.get(vueObjectData.object)).has(
              name
            )
          ) {
            report(node, name)
          }
        }
      })
    )
  }
}