prefer-read-only-props.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @fileoverview Require component props to be typed as read-only.
  3. * @author Luke Zapart
  4. */
  5. 'use strict';
  6. const flatMap = require('array.prototype.flatmap');
  7. const values = require('object.values');
  8. const Components = require('../util/Components');
  9. const docsUrl = require('../util/docsUrl');
  10. const report = require('../util/report');
  11. function isFlowPropertyType(node) {
  12. return node.type === 'ObjectTypeProperty';
  13. }
  14. function isCovariant(node) {
  15. return (node.variance && node.variance.kind === 'plus')
  16. || (
  17. node.parent
  18. && node.parent.parent
  19. && node.parent.parent.parent
  20. && node.parent.parent.parent.id
  21. && node.parent.parent.parent.id.name === '$ReadOnly'
  22. );
  23. }
  24. // ------------------------------------------------------------------------------
  25. // Rule Definition
  26. // ------------------------------------------------------------------------------
  27. const messages = {
  28. readOnlyProp: 'Prop \'{{name}}\' should be read-only.',
  29. };
  30. module.exports = {
  31. meta: {
  32. docs: {
  33. description: 'Enforce that props are read-only',
  34. category: 'Stylistic Issues',
  35. recommended: false,
  36. url: docsUrl('prefer-read-only-props'),
  37. },
  38. fixable: 'code',
  39. messages,
  40. schema: [],
  41. },
  42. create: Components.detect((context, components) => ({
  43. 'Program:exit'() {
  44. flatMap(
  45. values(components.list()),
  46. (component) => component.declaredPropTypes || []
  47. ).forEach((declaredPropTypes) => {
  48. Object.keys(declaredPropTypes).forEach((propName) => {
  49. const prop = declaredPropTypes[propName];
  50. if (!prop.node || !isFlowPropertyType(prop.node)) {
  51. return;
  52. }
  53. if (!isCovariant(prop.node)) {
  54. report(context, messages.readOnlyProp, 'readOnlyProp', {
  55. node: prop.node,
  56. data: {
  57. name: propName,
  58. },
  59. fix: (fixer) => {
  60. if (!prop.node.variance) {
  61. // Insert covariance
  62. return fixer.insertTextBefore(prop.node, '+');
  63. }
  64. // Replace contravariance with covariance
  65. return fixer.replaceText(prop.node.variance, '+');
  66. },
  67. });
  68. }
  69. });
  70. });
  71. },
  72. })),
  73. };