isSyntacticallyValidPropertyValue.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. Object.defineProperty(exports, // Arbitrary values must contain balanced brackets (), [] and {}. Escaped
  6. // values don't count, and brackets inside quotes also don't count.
  7. //
  8. // E.g.: w-[this-is]w-[weird-and-invalid]
  9. // E.g.: w-[this-is\\]w-\\[weird-but-valid]
  10. // E.g.: content-['this-is-also-valid]-weirdly-enough']
  11. "default", {
  12. enumerable: true,
  13. get: function() {
  14. return isSyntacticallyValidPropertyValue;
  15. }
  16. });
  17. let matchingBrackets = new Map([
  18. [
  19. "{",
  20. "}"
  21. ],
  22. [
  23. "[",
  24. "]"
  25. ],
  26. [
  27. "(",
  28. ")"
  29. ]
  30. ]);
  31. let inverseMatchingBrackets = new Map(Array.from(matchingBrackets.entries()).map(([k, v])=>[
  32. v,
  33. k
  34. ]));
  35. let quotes = new Set([
  36. '"',
  37. "'",
  38. "`"
  39. ]);
  40. function isSyntacticallyValidPropertyValue(value) {
  41. let stack = [];
  42. let inQuotes = false;
  43. for(let i = 0; i < value.length; i++){
  44. let char = value[i];
  45. if (char === ":" && !inQuotes && stack.length === 0) {
  46. return false;
  47. }
  48. // Non-escaped quotes allow us to "allow" anything in between
  49. if (quotes.has(char) && value[i - 1] !== "\\") {
  50. inQuotes = !inQuotes;
  51. }
  52. if (inQuotes) continue;
  53. if (value[i - 1] === "\\") continue; // Escaped
  54. if (matchingBrackets.has(char)) {
  55. stack.push(char);
  56. } else if (inverseMatchingBrackets.has(char)) {
  57. let inverse = inverseMatchingBrackets.get(char);
  58. // Nothing to pop from, therefore it is unbalanced
  59. if (stack.length <= 0) {
  60. return false;
  61. }
  62. // Popped value must match the inverse value, otherwise it is unbalanced
  63. if (stack.pop() !== inverse) {
  64. return false;
  65. }
  66. }
  67. }
  68. // If there is still something on the stack, it is also unbalanced
  69. if (stack.length > 0) {
  70. return false;
  71. }
  72. // All good, totally balanced!
  73. return true;
  74. }