All files / plugins/lib decl-validator.js

99.18% Statements 121/122
98.46% Branches 64/65
100% Functions 22/22
99.12% Lines 113/114

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 2399x 9x 9x   9x 9x   9x 44x 44x 44x 36x 7584x 11290x         44x   117x 1x   116x 116x   116x 116x               44x 44x 44x 116x 2454x       44x 75x 2x             2x   73x 73x 70x 70x 70x   3x         116x 551x 116x 116x 23972x 33866x 2272x       116x       129x       107x 107x 108x 37x           71x 41x 41x 42x   41x             30x 16x               14x 14x 36x 36x   25x 25x 25x     18x 14x 1x     17x 21x   13x 13x 21x 4x       13x 2x     13x                     9x 9x 17x 17x 17x 5x     12x   12x 12x 12x 50x 19x     31x   31x 31x 31x 24x 24x     31x 31x 30x 30x 23x       23x   30x 28x     1x       12x     12x 4x 4x   4x               8x                   204x         51x 51x 51x       75x 75x 204x      
const anymatch = require('anymatch')
const valueParser = require('postcss-value-parser')
const TapMap = require('tap-map')
 
const SKIP_VALUE_NODE_TYPES = new Set(['space', 'div'])
const SKIP_AT_RULE_NAMES = new Set(['each', 'for', 'function', 'mixin'])
 
module.exports = function declarationValidator(rules, options = {}) {
  const {formatMessage = defaultMessageFormatter, variables, verbose = false} = options
  const variableReplacements = new TapMap()
  if (variables) {
    for (const [name, {values}] of Object.entries(variables)) {
      for (const value of values) {
        variableReplacements.tap(value, () => []).push(name)
      }
    }
  }
 
  const validators = Object.entries(rules)
    .map(([key, rule]) => {
      if (rule === false) {
        return false
      }
      const {name = key, props = name, expects = `a ${name} value`} = rule
      const replacements = Object.assign({}, rule.replacements, getVariableReplacements(rule.values))
      // console.warn(`replacements for "${key}": ${JSON.stringify(replacements)}`)
      Object.assign(rule, {name, props, expects, replacements})
      return {
        rule,
        matchesProp: anymatch(props),
        validate: Array.isArray(rule.components) ? componentValidator(rule) : valueValidator(rule)
      }
    })
    .filter(Boolean)
 
  const validatorsByProp = new TapMap()
  const validatorsByReplacementValue = new Map()
  for (const validator of validators) {
    for (const value of Object.keys(validator.rule.replacements)) {
      validatorsByReplacementValue.set(value, validator)
    }
  }
 
  return decl => {
    if (closest(decl, isSkippableAtRule)) {
      Iif (verbose) {
        // eslint-disable-next-line no-console
        console.warn(`skipping declaration: ${decl.parent.toString()}`)
      }
      // As a general rule, any rule nested in an at-rule is ignored, since
      // @for, @each, @mixin, and @function blocks can use whatever variables
      // they want
      return {valid: true}
    }
    const validator = getPropValidator(decl.prop)
    if (validator) {
      const result = validator.validate(decl)
      result.errors = result.errors.map(formatMessage)
      return result
    } else {
      return {valid: true}
    }
  }
 
  function getVariableReplacements(values) {
    const replacements = {}
    const varValues = (Array.isArray(values) ? values : [values]).filter(v => typeof v === 'string' && v.includes('$'))
    const matches = anymatch(varValues)
    for (const [value, aliases] of variableReplacements.entries()) {
      for (const alias of aliases) {
        if (matches(alias)) {
          replacements[value] = alias
        }
      }
    }
    return replacements
  }
 
  function getPropValidator(prop) {
    return validatorsByProp.tap(prop, () => validators.find(v => v.matchesProp(prop)))
  }
 
  function valueValidator({expects, values, replacements, singular = false}) {
    const matches = anymatch(values)
    return function validate({prop, value}, nested) {
      if (matches(value)) {
        return {
          valid: true,
          errors: [],
          fixable: false,
          replacement: undefined
        }
      } else if (replacements[value]) {
        let replacement = value
        do {
          replacement = replacements[replacement]
        } while (replacements[replacement])
        return {
          valid: false,
          errors: [{expects, prop, value, replacement}],
          fixable: true,
          replacement
        }
      } else {
        if (nested || singular) {
          return {
            valid: false,
            errors: [{expects, prop, value}],
            fixable: false,
            replacement: undefined
          }
        }
 
        const parsed = valueParser(value)
        const validations = parsed.nodes
          .map((node, index) => Object.assign(node, {index}))
          .filter(node => !SKIP_VALUE_NODE_TYPES.has(node.type))
          .map(node => {
            const validation = validate({prop, value: valueParser.stringify(node)}, true)
            validation.index = node.index
            return validation
          })
 
        const valid = validations.every(v => v.valid)
        if (valid) {
          return {valid, errors: [], fixable: false, replacement: undefined}
        }
 
        const fixable = validations.some(v => v.fixable)
        const errors = validations.reduce((list, v) => list.concat(v.errors), [])
 
        let replacement = undefined
        for (const validation of validations) {
          if (fixable && validation.replacement) {
            parsed.nodes[validation.index] = {type: 'word', value: validation.replacement}
          }
        }
 
        if (fixable) {
          replacement = valueParser.stringify(parsed)
        }
 
        return {
          valid,
          fixable,
          errors,
          replacement
        }
      }
    }
  }
 
  function componentValidator({expects, components, values, replacements}) {
    const matchesCompoundValue = anymatch(values)
    return decl => {
      const {prop, value: compoundValue} = decl
      const parsed = valueParser(compoundValue)
      if (parsed.nodes.length === 1 && matchesCompoundValue(compoundValue)) {
        return {valid: true, errors: []}
      }
 
      const errors = []
 
      let fixable = false
      let componentIndex = 0
      for (const [index, node] of Object.entries(parsed.nodes)) {
        if (SKIP_VALUE_NODE_TYPES.has(node.type)) {
          continue
        }
 
        const value = valueParser.stringify(node)
 
        let componentProp = components[componentIndex++]
        let validator = getPropValidator(componentProp)
        if (validatorsByReplacementValue.has(value)) {
          validator = validatorsByReplacementValue.get(value)
          componentProp = validator.rule.name
        }
 
        const nestedProp = `${componentProp} (in ${prop})`
        if (validator) {
          const result = validator.validate({prop: nestedProp, value}, true)
          if (result.replacement) {
            parsed.nodes[index] = {
              type: 'word',
              value: result.replacement
            }
            fixable = true
          }
          for (const error of result.errors) {
            errors.push(error)
          }
        } else {
          errors.push({expects, prop: nestedProp, value})
        }
      }
 
      let replacement = fixable ? valueParser.stringify(parsed) : undefined
 
      // if a compound replacement exists, suggest *that* instead
      if (replacement && replacements[replacement]) {
        do {
          replacement = replacements[replacement]
        } while (replacements[replacement])
        return {
          valid: false,
          errors: [{expects, prop, value: compoundValue, replacement}],
          fixable: true,
          replacement
        }
      }
 
      return {
        valid: errors.length === 0,
        errors,
        fixable,
        replacement
      }
    }
  }
 
  function isSkippableAtRule(node) {
    return node.type === 'atrule' && SKIP_AT_RULE_NAMES.has(node.name)
  }
}
 
function defaultMessageFormatter(error) {
  const {expects, value, replacement} = error
  const expected = replacement ? `"${replacement}"` : expects
  return `Please use ${expected} instead of "${value}"`
}
 
function closest(node, test) {
  let ancestor = node
  do {
    if (test(ancestor)) return ancestor
  } while ((ancestor = ancestor.parent))
}