no-json-superset.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const { definePatternSearchGenerator } = require("../utils")
  7. const iterateTargetChars = definePatternSearchGenerator(/[\u2028\u2029]/gu)
  8. module.exports = {
  9. meta: {
  10. docs: {
  11. description: "disallow `\\u2028` and `\\u2029` in string literals.",
  12. category: "ES2019",
  13. recommended: false,
  14. url:
  15. "http://mysticatea.github.io/eslint-plugin-es/rules/no-json-superset.html",
  16. },
  17. fixable: "code",
  18. messages: {
  19. forbidden: "ES2019 '\\u{{code}}' in string literals is forbidden.",
  20. },
  21. schema: [],
  22. type: "problem",
  23. },
  24. create(context) {
  25. const sourceCode = context.getSourceCode()
  26. return {
  27. Literal(node) {
  28. if (typeof node.value !== "string") {
  29. return
  30. }
  31. const offset = node.range[0]
  32. for (const { index } of iterateTargetChars(node.raw)) {
  33. const code = node.raw.codePointAt(index).toString(16)
  34. const loc = sourceCode.getLocFromIndex(offset + index)
  35. context.report({
  36. node,
  37. loc,
  38. messageId: "forbidden",
  39. data: { code },
  40. fix(fixer) {
  41. return fixer.replaceTextRange(
  42. [offset + index, offset + index + 1],
  43. `\\u${code}`
  44. )
  45. },
  46. })
  47. }
  48. },
  49. }
  50. },
  51. }