regular-expressions.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @fileoverview Common utils for regular expressions.
  3. * @author Josh Goldberg
  4. * @author Toru Nagashima
  5. */
  6. "use strict";
  7. const { RegExpValidator } = require("@eslint-community/regexpp");
  8. const REGEXPP_LATEST_ECMA_VERSION = 2025;
  9. /**
  10. * Checks if the given regular expression pattern would be valid with the `u` flag.
  11. * @param {number} ecmaVersion ECMAScript version to parse in.
  12. * @param {string} pattern The regular expression pattern to verify.
  13. * @param {"u"|"v"} flag The type of Unicode flag
  14. * @returns {boolean} `true` if the pattern would be valid with the `u` flag.
  15. * `false` if the pattern would be invalid with the `u` flag or the configured
  16. * ecmaVersion doesn't support the `u` flag.
  17. */
  18. function isValidWithUnicodeFlag(ecmaVersion, pattern, flag = "u") {
  19. if (flag === "u" && ecmaVersion <= 5) {
  20. // ecmaVersion <= 5 doesn't support the 'u' flag
  21. return false;
  22. }
  23. if (flag === "v" && ecmaVersion <= 2023) {
  24. return false;
  25. }
  26. const validator = new RegExpValidator({
  27. ecmaVersion: Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION),
  28. });
  29. try {
  30. validator.validatePattern(
  31. pattern,
  32. void 0,
  33. void 0,
  34. flag === "u"
  35. ? {
  36. unicode: /* uFlag = */ true,
  37. }
  38. : {
  39. unicodeSets: true,
  40. },
  41. );
  42. } catch {
  43. return false;
  44. }
  45. return true;
  46. }
  47. module.exports = {
  48. isValidWithUnicodeFlag,
  49. REGEXPP_LATEST_ECMA_VERSION,
  50. };