all files / liquidjs/src/ scope.js

100% Statements 104/104
100% Branches 42/42
100% Functions 16/16
100% Lines 103/103
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           288× 288×   28×         56× 56× 56×     106× 105×     95×     56× 56× 38×   56× 32×   56×               288× 285×   284× 284× 262×   69×   67×                             295× 295× 295× 295× 295× 1588×   27×   27× 27×   21× 21× 20× 20×   20× 20×   24×   56× 56× 56×   1505× 1505×     292× 292×   399× 399×         56× 56× 60× 60×       59× 55×             67×         284× 301× 301× 262×     22×     21× 21× 78×   78× 22× 22× 20×           333×             333× 333× 333× 333×    
const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
 
var Scope = {
  getAll: function () {
    var ctx = {}
    for (var i = this.scopes.length - 1; i >= 0; i--) {
      _.assign(ctx, this.scopes[i])
    }
    return ctx
  },
  get: function (str) {
    try {
      return this.getPropertyByPath(this.scopes, str)
    } catch (e) {
      if (!/undefined variable/.test(e.message) || this.opts.strict_variables) {
        throw e
      }
    }
  },
  set: function (k, v) {
    var scope = this.findScopeFor(k)
    setPropertyByPath(scope, k, v)
    return this
  },
  push: function (ctx) {
    assert(ctx, `trying to push ${ctx} into scopes`)
    return this.scopes.push(ctx)
  },
  pop: function () {
    return this.scopes.pop()
  },
  findScopeFor: function (key) {
    var i = this.scopes.length - 1
    while (i >= 0 && !(key in this.scopes[i])) {
      i--
    }
    if (i < 0) {
      i = this.scopes.length - 1
    }
    return this.scopes[i]
  },
  unshift: function (ctx) {
    assert(ctx, `trying to push ${ctx} into scopes`)
    return this.scopes.unshift(ctx)
  },
  shift: function () {
    return this.scopes.shift()
  },
 
  getPropertyByPath: function (scopes, path) {
    var paths = this.propertyAccessSeq(path + '')
    if (!paths.length) {
      throw new TypeError('undefined variable: ' + path)
    }
    var key = paths.shift()
    var value = getValueFromScopes(key, scopes)
    return paths.reduce(
      (value, key) => {
        if (_.isNil(value)) {
          throw new TypeError('undefined variable: ' + key)
        }
        return getValueFromParent(key, value)
      },
      value
    )
  },
 
  /*
   * Parse property access sequence from access string
   * @example
   * accessSeq("foo.bar")            // ['foo', 'bar']
   * accessSeq("foo['bar']")      // ['foo', 'bar']
   * accessSeq("foo['b]r']")      // ['foo', 'b]r']
   * accessSeq("foo[bar.coo]")    // ['foo', 'bar'], for bar.coo == 'bar'
   */
  propertyAccessSeq: function (str) {
    var seq = []
    var name = ''
    var j
    var i = 0
    while (i < str.length) {
      switch (str[i]) {
        case '[':
          push()
 
          var delemiter = str[i + 1]
          if (/['"]/.test(delemiter)) { // foo["bar"]
            j = str.indexOf(delemiter, i + 2)
            assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
            name = str.slice(i + 2, j)
            push()
            i = j + 2
          } else { // foo[bar.coo]
            j = matchRightBracket(str, i + 1)
            assert(j !== -1, `unbalanced []: ${str}`)
            name = str.slice(i + 1, j)
            if (!lexical.isInteger(name)) { // foo[bar] vs. foo[1]
              name = this.get(name)
            }
            push()
            i = j + 1
          }
          break
        case '.':// foo.bar, foo[0].bar
          push()
          i++
          break
        default:// foo.bar
          name += str[i]
          i++
      }
    }
    push()
    return seq
 
    function push () {
      if (name.length) seq.push(name)
      name = ''
    }
  }
}
 
function setPropertyByPath (obj, path, val) {
  var paths = (path + '').replace(/\[/g, '.').replace(/\]/g, '').split('.')
  for (var i = 0; i < paths.length; i++) {
    var key = paths[i]
    if (!_.isObject(obj)) {
      // cannot set property of non-object
      return
    }
    // for end point
    if (i === paths.length - 1) {
      return (obj[key] = val)
    }
    // if path not exist
    if (undefined === obj[key]) {
      obj[key] = {}
    }
    obj = obj[key]
  }
}
 
function getValueFromParent (key, value) {
  return (key === 'size' && (_.isArray(value) || _.isString(value)))
    ? value.length
    : value[key]
}
 
function getValueFromScopes (key, scopes) {
  for (var i = scopes.length - 1; i > -1; i--) {
    var scope = scopes[i]
    if (scope.hasOwnProperty(key)) {
      return scope[key]
    }
  }
  throw new TypeError('undefined variable: ' + key)
}
 
function matchRightBracket (str, begin) {
  var stack = 1 // count of '[' - count of ']'
  for (var i = begin; i < str.length; i++) {
    if (str[i] === '[') {
      stack++
    }
    if (str[i] === ']') {
      stack--
      if (stack === 0) {
        return i
      }
    }
  }
  return -1
}
 
exports.factory = function (ctx, opts) {
  var defaultOptions = {
    dynamicPartials: true,
    strict_variables: false,
    strict_filters: false,
    blocks: {},
    root: []
  }
  var scope = Object.create(Scope)
  scope.opts = _.assign(defaultOptions, opts)
  scope.scopes = [ctx || {}]
  return scope
}