All files / fast-redact/lib restorer.js

100% Statements 18/18
100% Branches 8/8
100% Functions 6/6
100% Lines 17/17

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    1x   1x     66x 82x 64x 49x 64x 64x 64x   64x               64x 49x 49x     49x 49x               64x                       64x              
'use strict'
 
const { groupRestore, nestedRestore } = require('./modifiers')
 
module.exports = restorer
 
function restorer ({secret, wcLen}) {
  return function compileRestore () {
    if (this.restore) return
    const paths = Object.keys(secret)
      .filter((path) => secret[path].precensored === false)
    const resetters = resetTmpl(secret, paths)
    const hasWildcards = wcLen > 0
    const state = hasWildcards ? {secret, groupRestore, nestedRestore} : {secret}
    /* eslint-disable-next-line */
    this.restore = Function(
      'o',
      restoreTmpl(resetters, paths, hasWildcards)
    ).bind(state)
  }
}
 
function resetTmpl (secret, paths) {
  return paths.map((path) => {
    const { circle, escPath } = secret[path]
    const reset = circle
      ? `o.${circle} = secret[${escPath}].val`
      : `o.${path} = secret[${escPath}].val`
    const clear = `secret[${escPath}].val = null`
    return `
      try { ${reset} } catch (e) {}
      ${clear}
    `
  }).join('')
}
 
function restoreTmpl (resetters, paths, hasWildcards) {
  const dynamicReset = hasWildcards === true ? `
    const keys = Object.keys(secret)
    const len = keys.length
    for (var i = ${paths.length}; i < len; i++) {
      const k = keys[i]
      const o = secret[k]
      if (o.flat === true) this.groupRestore(o)
      else this.nestedRestore(o)
      secret[k] = null
    }
  ` : ''
 
  return `
    const secret = this.secret
    ${resetters}
    ${dynamicReset}
    return o
  `
}