3822ff9c408199d20e0ec97cbfabac3580c39f4232376d7f678a79de44a100189d99f5a79584778279bf25fe124411befa7c61d9d549b9a93272f4a62bb988 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /**
  2. * @fileoverview require prop type to be a constructor
  3. * @author Michał Sajnóg
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const { isDef } = require('../utils')
  8. // ------------------------------------------------------------------------------
  9. // Rule Definition
  10. // ------------------------------------------------------------------------------
  11. const message = 'The "{{name}}" property should be a constructor.'
  12. const forbiddenTypes = [
  13. 'Literal',
  14. 'TemplateLiteral',
  15. 'BinaryExpression',
  16. 'UpdateExpression'
  17. ]
  18. /**
  19. * @param {ESNode} node
  20. */
  21. function isForbiddenType(node) {
  22. return (
  23. forbiddenTypes.indexOf(node.type) > -1 &&
  24. !(node.type === 'Literal' && node.value == null && !node.bigint)
  25. )
  26. }
  27. module.exports = {
  28. meta: {
  29. type: 'suggestion',
  30. docs: {
  31. description: 'require prop type to be a constructor',
  32. categories: ['vue3-essential', 'essential'],
  33. url: 'https://eslint.vuejs.org/rules/require-prop-type-constructor.html'
  34. },
  35. fixable: 'code', // or "code" or "whitespace"
  36. schema: []
  37. },
  38. /** @param {RuleContext} context */
  39. create(context) {
  40. /**
  41. * @param {string} propName
  42. * @param {ESNode} node
  43. */
  44. function checkPropertyNode(propName, node) {
  45. /** @type {ESNode[]} */
  46. const nodes =
  47. node.type === 'ArrayExpression' ? node.elements.filter(isDef) : [node]
  48. nodes
  49. .filter((prop) => isForbiddenType(prop))
  50. .forEach((prop) =>
  51. context.report({
  52. node: prop,
  53. message,
  54. data: {
  55. name: propName
  56. },
  57. fix: (fixer) => {
  58. if (prop.type === 'Literal' || prop.type === 'TemplateLiteral') {
  59. const newText = utils.getStringLiteralValue(prop, true)
  60. if (newText) {
  61. return fixer.replaceText(prop, newText)
  62. }
  63. }
  64. return null
  65. }
  66. })
  67. )
  68. }
  69. return utils.executeOnVueComponent(context, (obj) => {
  70. for (const prop of utils.getComponentProps(obj)) {
  71. if (!prop.value || prop.propName == null) {
  72. continue
  73. }
  74. if (
  75. isForbiddenType(prop.value) ||
  76. prop.value.type === 'ArrayExpression'
  77. ) {
  78. checkPropertyNode(prop.propName, prop.value)
  79. } else if (prop.value.type === 'ObjectExpression') {
  80. const typeProperty = utils.findProperty(prop.value, 'type')
  81. if (!typeProperty) continue
  82. checkPropertyNode(prop.propName, typeProperty.value)
  83. }
  84. }
  85. })
  86. }
  87. }