All files / src get-script-to-run.js

100% Statements 24/24
100% Branches 16/16
100% Functions 5/5
100% Lines 24/24
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                25x     25x 25x 25x 19x       6x           31x   31x 26x 2x 1x   1x     26x 26x 26x 6x   26x         5x       34x 49x 5x 44x 9x     34x    
import {each, cloneDeep, isPlainObject, isUndefined, isString} from 'lodash'
import prefixMatches from 'prefix-matches'
import resolveScriptObjectToString from './resolve-script-object-to-string'
import kebabAndCamelCasify from './kebab-and-camel-casify'
 
export default getScriptToRun
 
function getScriptToRun(config, input) {
  config = kebabAndCamelCasify(config)
  // remove the default objects/strings so we cancheck
  // if the prefix works with another script first
  const defaultlessConfig = removeDefaults(cloneDeep(config))
  const scriptToRun = getScript(defaultlessConfig, input)
  if (!isUndefined(scriptToRun) && isString(scriptToRun.script)) {
    return scriptToRun
  } else {
    // fallback to the defaults if no other script was
    // found with the given input
    return getScript(config, input)
  }
}
 
function getScript(config, input) {
  // will always return an empty array if no result where found
  const matchingScripts = prefixMatches(input, config)
 
  if (matchingScripts.length !== 0) {
    const script = matchingScripts.reduce((script, possibleScript) => {
      if (possibleScript[input]) {
        return possibleScript
      }
      return script
    })
 
    const scriptName = Object.keys(script).shift()
    let scriptToRun = script[scriptName]
    if (scriptName && isPlainObject(scriptToRun)) {
      scriptToRun = resolveScriptObjectToString(scriptToRun)
    }
    return {
      scriptName,
      script: scriptToRun,
    }
  }
  return undefined
}
 
function removeDefaults(object) {
  each(object, (value, key) => {
    if (key === 'default') {
      delete object[key]
    } else if (isPlainObject(value)) {
      object[key] = removeDefaults(value)
    }
  })
  return object
}