no-hex-escape.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const {replaceTemplateElement} = require('./fix/index.js');
  3. const MESSAGE_ID = 'no-hex-escape';
  4. const messages = {
  5. [MESSAGE_ID]: 'Use Unicode escapes instead of hexadecimal escapes.',
  6. };
  7. function checkEscape(context, node, value) {
  8. const fixedValue = value.replace(/(?<=(?:^|[^\\])(?:\\\\)*\\)x/g, 'u00');
  9. if (value !== fixedValue) {
  10. return {
  11. node,
  12. messageId: MESSAGE_ID,
  13. fix: fixer =>
  14. node.type === 'TemplateElement'
  15. ? replaceTemplateElement(fixer, node, fixedValue)
  16. : fixer.replaceText(node, fixedValue),
  17. };
  18. }
  19. }
  20. /** @param {import('eslint').Rule.RuleContext} context */
  21. const create = context => ({
  22. Literal(node) {
  23. if (node.regex || typeof node.value === 'string') {
  24. return checkEscape(context, node, node.raw);
  25. }
  26. },
  27. TemplateElement: node => checkEscape(context, node, node.value.raw),
  28. });
  29. /** @type {import('eslint').Rule.RuleModule} */
  30. module.exports = {
  31. create,
  32. meta: {
  33. type: 'suggestion',
  34. docs: {
  35. description: 'Enforce the use of Unicode escapes instead of hexadecimal escapes.',
  36. },
  37. fixable: 'code',
  38. messages,
  39. },
  40. };