no-mutating-props.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /**
  2. * @fileoverview disallow mutation component props
  3. * @author 2018 Armano
  4. */
  5. 'use strict'
  6. /**
  7. * @typedef {{name?: string, set: Set<string>}} PropsInfo
  8. */
  9. const utils = require('../utils')
  10. const { findVariable } = require('@eslint-community/eslint-utils')
  11. // https://github.com/vuejs/vue-next/blob/7c11c58faf8840ab97b6449c98da0296a60dddd8/packages/shared/src/globalsWhitelist.ts
  12. const GLOBALS_WHITE_LISTED = new Set([
  13. 'Infinity',
  14. 'undefined',
  15. 'NaN',
  16. 'isFinite',
  17. 'isNaN',
  18. 'parseFloat',
  19. 'parseInt',
  20. 'decodeURI',
  21. 'decodeURIComponent',
  22. 'encodeURI',
  23. 'encodeURIComponent',
  24. 'Math',
  25. 'Number',
  26. 'Date',
  27. 'Array',
  28. 'Object',
  29. 'Boolean',
  30. 'String',
  31. 'RegExp',
  32. 'Map',
  33. 'Set',
  34. 'JSON',
  35. 'Intl',
  36. 'BigInt'
  37. ])
  38. /**
  39. * @param {ASTNode} node
  40. * @returns {VExpressionContainer}
  41. */
  42. function getVExpressionContainer(node) {
  43. let n = node
  44. while (n.type !== 'VExpressionContainer') {
  45. n = /** @type {ASTNode} */ (n.parent)
  46. }
  47. return n
  48. }
  49. /**
  50. * @param {ASTNode} node
  51. * @returns {node is Identifier}
  52. */
  53. function isVmReference(node) {
  54. if (node.type !== 'Identifier') {
  55. return false
  56. }
  57. const parent = node.parent
  58. if (parent.type === 'MemberExpression') {
  59. if (parent.property === node) {
  60. // foo.id
  61. return false
  62. }
  63. } else if (
  64. parent.type === 'Property' &&
  65. parent.key === node &&
  66. !parent.computed
  67. ) {
  68. // {id: foo}
  69. return false
  70. }
  71. const exprContainer = getVExpressionContainer(node)
  72. for (const reference of exprContainer.references) {
  73. if (reference.variable != null) {
  74. // Not vm reference
  75. continue
  76. }
  77. if (reference.id === node) {
  78. return true
  79. }
  80. }
  81. return false
  82. }
  83. /**
  84. * @param { object } options
  85. * @param { boolean } options.shallowOnly Enables mutating the value of a prop but leaving the reference the same
  86. */
  87. function parseOptions(options) {
  88. return Object.assign(
  89. {
  90. shallowOnly: false
  91. },
  92. options
  93. )
  94. }
  95. module.exports = {
  96. meta: {
  97. type: 'suggestion',
  98. docs: {
  99. description: 'disallow mutation of component props',
  100. categories: ['vue3-essential', 'essential'],
  101. url: 'https://eslint.vuejs.org/rules/no-mutating-props.html'
  102. },
  103. fixable: null,
  104. schema: [
  105. {
  106. type: 'object',
  107. properties: {
  108. shallowOnly: {
  109. type: 'boolean'
  110. }
  111. },
  112. additionalProperties: false
  113. }
  114. ],
  115. messages: {
  116. unexpectedMutation: 'Unexpected mutation of "{{key}}" prop.'
  117. }
  118. },
  119. /** @param {RuleContext} context */
  120. create(context) {
  121. const { shallowOnly } = parseOptions(context.options[0])
  122. /** @type {Map<ObjectExpression|CallExpression, PropsInfo>} */
  123. const propsMap = new Map()
  124. /** @type { { type: 'export' | 'mark' | 'definition', object: ObjectExpression } | { type: 'setup', object: CallExpression } | null } */
  125. let vueObjectData = null
  126. /**
  127. * @param {ASTNode} node
  128. * @param {string} name
  129. */
  130. function report(node, name) {
  131. context.report({
  132. node,
  133. messageId: 'unexpectedMutation',
  134. data: {
  135. key: name
  136. }
  137. })
  138. }
  139. /**
  140. * @param {MemberExpression|AssignmentProperty} node
  141. * @returns {string}
  142. */
  143. function getPropertyNameText(node) {
  144. const name = utils.getStaticPropertyName(node)
  145. if (name) {
  146. return name
  147. }
  148. if (node.computed) {
  149. const expr = node.type === 'Property' ? node.key : node.property
  150. const str = context.getSourceCode().getText(expr)
  151. return `[${str}]`
  152. }
  153. return '?unknown?'
  154. }
  155. /**
  156. * @param {MemberExpression|Identifier} props
  157. * @param {string} name
  158. * @param {boolean} isRootProps
  159. */
  160. function verifyMutating(props, name, isRootProps = false) {
  161. const invalid = utils.findMutating(props)
  162. if (invalid && isShallowOnlyInvalid(invalid, isRootProps)) {
  163. report(invalid.node, name)
  164. }
  165. }
  166. /**
  167. * @param {Pattern} param
  168. * @param {string[]} path
  169. * @returns {Generator<{ node: Identifier, path: string[] }>}
  170. */
  171. function* iteratePatternProperties(param, path) {
  172. if (!param) {
  173. return
  174. }
  175. switch (param.type) {
  176. case 'Identifier': {
  177. yield { node: param, path }
  178. break
  179. }
  180. case 'RestElement': {
  181. yield* iteratePatternProperties(param.argument, path)
  182. break
  183. }
  184. case 'AssignmentPattern': {
  185. yield* iteratePatternProperties(param.left, path)
  186. break
  187. }
  188. case 'ObjectPattern': {
  189. for (const prop of param.properties) {
  190. if (prop.type === 'Property') {
  191. const name = getPropertyNameText(prop)
  192. yield* iteratePatternProperties(prop.value, [...path, name])
  193. } else if (prop.type === 'RestElement') {
  194. yield* iteratePatternProperties(prop.argument, path)
  195. }
  196. }
  197. break
  198. }
  199. case 'ArrayPattern': {
  200. for (let index = 0; index < param.elements.length; index++) {
  201. const element = param.elements[index]
  202. yield* iteratePatternProperties(element, [...path, `${index}`])
  203. }
  204. break
  205. }
  206. }
  207. }
  208. /**
  209. * @param {Identifier} prop
  210. * @param {string[]} path
  211. */
  212. function verifyPropVariable(prop, path) {
  213. const variable = findVariable(context.getScope(), prop)
  214. if (!variable) {
  215. return
  216. }
  217. for (const reference of variable.references) {
  218. if (!reference.isRead()) {
  219. continue
  220. }
  221. const id = reference.identifier
  222. const invalid = utils.findMutating(id)
  223. if (!invalid) {
  224. continue
  225. }
  226. let name
  227. if (!isShallowOnlyInvalid(invalid, path.length === 0)) {
  228. continue
  229. }
  230. if (path.length === 0) {
  231. if (invalid.pathNodes.length === 0) {
  232. continue
  233. }
  234. const mem = invalid.pathNodes[0]
  235. name = getPropertyNameText(mem)
  236. } else {
  237. if (invalid.pathNodes.length === 0 && invalid.kind !== 'call') {
  238. continue
  239. }
  240. name = path[0]
  241. }
  242. report(invalid.node, name)
  243. }
  244. }
  245. function* extractDefineVariableNames() {
  246. const globalScope = context.getSourceCode().scopeManager.globalScope
  247. if (globalScope) {
  248. for (const variable of globalScope.variables) {
  249. if (variable.defs.length > 0) {
  250. yield variable.name
  251. }
  252. }
  253. const moduleScope = globalScope.childScopes.find(
  254. (scope) => scope.type === 'module'
  255. )
  256. for (const variable of (moduleScope && moduleScope.variables) || []) {
  257. if (variable.defs.length > 0) {
  258. yield variable.name
  259. }
  260. }
  261. }
  262. }
  263. /**
  264. * Is shallowOnly false or the prop reassigned
  265. * @param {Exclude<ReturnType<typeof utils.findMutating>, null>} invalid
  266. * @param {boolean} isRootProps
  267. * @return {boolean}
  268. */
  269. function isShallowOnlyInvalid(invalid, isRootProps) {
  270. return (
  271. !shallowOnly ||
  272. (invalid.pathNodes.length === (isRootProps ? 1 : 0) &&
  273. ['assignment', 'update'].includes(invalid.kind))
  274. )
  275. }
  276. return utils.compositingVisitors(
  277. {},
  278. utils.defineScriptSetupVisitor(context, {
  279. onDefinePropsEnter(node, props) {
  280. const defineVariableNames = new Set(extractDefineVariableNames())
  281. const propsInfo = {
  282. name: '',
  283. set: new Set(
  284. props
  285. .map((p) => p.propName)
  286. .filter(
  287. /**
  288. * @returns {propName is string}
  289. */
  290. (propName) =>
  291. utils.isDef(propName) &&
  292. !GLOBALS_WHITE_LISTED.has(propName) &&
  293. !defineVariableNames.has(propName)
  294. )
  295. )
  296. }
  297. propsMap.set(node, propsInfo)
  298. vueObjectData = {
  299. type: 'setup',
  300. object: node
  301. }
  302. let target = node
  303. if (
  304. target.parent &&
  305. target.parent.type === 'CallExpression' &&
  306. target.parent.arguments[0] === target &&
  307. target.parent.callee.type === 'Identifier' &&
  308. target.parent.callee.name === 'withDefaults'
  309. ) {
  310. target = target.parent
  311. }
  312. if (
  313. !target.parent ||
  314. target.parent.type !== 'VariableDeclarator' ||
  315. target.parent.init !== target
  316. ) {
  317. return
  318. }
  319. for (const { node: prop, path } of iteratePatternProperties(
  320. target.parent.id,
  321. []
  322. )) {
  323. if (path.length === 0) {
  324. propsInfo.name = prop.name
  325. } else {
  326. propsInfo.set.add(prop.name)
  327. }
  328. verifyPropVariable(prop, path)
  329. }
  330. }
  331. }),
  332. utils.defineVueVisitor(context, {
  333. onVueObjectEnter(node) {
  334. propsMap.set(node, {
  335. set: new Set(
  336. utils
  337. .getComponentPropsFromOptions(node)
  338. .map((p) => p.propName)
  339. .filter(utils.isDef)
  340. )
  341. })
  342. },
  343. onVueObjectExit(node, { type }) {
  344. if (
  345. (!vueObjectData ||
  346. (vueObjectData.type !== 'export' &&
  347. vueObjectData.type !== 'setup')) &&
  348. type !== 'instance'
  349. ) {
  350. vueObjectData = {
  351. type,
  352. object: node
  353. }
  354. }
  355. },
  356. onSetupFunctionEnter(node) {
  357. const propsParam = node.params[0]
  358. if (!propsParam) {
  359. // no arguments
  360. return
  361. }
  362. if (
  363. propsParam.type === 'RestElement' ||
  364. propsParam.type === 'ArrayPattern'
  365. ) {
  366. // cannot check
  367. return
  368. }
  369. for (const { node: prop, path } of iteratePatternProperties(
  370. propsParam,
  371. []
  372. )) {
  373. verifyPropVariable(prop, path)
  374. }
  375. },
  376. /** @param {(Identifier | ThisExpression) & { parent: MemberExpression } } node */
  377. 'MemberExpression > :matches(Identifier, ThisExpression)'(
  378. node,
  379. { node: vueNode }
  380. ) {
  381. if (!utils.isThis(node, context)) {
  382. return
  383. }
  384. const mem = node.parent
  385. if (mem.object !== node) {
  386. return
  387. }
  388. const name = utils.getStaticPropertyName(mem)
  389. if (
  390. name &&
  391. /** @type {PropsInfo} */ (propsMap.get(vueNode)).set.has(name)
  392. ) {
  393. verifyMutating(mem, name)
  394. }
  395. }
  396. }),
  397. utils.defineTemplateBodyVisitor(context, {
  398. /** @param {ThisExpression & { parent: MemberExpression } } node */
  399. 'VExpressionContainer MemberExpression > ThisExpression'(node) {
  400. if (!vueObjectData) {
  401. return
  402. }
  403. const mem = node.parent
  404. if (mem.object !== node) {
  405. return
  406. }
  407. const name = utils.getStaticPropertyName(mem)
  408. if (
  409. name &&
  410. /** @type {PropsInfo} */ (
  411. propsMap.get(vueObjectData.object)
  412. ).set.has(name)
  413. ) {
  414. verifyMutating(mem, name)
  415. }
  416. },
  417. /** @param {Identifier } node */
  418. 'VExpressionContainer Identifier'(node) {
  419. if (!vueObjectData) {
  420. return
  421. }
  422. if (!isVmReference(node)) {
  423. return
  424. }
  425. const propsInfo = /** @type {PropsInfo} */ (
  426. propsMap.get(vueObjectData.object)
  427. )
  428. const isRootProps = !!node.name && propsInfo.name === node.name
  429. const parent = node.parent
  430. const name =
  431. (isRootProps &&
  432. parent.type === 'MemberExpression' &&
  433. utils.getStaticPropertyName(parent)) ||
  434. node.name
  435. if (name && (propsInfo.set.has(name) || isRootProps)) {
  436. verifyMutating(node, name, isRootProps)
  437. }
  438. },
  439. /** @param {ESNode} node */
  440. "VAttribute[directive=true]:matches([key.name.name='model'], [key.name.name='bind']) VExpressionContainer > *"(
  441. node
  442. ) {
  443. if (!vueObjectData) {
  444. return
  445. }
  446. let attr = node.parent
  447. while (attr && attr.type !== 'VAttribute') {
  448. attr = attr.parent
  449. }
  450. if (
  451. attr &&
  452. attr.directive &&
  453. attr.key.name.name === 'bind' &&
  454. !attr.key.modifiers.some((mod) => mod.name === 'sync')
  455. ) {
  456. return
  457. }
  458. const propsInfo = /** @type {PropsInfo} */ (
  459. propsMap.get(vueObjectData.object)
  460. )
  461. const nodes = utils.getMemberChaining(node)
  462. const first = nodes[0]
  463. let name
  464. if (isVmReference(first)) {
  465. if (first.name === propsInfo.name) {
  466. // props variable
  467. if (shallowOnly && nodes.length > 2) {
  468. return
  469. }
  470. name = (nodes[1] && getPropertyNameText(nodes[1])) || first.name
  471. } else {
  472. if (shallowOnly && nodes.length > 1) {
  473. return
  474. }
  475. name = first.name
  476. if (!name || !propsInfo.set.has(name)) {
  477. return
  478. }
  479. }
  480. } else if (first.type === 'ThisExpression') {
  481. if (shallowOnly && nodes.length > 2) {
  482. return
  483. }
  484. const mem = nodes[1]
  485. if (!mem) {
  486. return
  487. }
  488. name = utils.getStaticPropertyName(mem)
  489. if (!name || !propsInfo.set.has(name)) {
  490. return
  491. }
  492. } else {
  493. return
  494. }
  495. report(node, name)
  496. }
  497. })
  498. )
  499. }
  500. }