all files / liquidjs/src/ scope.js

100% Statements 97/97
100% Branches 44/44
100% Functions 11/11
100% Lines 93/93
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          325× 321× 407×     57× 57× 57× 63×   62× 56× 56×           133× 132×     123× 32×   181× 91×   90×     378× 378× 74×   378× 52×   378×     407× 407× 405×   403×   407×   401×                       389× 389× 389× 389× 389× 389× 2209×   27×   27× 27×   21× 21× 20× 20×   20× 20×   24×   79× 79× 79×   2103× 2103×     386×   386×   385×   516× 516×         21× 21× 78×   78× 22× 22× 20×           375×             375× 375× 375× 375×    
'use strict'
const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
 
var Scope = {
  getAll: function () {
    return this.scopes.reduce((ctx, val) => Object.assign(ctx, val), Object.create(null))
  },
  get: function (path) {
    let paths = this.propertyAccessSeq(path)
    let scope = this.findScopeFor(paths[0])
    return paths.reduce((value, key) => this.readProperty(value, key), scope)
  },
  set: function (path, v) {
    let paths = this.propertyAccessSeq(path)
    let scope = this.findScopeFor(paths[0])
    paths.some((key, i) => {
      if (!_.isObject(scope)) {
        return true
      }
      if (i === paths.length - 1) {
        scope[key] = v
        return true
      }
      if (undefined === scope[key]) {
        scope[key] = {}
      }
      scope = scope[key]
    })
  },
  push: function (ctx) {
    assert(ctx, `trying to push ${ctx} into scopes`)
    this.scopes.push(ctx)
  },
  pop: function (ctx) {
    if (!arguments.length) {
      return this.scopes.pop()
    }
    let i = this.scopes.findIndex(scope => scope === ctx)
    if (i === -1) {
      throw new TypeError('scope not found, cannot pop')
    }
    return this.scopes.splice(i, 1)[0]
  },
  findScopeFor: function (key) {
    let 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]
  },
  readProperty: function (obj, key) {
    let val
    if (key === 'size' && (_.isArray(obj) || _.isString(obj))) {
      val = obj.length
    } else if (_.isNil(obj)) {
      val = undefined
    } else {
      val = obj[key]
    }
    if (_.isNil(val) && this.opts.strict_variables) {
      throw new TypeError(`undefined variable: ${key}`)
    }
    return val
  },
 
  /*
   * 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) {
    str = String(str)
    let seq = []
    let name = ''
    let j
    let i = 0
    while (i < str.length) {
      switch (str[i]) {
        case '[':
          push()
 
          let 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()
 
    if (!seq.length) {
      throw new TypeError(`invalid path:"${str}"`)
    }
    return seq
 
    function push () {
      if (name.length) seq.push(name)
      name = ''
    }
  }
}
 
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
}