<commit_before>/**
 * Binding observer.fire to keydown event.
 */
document.addEventListener("keydown", function(event){keydown_observer.fire(event)}, false);

/**
 * KeyDown event observer.
 */
var keydown_observer = new function(){

    this.listeners = {};

    this.emulate_key = function(key_code){

        this.fire({"keyCode" : key_code});
    }

    this.fire = function(e){

        if (stb && stb.key_lock === true){
            _debug('key locked');
            return;
        }

        var code = e.keyCode || e.which;

        if (e.shiftKey){
            code += 1000;
        }

        if (e.altKey){
            code += 2000;
        }

        _debug('code:', code);

        var item;
        var priority_item;
        var normal_item;

        if (this.listeners.hasOwnProperty(code)){
            for(var i=0; i<this.listeners[code].length; i++){

                item = this.listeners[code][i];

                if (item.c.hasOwnProperty('con_menu')){
                    if (item.c.con_menu.on){
                        continue;
                    }
                }

                if (item.c.on && item.priority){
                    priority_item = item;
                    break;
                } else if (item.c.on || item.c === window){
                    if (!normal_item){
                        normal_item = item;
                    }
                }
            }

            if (priority_item){
                priority_item.f.apply(priority_item.c, priority_item.a);
            }else if (normal_item){
                normal_item.f.apply(normal_item.c, normal_item.a);
            }

        }
    }
}

/**
 * Binding function to key.
 * @param {number} key
 * @param {Object} context The object to be used as the value of 'this' within 'f'
 * @param {*} args
 * @return {Function}
 */
Function.prototype.bind = function(key, context, args){
    context = context || window;
    keydown_observer.listeners[key] = keydown_observer.listeners[key] || [];
    args = Array.prototype.splice.apply(arguments, [2, arguments.length]);
    keydown_observer.listeners[key].unshift({"f" : this, "c" : context, "a" : args});
    return this;
}

Function.prototype.priority_bind = function(key, context, args){
    context = context || window;
    keydown_observer.listeners[key] = keydown_observer.listeners[key] || [];
    args = Array.prototype.splice.apply(arguments, [2, arguments.length]);
    keydown_observer.listeners[key].unshift({"f" : this, "c" : context, "a" : args, "priority" : true});
    return this;
}<commit_msg>"Modify fire. If key.FRAME - not locked"<commit_after>/**
 * Binding observer.fire to keydown event.
 */
document.addEventListener("keydown", function(event){keydown_observer.fire(event)}, false);

/**
 * KeyDown event observer.
 */
var keydown_observer = new function(){

    this.listeners = {};

    this.emulate_key = function(key_code){

        this.fire({"keyCode" : key_code});
    }

    this.fire = function(e){

        var code = e.keyCode || e.which;

        if (stb && stb.key_lock === true && code != key.FRAME){
            _debug('key locked');
            return;
        }

        if (e.shiftKey){
            code += 1000;
        }

        if (e.altKey){
            code += 2000;
        }

        _debug('code:', code);

        var item;
        var priority_item;
        var normal_item;

        if (this.listeners.hasOwnProperty(code)){
            for(var i=0; i<this.listeners[code].length; i++){

                item = this.listeners[code][i];

                if (item.c.hasOwnProperty('con_menu')){
                    if (item.c.con_menu.on){
                        continue;
                    }
                }

                if (item.c.on && item.priority){
                    priority_item = item;
                    break;
                } else if (item.c.on || item.c === window){
                    if (!normal_item){
                        normal_item = item;
                    }
                }
            }

            if (priority_item){
                priority_item.f.apply(priority_item.c, priority_item.a);
            }else if (normal_item){
                normal_item.f.apply(normal_item.c, normal_item.a);
            }

        }
    }
}

/**
 * Binding function to key.
 * @param {number} key
 * @param {Object} context The object to be used as the value of 'this' within 'f'
 * @param {*} args
 * @return {Function}
 */
Function.prototype.bind = function(key, context, args){
    context = context || window;
    keydown_observer.listeners[key] = keydown_observer.listeners[key] || [];
    args = Array.prototype.splice.apply(arguments, [2, arguments.length]);
    keydown_observer.listeners[key].unshift({"f" : this, "c" : context, "a" : args});
    return this;
}

Function.prototype.priority_bind = function(key, context, args){
    context = context || window;
    keydown_observer.listeners[key] = keydown_observer.listeners[key] || [];
    args = Array.prototype.splice.apply(arguments, [2, arguments.length]);
    keydown_observer.listeners[key].unshift({"f" : this, "c" : context, "a" : args, "priority" : true});
    return this;
}<|endoftext|>


<commit_before>/**
 * Path-to-Regex - Express-style path to regexp
 *
 * Is a modified and google closure adapted implementation of
 * https://github.com/pillarjs/path-to-regexp
 * @author Andrey Antukh <niwi@niwi.nz>, 2016
 * @author Blake Embrey <hello@blakeembrey.com>, 2014
 * @license MIT License <https://opensource.org/licenses/MIT>
 */

"use strict";

goog.provide("bide.impl.path");

goog.scope(function() {
  var toString = Object.prototype.toString;
  var isArray = Array.isArray || function (val) {
    return !! val && '[object Array]' == toString.call(val);
  };

  /**
   * The main path matching regexp utility.
   *
   * @type {RegExp}
   */
  var PATH_REGEXP = new RegExp([
    // Match escaped characters that would otherwise appear in future matches.
    // This allows the user to escape special characters that won't transform.
    '(\\\\.)',
    // Match Express-style parameters and un-named parameters with a prefix
    // and optional suffixes. Matches appear as:
    //
    // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
    // "/route(\\d+)"  => [undefined, undefined, undefined, "\d+", undefined, undefined]
    // "/*"            => ["/", undefined, undefined, undefined, undefined, "*"]
    '([\\/.])?(?:(?:\\:([\\w\\-]+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  ].join('|'), 'g');

  /**
   * Parse a string to the raw tokens.
   *
   * @param  {string} str
   * @return {!Array}
   */
  function parseTokens (str) {
    var tokens = [];
    var key = 0;
    var index = 0;
    var path = '';
    var res;

    while ((res = PATH_REGEXP.exec(str)) != null) {
      var m = res[0];
      var escaped = res[1];
      var offset = res.index;
      path += str.slice(index, offset);
      index = offset + m.length;

      // Ignore already escaped sequences.
      if (escaped) {
        path += escaped[1];
        continue;
      }

      var next = str[index];
      var prefix = res[2];
      var name = res[3];
      var capture = res[4];
      var group = res[5];
      var modifier = res[6];
      var asterisk = res[7];

      // Push the current path onto the tokens.
      if (path) {
        tokens.push(path);
        path = '';
      }

      var partial = prefix != null && next != null && next !== prefix;
      var repeat = modifier === '+' || modifier === '*';
      var optional = modifier === '?' || modifier === '*';
      var delimiter = res[2] || '/';
      var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?');

      tokens.push({
        name: name || key++,
        prefix: prefix || '',
        delimiter: delimiter,
        optional: optional,
        repeat: repeat,
        partial: partial,
        asterisk: !!asterisk,
        pattern: escapeGroup(pattern)
      });
    }

    // Match any characters still remaining.
    if (index < str.length) {
      path += str.substr(index);
    }

    // If the path exists, push it onto the end.
    if (path) {
      tokens.push(path);
    }

    return tokens;
  }

  /**
   * Prettier encoding of URI path segments.
   *
   * @param  {string}
   * @return {string}
   */
  function encodeURIComponentPretty (str) {
    return encodeURI(str).replace(/[\/?#]/g, function (c) {
      return '%' + c.charCodeAt(0).toString(16).toUpperCase();
    });
  }

  /**
   * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
   *
   * @param  {string}
   * @return {string}
   */
  function encodeAsterisk (str) {
    return encodeURI(str).replace(/[?#]/g, function (c) {
      return '%' + c.charCodeAt(0).toString(16).toUpperCase();
    });
  }

  /**
   * Escape a regular expression string.
   *
   * @param  {string} str
   * @return {string}
   */
  function escapeString (str) {
    return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1');
  }

  /**
   * Escape the capturing group by escaping special characters and meaning.
   *
   * @param  {string} group
   * @return {string}
   */
  function escapeGroup (group) {
    return group.replace(/([=!:$\/()])/g, '\\$1');
  }

  /**
   * Get the flags for a regexp from the options.
   *
   * @param  {Object} options
   * @return {string}
   */
  function flags (options) {
    return options.sensitive ? '' : 'i';
  }

  /**
   * Pull out keys from a regexp.
   *
   * @param  {!RegExp} path
   * @param  {!Array}  keys
   * @return {!RegExp}
   */
  function regexpToRegexp (path) {
    // Use a negative lookahead to match only capturing groups.
    var groups = path.source.match(/\((?!\?)/g);
    var keys = [];

    if (groups) {
      for (var i = 0; i < groups.length; i++) {
        keys.push({
          name: i,
          prefix: null,
          delimiter: null,
          optional: false,
          repeat: false,
          partial: false,
          asterisk: false,
          pattern: null
        });
      }
    }

    return [path, keys];
  }

  /**
   * Expose a function for taking tokens and returning a RegExp.
   *
   * @param  {!Array}  tokens
   * @param  {Object=} options
   * @return {!RegExp}
   */
  function tokensToRegExp (tokens, options) {
    options = options || {};

    var strict = options.strict;
    var end = options.end !== false;
    var route = '';
    var lastToken = tokens[tokens.length - 1];
    var endsWithSlash = typeof lastToken === 'string' && /\/$/.test(lastToken);

    // Iterate over the tokens and create our regexp string.
    for (var i = 0; i < tokens.length; i++) {
      var token = tokens[i];

      if (typeof token === 'string') {
        route += escapeString(token);
      } else {
        var prefix = escapeString(token.prefix);
        var capture = '(?:' + token.pattern + ')';

        if (token.repeat) {
          capture += '(?:' + prefix + capture + ')*';
        }

        if (token.optional) {
          if (!token.partial) {
            capture = '(?:' + prefix + '(' + capture + '))?';
          } else {
            capture = prefix + '(' + capture + ')?';
          }
        } else {
          capture = prefix + '(' + capture + ')';
        }

        route += capture;
      }
    }

    // In non-strict mode we allow a slash at the end of match. If the path to
    // match already ends with a slash, we remove it for consistency. The slash
    // is valid at the end of a path match, not in the middle. This is important
    // in non-ending mode, where "/test/" shouldn't match "/test//route".
    if (!strict) {
      route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\/(?=$))?';
    }

    if (end) {
      route += '$';
    } else {
      // In non-ending mode, we need the capturing groups to match as much as
      // possible by using a positive lookahead to the end or next path segment.
      route += strict && endsWithSlash ? '' : '(?=\\/|$)';
    }

    return new RegExp('^' + route, flags(options));
  }

  /**
   * Compile a string to a template function for the path tokens.
   *
   * @param  {!Array}             tokens
   * @return {!function(Object=, Object=)}
   */
  function compileTokens (tokens) {
    // Compile all the tokens into regexps.
    var matches = new Array(tokens.length);

    // Compile all the patterns before compilation.
    for (var i = 0; i < tokens.length; i++) {
      if (typeof tokens[i] === 'object') {
        matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
      }
    }

    return function (obj, opts) {
      var path = '';
      var data = obj || {};
      var options = opts || {};
      var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;

      for (var i = 0; i < tokens.length; i++) {
        var token = tokens[i];

        if (typeof token === 'string') {
          path += token;

          continue;
        }

        var value = data[token.name];
        var segment;

        if (value == null) {
          if (token.optional) {
            // Prepend partial segment prefixes.
            if (token.partial) {
              path += token.prefix;
            }

            continue;
          } else {
            throw new TypeError('Expected "' + token.name + '" to be defined');
          }
        }

        if (isArray(value)) {
          if (!token.repeat) {
            throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`');
          }

          if (value.length === 0) {
            if (token.optional) {
              continue;
            } else {
              throw new TypeError('Expected "' + token.name + '" to not be empty');
            }
          }

          for (var j = 0; j < value.length; j++) {
            segment = encode(value[j]);

            if (!matches[i].test(segment)) {
              throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`');
            }

            path += (j === 0 ? token.prefix : token.delimiter) + segment;
          }

          continue;
        }

        segment = token.asterisk ? encodeAsterisk(value) : encode(value);

        if (!matches[i].test(segment)) {
          throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"');
        }

        path += token.prefix + segment;
      }

      return path;
    };
  }

  /**
   * Create a path regexp from string input.
   *
   * @param  {string}  path
   * @param  {!Array}  keys
   * @param  {!Object} options
   * @return {!Array}
   */
  function parse(path, options) {
    if (!options) options = {};

    var keys = [];
    var tokens = parseTokens(path);
    var re = tokensToRegExp(tokens, options);

    // Attach keys back to the regexp.
    for (var i = 0; i < tokens.length; i++) {
      if (typeof tokens[i] !== 'string') {
        keys.push(tokens[i]);
      }
    }

    return [re, tokens, keys];
  }

  /**
   * Compile a string to a template function for the path.
   *
   * @param  {string}             str
   * @return {!function(Object=, Object=)}
   */
  function compilePath (str) {
    return tokensToFunction(parseTokens(str));
  }

  var self = bide.impl.path;
  self.parse = parse;
  self.compilePath = compilePath;
  self.compileTokens = compileTokens;
});
<commit_msg>Escape some chars in path regex.<commit_after>/**
 * Path-to-Regex - Express-style path to regexp
 *
 * Is a modified and google closure adapted implementation of
 * https://github.com/pillarjs/path-to-regexp
 * @author Andrey Antukh <niwi@niwi.nz>, 2016
 * @author Blake Embrey <hello@blakeembrey.com>, 2014
 * @license MIT License <https://opensource.org/licenses/MIT>
 */

"use strict";

goog.provide("bide.impl.path");

goog.scope(function() {
  var toString = Object.prototype.toString;
  var isArray = Array.isArray || function (val) {
    return !! val && '[object Array]' == toString.call(val);
  };

  /**
   * The main path matching regexp utility.
   *
   * @type {RegExp}
   */
  var PATH_REGEXP = new RegExp([
    // Match escaped characters that would otherwise appear in future matches.
    // This allows the user to escape special characters that won't transform.
    '(\\\\.)',
    // Match Express-style parameters and un-named parameters with a prefix
    // and optional suffixes. Matches appear as:
    //
    // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
    // "/route(\\d+)"  => [undefined, undefined, undefined, "\d+", undefined, undefined]
    // "/*"            => ["/", undefined, undefined, undefined, undefined, "*"]
    '([\\/.])?(?:(?:\\:([\\w\\-]+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  ].join('|'), 'g');

  /**
   * Parse a string to the raw tokens.
   *
   * @param  {string} str
   * @return {!Array}
   */
  function parseTokens (str) {
    var tokens = [];
    var key = 0;
    var index = 0;
    var path = '';
    var res;

    while ((res = PATH_REGEXP.exec(str)) != null) {
      var m = res[0];
      var escaped = res[1];
      var offset = res.index;
      path += str.slice(index, offset);
      index = offset + m.length;

      // Ignore already escaped sequences.
      if (escaped) {
        path += escaped[1];
        continue;
      }

      var next = str[index];
      var prefix = res[2];
      var name = res[3];
      var capture = res[4];
      var group = res[5];
      var modifier = res[6];
      var asterisk = res[7];

      // Push the current path onto the tokens.
      if (path) {
        tokens.push(path);
        path = '';
      }

      var partial = prefix != null && next != null && next !== prefix;
      var repeat = modifier === '+' || modifier === '*';
      var optional = modifier === '?' || modifier === '*';
      var delimiter = res[2] || '/';
      var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?');

      tokens.push({
        name: name || key++,
        prefix: prefix || '',
        delimiter: delimiter,
        optional: optional,
        repeat: repeat,
        partial: partial,
        asterisk: !!asterisk,
        pattern: escapeGroup(pattern)
      });
    }

    // Match any characters still remaining.
    if (index < str.length) {
      path += str.substr(index);
    }

    // If the path exists, push it onto the end.
    if (path) {
      tokens.push(path);
    }

    return tokens;
  }

  /**
   * Prettier encoding of URI path segments.
   *
   * @param  {string}
   * @return {string}
   */
  function encodeURIComponentPretty (str) {
    return encodeURI(str).replace(/[\/?#]/g, function (c) {
      return '%' + c.charCodeAt(0).toString(16).toUpperCase();
    });
  }

  /**
   * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
   *
   * @param  {string}
   * @return {string}
   */
  function encodeAsterisk (str) {
    return encodeURI(str).replace(/[?#]/g, function (c) {
      return '%' + c.charCodeAt(0).toString(16).toUpperCase();
    });
  }

  /**
   * Escape a regular expression string.
   *
   * @param  {string} str
   * @return {string}
   */
  function escapeString (str) {
    return str.replace(/([.+*?=^!:${}\(\)\[\]|\/\\])/g, '\\$1');
  }

  /**
   * Escape the capturing group by escaping special characters and meaning.
   *
   * @param  {string} group
   * @return {string}
   */
  function escapeGroup (group) {
    return group.replace(/([=!:$\/()])/g, '\\$1');
  }

  /**
   * Get the flags for a regexp from the options.
   *
   * @param  {Object} options
   * @return {string}
   */
  function flags (options) {
    return options.sensitive ? '' : 'i';
  }

  /**
   * Pull out keys from a regexp.
   *
   * @param  {!RegExp} path
   * @param  {!Array}  keys
   * @return {!RegExp}
   */
  function regexpToRegexp (path) {
    // Use a negative lookahead to match only capturing groups.
    var groups = path.source.match(/\((?!\?)/g);
    var keys = [];

    if (groups) {
      for (var i = 0; i < groups.length; i++) {
        keys.push({
          name: i,
          prefix: null,
          delimiter: null,
          optional: false,
          repeat: false,
          partial: false,
          asterisk: false,
          pattern: null
        });
      }
    }

    return [path, keys];
  }

  /**
   * Expose a function for taking tokens and returning a RegExp.
   *
   * @param  {!Array}  tokens
   * @param  {Object=} options
   * @return {!RegExp}
   */
  function tokensToRegExp (tokens, options) {
    options = options || {};

    var strict = options.strict;
    var end = options.end !== false;
    var route = '';
    var lastToken = tokens[tokens.length - 1];
    var endsWithSlash = typeof lastToken === 'string' && /\/$/.test(lastToken);

    // Iterate over the tokens and create our regexp string.
    for (var i = 0; i < tokens.length; i++) {
      var token = tokens[i];

      if (typeof token === 'string') {
        route += escapeString(token);
      } else {
        var prefix = escapeString(token.prefix);
        var capture = '(?:' + token.pattern + ')';

        if (token.repeat) {
          capture += '(?:' + prefix + capture + ')*';
        }

        if (token.optional) {
          if (!token.partial) {
            capture = '(?:' + prefix + '(' + capture + '))?';
          } else {
            capture = prefix + '(' + capture + ')?';
          }
        } else {
          capture = prefix + '(' + capture + ')';
        }

        route += capture;
      }
    }

    // In non-strict mode we allow a slash at the end of match. If the path to
    // match already ends with a slash, we remove it for consistency. The slash
    // is valid at the end of a path match, not in the middle. This is important
    // in non-ending mode, where "/test/" shouldn't match "/test//route".
    if (!strict) {
      route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\/(?=$))?';
    }

    if (end) {
      route += '$';
    } else {
      // In non-ending mode, we need the capturing groups to match as much as
      // possible by using a positive lookahead to the end or next path segment.
      route += strict && endsWithSlash ? '' : '(?=\\/|$)';
    }

    return new RegExp('^' + route, flags(options));
  }

  /**
   * Compile a string to a template function for the path tokens.
   *
   * @param  {!Array}             tokens
   * @return {!function(Object=, Object=)}
   */
  function compileTokens (tokens) {
    // Compile all the tokens into regexps.
    var matches = new Array(tokens.length);

    // Compile all the patterns before compilation.
    for (var i = 0; i < tokens.length; i++) {
      if (typeof tokens[i] === 'object') {
        matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
      }
    }

    return function (obj, opts) {
      var path = '';
      var data = obj || {};
      var options = opts || {};
      var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;

      for (var i = 0; i < tokens.length; i++) {
        var token = tokens[i];

        if (typeof token === 'string') {
          path += token;

          continue;
        }

        var value = data[token.name];
        var segment;

        if (value == null) {
          if (token.optional) {
            // Prepend partial segment prefixes.
            if (token.partial) {
              path += token.prefix;
            }

            continue;
          } else {
            throw new TypeError('Expected "' + token.name + '" to be defined');
          }
        }

        if (isArray(value)) {
          if (!token.repeat) {
            throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`');
          }

          if (value.length === 0) {
            if (token.optional) {
              continue;
            } else {
              throw new TypeError('Expected "' + token.name + '" to not be empty');
            }
          }

          for (var j = 0; j < value.length; j++) {
            segment = encode(value[j]);

            if (!matches[i].test(segment)) {
              throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`');
            }

            path += (j === 0 ? token.prefix : token.delimiter) + segment;
          }

          continue;
        }

        segment = token.asterisk ? encodeAsterisk(value) : encode(value);

        if (!matches[i].test(segment)) {
          throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"');
        }

        path += token.prefix + segment;
      }

      return path;
    };
  }

  /**
   * Create a path regexp from string input.
   *
   * @param  {string}  path
   * @param  {!Array}  keys
   * @param  {!Object} options
   * @return {!Array}
   */
  function parse(path, options) {
    if (!options) options = {};

    var keys = [];
    var tokens = parseTokens(path);
    var re = tokensToRegExp(tokens, options);

    // Attach keys back to the regexp.
    for (var i = 0; i < tokens.length; i++) {
      if (typeof tokens[i] !== 'string') {
        keys.push(tokens[i]);
      }
    }

    return [re, tokens, keys];
  }

  /**
   * Compile a string to a template function for the path.
   *
   * @param  {string}             str
   * @return {!function(Object=, Object=)}
   */
  function compilePath (str) {
    return tokensToFunction(parseTokens(str));
  }

  var self = bide.impl.path;
  self.parse = parse;
  self.compilePath = compilePath;
  self.compileTokens = compileTokens;
});
<|endoftext|>


<commit_before>const { assertNoWarnings, assertErrorMessage, assertWarnsCount } = require('./../../common/asserts')
const linter = require('./../../../lib/index')

describe('Linter - payable-fallback', () => {
  it('should raise warn when fallback is not payable', () => {
    const code = require('../../fixtures/best-practises/fallback-not-payable')

    const report = linter.processStr(code, {
      rules: { 'payable-fallback': 'warn' }
    })

    assertWarnsCount(report, 1)
    assertErrorMessage(report, 'payable')
  })

  it('should not raise warn when fallback is payable', () => {
    const code = require('../../fixtures/best-practises/fallback-payable')

    const report = linter.processStr(code, {
      rules: { 'payable-fallback': 'warn' }
    })

    assertNoWarnings(report)
  })
})
<commit_msg>Add test for payable-fallback<commit_after>const { assertNoWarnings, assertErrorMessage, assertWarnsCount } = require('./../../common/asserts')
const linter = require('./../../../lib/index')
const { contractWith } = require('./../../common/contract-builder')

describe('Linter - payable-fallback', () => {
  it('should raise warn when fallback is not payable', () => {
    const code = require('../../fixtures/best-practises/fallback-not-payable')

    const report = linter.processStr(code, {
      rules: { 'payable-fallback': 'warn' }
    })

    assertWarnsCount(report, 1)
    assertErrorMessage(report, 'payable')
  })

  it('should not raise warn when fallback is payable', () => {
    const code = require('../../fixtures/best-practises/fallback-payable')

    const report = linter.processStr(code, {
      rules: { 'payable-fallback': 'warn' }
    })

    assertNoWarnings(report)
  })

  it('should ignore non-fallback functions', () => {
    const code = contractWith('function f() {} function g() payable {}')

    const report = linter.processStr(code, {
      rules: { 'payable-fallback': 'warn' }
    })

    assertNoWarnings(report)
  })
})
<|endoftext|>


<commit_before>'use strict';

/**
 * Question service tests
 */
var expect = require('chai').expect;
var questionService = require('../../../server/services/question.service');
var userService = require('../../../server/services/user.service');
var Promise = require('bluebird');

module.exports = function() {
  describe('Service: Question', function() {
    describe('#getQuestions', function() {
      it('should return all questions', function() {
        return questionService.getQuestions()
          .should.be.fulfilled
          .then(questions => questions.length.should.be.above(0));
      });
    });
    describe('#getPublishedQuestions', function() {
      it('should return all published questions', function() {
        return questionService.getPublishedQuestions()
          .should.be.fulfilled
          .then(questions => questions.length.should.be.above(0));
      });
    });
    describe('#count', function() {
      it('should return the number of questions', function() {
        return questionService.count()
          .then(count => count.should.be.above(0));
      });
    });
    describe('#getQuestionsByAuthor', function() {
      it('should return the questions written by a specific user', function() {
        return userService.getUserByUsername('joe')
          .then(user => questionService.getQuestionsByAuthor(user._id))
          .should.be.fulfilled
          .then(questions => questions.length.should.equal(3));
      });
    });
    describe('#getQuestionsByTag', function() {
      it('should return the questions having a specific tag', function() {
        return questionService.getQuestionsByTag('sport')
          .should.be.fulfilled
          .then(questions => questions.length.should.be.above(0));
      });
    });
    describe('#getQuestionById', function() {
      it('should return the question with a specific id', function() {
        return questionService.getQuestionById('563237258d2528ac0b65edc8')
          .should.be.fulfilled;
      });
      it('should not return a question if the id does not exist', function() {
        return questionService.getQuestionById('563237258d2528ac0b65edc9')
          .should.be.rejectedWith(Error, 'QUESTION_DOES_NOT_EXIST');
      });
      it('should not return the question if it is not published and user is not an admin', function() {
        return questionService.getQuestionById('56323699a65ccd98297256dd', false)
          .should.be.rejectedWith(Error, 'NOT_AUTHORIZED');
      });
    });
    describe('#getRandomQuestion', function() {
      it('should return a random question', function() {
        return questionService.getRandomQuestion()
          .should.be.fulfilled;
      });
    });
    describe('#getUnansweredRandomQuestion', function() {
      /*

      it('should return a random unanswered question', function() {
        var userAnswers = [{
          question: '5632378d8d2528ac0b65edcb'
        }, {
          question: '563237258d2528ac0b65edc8'
        }];

        var randomQuestions = [];
        for (let i = 0; i < 100; i++) {
          randomQuestions.push(questionService.getUnansweredRandomQuestion(userAnswers));
        }
        return Promise.all(randomQuestions)
          .should.be.fulfilled
          .then(questions => questions.map(
              question => expect(userAnswers).to.include(question._id))
            );
        */
      });
    });
    describe('#createQuestion', function() {

    });
    describe('#updateQuestion', function() {

    });
    describe('#deleteQuestion', function() {

    });
    describe('#answerQuestion', function() {

    });
    describe('#upvoteQuestion', function() {

    });
  });
};
<commit_msg>Fix broken test<commit_after>'use strict';

/**
 * Question service tests
 */
var expect = require('chai').expect;
var questionService = require('../../../server/services/question.service');
var userService = require('../../../server/services/user.service');
var Promise = require('bluebird');

module.exports = function() {
  describe('Service: Question', function() {
    describe('#getQuestions', function() {
      it('should return all questions', function() {
        return questionService.getQuestions()
          .should.be.fulfilled
          .then(questions => questions.length.should.be.above(0));
      });
    });
    describe('#getPublishedQuestions', function() {
      it('should return all published questions', function() {
        return questionService.getPublishedQuestions()
          .should.be.fulfilled
          .then(questions => questions.length.should.be.above(0));
      });
    });
    describe('#count', function() {
      it('should return the number of questions', function() {
        return questionService.count()
          .then(count => count.should.be.above(0));
      });
    });
    describe('#getQuestionsByAuthor', function() {
      it('should return the questions written by a specific user', function() {
        return userService.getUserByUsername('joe')
          .then(user => questionService.getQuestionsByAuthor(user._id))
          .should.be.fulfilled
          .then(questions => questions.length.should.equal(3));
      });
    });
    describe('#getQuestionsByTag', function() {
      it('should return the questions having a specific tag', function() {
        return questionService.getQuestionsByTag('sport')
          .should.be.fulfilled
          .then(questions => questions.length.should.be.above(0));
      });
    });
    describe('#getQuestionById', function() {
      it('should return the question with a specific id', function() {
        return questionService.getQuestionById('563237258d2528ac0b65edc8')
          .should.be.fulfilled;
      });
      it('should not return a question if the id does not exist', function() {
        return questionService.getQuestionById('563237258d2528ac0b65edc9')
          .should.be.rejectedWith(Error, 'QUESTION_DOES_NOT_EXIST');
      });
      it('should not return the question if it is not published and user is not an admin', function() {
        return questionService.getQuestionById('56323699a65ccd98297256dd', false)
          .should.be.rejectedWith(Error, 'NOT_AUTHORIZED');
      });
    });
    describe('#getRandomQuestion', function() {
      it('should return a random question', function() {
        return questionService.getRandomQuestion()
          .should.be.fulfilled;
      });
    });
    describe('#getUnansweredRandomQuestion', function() {
      /*
      it('should return a random unanswered question', function() {
        var userAnswers = [{
          question: '5632378d8d2528ac0b65edcb'
        }, {
          question: '563237258d2528ac0b65edc8'
        }];

        var randomQuestions = [];
        for (let i = 0; i < 100; i++) {
          randomQuestions.push(questionService.getUnansweredRandomQuestion(userAnswers));
        }
        return Promise.all(randomQuestions)
          .should.be.fulfilled
          .then(questions => questions.map(
              question => expect(userAnswers).to.include(question._id))
            );
      });
      */
    });
    describe('#createQuestion', function() {

    });
    describe('#updateQuestion', function() {

    });
    describe('#deleteQuestion', function() {

    });
    describe('#answerQuestion', function() {

    });
    describe('#upvoteQuestion', function() {

    });
  });
};
<|endoftext|>


<commit_before>/*global describe, it, beforeEach, afterEach */
'use strict';
var SlackMessageInterface = require('../src/slackMessageInterface');
var TravisService = require('../src/travisService');

var expect = require('chai').expect;
var sinon = require('sinon');
var Bot = require('slackbots');
var nock = require('nock');

var Repository = require('../test/mockObjects/repository');
var Channel = require('../test/mockObjects/channel');
var Build = require('../test/mockObjects/build');

describe('Bot CI General Travis info communication', function () {

    beforeEach(function () {
        this.textCheck = '';

        this.slackbotStub = sinon.stub(Bot.prototype, 'postTo', (name, text, params) => {
            this.textCheck = params.attachments[0].text;
            this.colorMessage = params.attachments[0].color;
            this.fields = params.attachments[0].fields;
        });

        this.loginStub = sinon.stub(Bot.prototype, 'login', function() {});

        this.travisService = new TravisService('github-token');
        this.travisService.username = 'mbros';

        this.slackMessageInterface = new SlackMessageInterface('Fake-token-slack', this.travisService);
        this.slackMessageInterface.bot.self = {id: '1234'};
        this.slackMessageInterface.bot.channels = Channel.createChannelList();
        this.slackMessageInterface.run();
    });

    afterEach(function () {
        this.slackbotStub.restore();
        this.loginStub.restore();
        nock.cleanAll();
    });

    it('should the bot respond with the repositories list if asked "repository list" ', function (done) {
        var repos = Repository.createRepositoriesList();
        nock('https://api.travis-ci.org:443')
            .get('/repos/mbros')
            .reply(200, {repos});

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: repository list'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Hi <@C3P0> this is the repository list: \n • fakeuser/fake-project1\n• fakeuser/fake-project2\n• fakeuser/fake-project3');// jscs:ignore maximumLineLength
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 60);
    });

    it('should the bot respond with the command list if asked "command list" ', function (done) {
        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: command list'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Hi <@C3P0> <https://github.com/eromano/ci-alarm/wiki/Command-List|this is the command list> \n • status username/example-project  \n • repository list \n • command list \n • [build|rebuild] username/example-project  \n • history username/example-project \n • info username/example-project');// jscs:ignore maximumLineLength
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 20);
    });

    it('should the bot respond with the command list if asked "help" ', function (done) {
        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: command list'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Hi <@C3P0> <https://github.com/eromano/ci-alarm/wiki/Command-List|this is the command list> \n • status username/example-project  \n • repository list \n • command list \n • [build|rebuild] username/example-project  \n • history username/example-project \n • info username/example-project');// jscs:ignore maximumLineLength
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });

    it('should the bot respond with the build history if asked : "history username/example-project" ', function (done) {
        var buildsList = Build.createBuildsList();

        nock('https://api.travis-ci.org:443')
            .get('/repos/' + this.travisService.username + '/fake-project3/builds')
            .reply(200, buildsList);

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: history ' + this.travisService.username + '/fake-project3'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Build #53 was passed\nBuild #53 was passed\nBuild #53 was passed\n');
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });

    it('should the bot respond with the information about a repository id asked : "info username/example-project" ', function (done) {
        var repos = Repository.createRepositoriesList();

        nock('https://api.travis-ci.org:443').get('/repos/' + this.travisService.username).reply(200, {repos});

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: info fake-project3'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Repository fakeuser/fake-project3 status \nfake repo description\n');
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });

    it('should the bot respond with the status of all repository id asked : "report" ', function (done) {
        var repos = Repository.createRepositoriesList();

        nock('https://api.travis-ci.org:443').get('/repos/' + this.travisService.username).reply(200, {repos});

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: report'
        });

        setTimeout(()=> {
            expect(JSON.stringify(this.fields)).to.be.equal('[{\"title\":\"fakeuser/fake-project1\",\"value\":\"|Build  #37| status passed\",\"short\":false},{\"title\":\"fakeuser/fake-project2\",\"value\":\"|Build  #37| status failed\",\"short\":false},{\"title\":\"fakeuser/fake-project3\",\"value\":\"|Build  #37| \",\"short\":false}]');
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });
});

<commit_msg>jscs fix<commit_after>/*global describe, it, beforeEach, afterEach */
'use strict';
var SlackMessageInterface = require('../src/slackMessageInterface');
var TravisService = require('../src/travisService');

var expect = require('chai').expect;
var sinon = require('sinon');
var Bot = require('slackbots');
var nock = require('nock');

var Repository = require('../test/mockObjects/repository');
var Channel = require('../test/mockObjects/channel');
var Build = require('../test/mockObjects/build');

describe('Bot CI General Travis info communication', function () {

    beforeEach(function () {
        this.textCheck = '';

        this.slackbotStub = sinon.stub(Bot.prototype, 'postTo', (name, text, params) => {
            this.textCheck = params.attachments[0].text;
            this.colorMessage = params.attachments[0].color;
            this.fields = params.attachments[0].fields;
        });

        this.loginStub = sinon.stub(Bot.prototype, 'login', function() {});

        this.travisService = new TravisService('github-token');
        this.travisService.username = 'mbros';

        this.slackMessageInterface = new SlackMessageInterface('Fake-token-slack', this.travisService);
        this.slackMessageInterface.bot.self = {id: '1234'};
        this.slackMessageInterface.bot.channels = Channel.createChannelList();
        this.slackMessageInterface.run();
    });

    afterEach(function () {
        this.slackbotStub.restore();
        this.loginStub.restore();
        nock.cleanAll();
    });

    it('should the bot respond with the repositories list if asked "repository list" ', function (done) {
        var repos = Repository.createRepositoriesList();
        nock('https://api.travis-ci.org:443')
            .get('/repos/mbros')
            .reply(200, {repos});

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: repository list'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Hi <@C3P0> this is the repository list: \n • fakeuser/fake-project1\n• fakeuser/fake-project2\n• fakeuser/fake-project3');// jscs:ignore maximumLineLength
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 60);
    });

    it('should the bot respond with the command list if asked "command list" ', function (done) {
        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: command list'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Hi <@C3P0> <https://github.com/eromano/ci-alarm/wiki/Command-List|this is the command list> \n • status username/example-project  \n • repository list \n • command list \n • [build|rebuild] username/example-project  \n • history username/example-project \n • info username/example-project');// jscs:ignore maximumLineLength
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 20);
    });

    it('should the bot respond with the command list if asked "help" ', function (done) {
        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: command list'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Hi <@C3P0> <https://github.com/eromano/ci-alarm/wiki/Command-List|this is the command list> \n • status username/example-project  \n • repository list \n • command list \n • [build|rebuild] username/example-project  \n • history username/example-project \n • info username/example-project');// jscs:ignore maximumLineLength
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });

    it('should the bot respond with the build history if asked : "history username/example-project" ', function (done) {
        var buildsList = Build.createBuildsList();

        nock('https://api.travis-ci.org:443')
            .get('/repos/' + this.travisService.username + '/fake-project3/builds')
            .reply(200, buildsList);

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: history ' + this.travisService.username + '/fake-project3'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Build #53 was passed\nBuild #53 was passed\nBuild #53 was passed\n');
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });

    it('should the bot respond with the information about a repository id asked : "info username/example-project" ', function (done) {
        var repos = Repository.createRepositoriesList();

        nock('https://api.travis-ci.org:443').get('/repos/' + this.travisService.username).reply(200, {repos});

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: info fake-project3'
        });

        setTimeout(()=> {
            expect(this.textCheck).to.be.equal('Repository fakeuser/fake-project3 status \nfake repo description\n');
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });

    it('should the bot respond with the status of all repository id asked : "report" ', function (done) {
        var repos = Repository.createRepositoriesList();

        nock('https://api.travis-ci.org:443').get('/repos/' + this.travisService.username).reply(200, {repos});

        this.slackMessageInterface.bot.emit('message', {
            username: 'Sonikku',
            user: 'C3P0',
            channel: 'fake-general-channel-id',
            type: 'message',
            text: '<@' + this.slackMessageInterface.bot.self.id + '>: report'
        });

        setTimeout(()=> {
            expect(JSON.stringify(this.fields)).to.be.equal('[{\"title\":\"fakeuser/fake-project1\",\"value\":\"|Build  #37| status passed\",\"short\":false},{\"title\":\"fakeuser/fake-project2\",\"value\":\"|Build  #37| status failed\",\"short\":false},{\"title\":\"fakeuser/fake-project3\",\"value\":\"|Build  #37| \",\"short\":false}]');// jscs:ignore maximumLineLength
            expect(this.colorMessage).to.be.equal(this.slackMessageInterface.infoColor);
            done();
        }, 50);
    });
});

<|endoftext|>


<commit_before>/*global describe, it, beforeEach*/
var unexpected = require('../unexpected-with-plugins'),
    passError = require('passerror'),
    AssetGraph = require('../../lib/'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs;

describe('transforms/replaceSymbolsInJavaScript', function () {
    var assetGraph;
    beforeEach(function () {
        assetGraph = new AssetGraph();
    });

    var expect = unexpected.clone().addAssertion('to come out as', function (expect, subject, value, done) {
        // subject.code, subject.defines
        expect(subject, 'to be an object');
        var assetConfig = {
            url: 'file://' + __dirname + '/bogus.js'
        };
        if (subject.parseTree instanceof uglifyJs.AST_Node) {
            assetConfig.parseTree = subject.parseTree;
        } else if (typeof subject.text === 'string') {
            assetConfig.text = subject.text;
        } else if (Buffer.isBuffer(subject.rawSrc)) {
            assetConfig.rawSrc = subject.rawSrc;
        }
        assetGraph
            .loadAssets(new AssetGraph.JavaScript(assetConfig))
            .replaceSymbolsInJavaScript({type: 'JavaScript'}, subject.defines || {})
            .queue(function (assetGraph) {
                expect(assetGraph.findAssets({fileName: 'bogus.js'})[0], 'to have the same AST as', value);
            })
            .run(done);
    });

    it('should replace a primitive value', function (done) {
        expect({
            text: 'var bar = FOO;',
            defines: {
                FOO: '"foo"'
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'foo';
            /* jshint ignore:end */
        }, done);
    });

    it('should not replace an undefined value', function (done) {
        expect({
            text: 'var bar = FOO;',
            defines: {
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = FOO;
            /* jshint ignore:end */
        }, done);
    });

    it('should replace an undefined value in an object with undefined', function (done) {
        expect({
            text: 'var bar = FOO.BAR;',
            defines: {
                FOO: {}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = undefined;
            /* jshint ignore:end */
        }, done);
    });

    it('should replace an undefined value in a nested object with undefined', function (done) {
        expect({
            text: 'var bar = !BAZ.FOO.BAR;',
            defines: {
                BAZ: {}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = !undefined;
            /* jshint ignore:end */
        }, done);
    });

    it('should not replace the LHS of an assignment', function (done) {
        expect({
            text: 'var FOO = "bar";',
            defines: {
                FOO: new uglifyJs.AST_String({value: 'foo'})
            }
        }, 'to come out as', 'var FOO = "bar";', done);
    });

    it('should replace complex value', function (done) {
        expect({
            text: 'var bar = FOO;',
            defines: {
                FOO: {quux: {baz: 123}}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = {quux: {baz: 123}};
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with dot notation', function (done) {
        expect({
            text: 'var bar = FOO.quux;',
            defines: {
                FOO: {quux: 'baz'}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'baz';
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with bracket notation', function (done) {
        expect({
            text: 'var bar = FOO["quux"];',
            defines: {
                FOO: {quux: 'baz'}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'baz';
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with mixed notation', function (done) {
        expect({
            text: 'var bar = FOO["quux"].baz;',
            defines: {
                FOO: { quux: { baz: 'foo' } }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'foo';
            /* jshint ignore:end */
        }, done);
    });

    it('should work with numbers and bracket notation', function (done) {
        expect({
            text: 'var bar = FOO[1];',
            defines: {
                FOO: { 1: 'baz' }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'baz';
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with undefined if no value is found', function (done) {
        var infos = [];
        assetGraph.on('info', function (err) {
            infos.push(err);
        });
        expect({
            text: 'var qux = FOO.bar.baz.quux',
            defines: {
                FOO: { bar: { baz: {} } }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var qux = undefined;
            /* jshint ignore:end */
        }, passError(done, function () {
            expect(infos, 'to have length', 1);
            expect(infos[0].message, 'to equal', 'Could not find a value for "FOO.bar.baz.quux". Replacing with undefined.');
            done();
        }));
    });

    it('should proceed as far as possible if contents of brackets is not a constant', function (done) {
        expect({
            text: 'var bar = FOO[function () { return "bar"; }];',
            defines: {
                FOO: { bar: 'baz' }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = { bar: 'baz' }[function () { return "bar"; }];
            /* jshint ignore:end */
        }, done);
    });

    // Wishful thinking:
    it('should support dot notation in the LHS', function (done) {
        expect({
            text: 'console.log(123);',
            defines: {
                'console.log': 'foo.bar'
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            foo.bar(123);
            /* jshint ignore:end */
        }, done);
    });

    it('should support bracket notation in the LHS', function (done) {
        expect({
            text: 'alert(123 + hereIs["the thing"]);',
            defines: {
                'hereIs["the thing"]': 987
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            alert(123 + 987);
            /* jshint ignore:end */
        }, done);
    });

    it('should support a complex expression in the LHS', function (done) {
        expect({
            text: '123 + foo(1 + 2);',
            defines: {
                'foo(1 + 2)': '456'
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            123 + 456;
            /* jshint ignore:end */
        }, done);
    });
});
<commit_msg>replaceSymbolsInJavaScript: Test that different instances are used when replacing multiple instances.<commit_after>/*global describe, it, beforeEach*/
var unexpected = require('../unexpected-with-plugins'),
    passError = require('passerror'),
    AssetGraph = require('../../lib/'),
    passError = require('passerror'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs;

describe('transforms/replaceSymbolsInJavaScript', function () {
    var assetGraph;
    beforeEach(function () {
        assetGraph = new AssetGraph();
    });

    var expect = unexpected.clone().addAssertion('to come out as', function (expect, subject, value, done) {
        this.args.pop(); // Don't inspect the callback when the assertion fails
        // subject.code, subject.defines
        expect(subject, 'to be an object');
        var assetConfig = {
            url: 'file://' + __dirname + '/bogus.js'
        };
        if (subject.parseTree instanceof uglifyJs.AST_Node) {
            assetConfig.parseTree = subject.parseTree;
        } else if (typeof subject.text === 'string') {
            assetConfig.text = subject.text;
        } else if (Buffer.isBuffer(subject.rawSrc)) {
            assetConfig.rawSrc = subject.rawSrc;
        }
        assetGraph
            .loadAssets(new AssetGraph.JavaScript(assetConfig))
            .replaceSymbolsInJavaScript({type: 'JavaScript'}, subject.defines || {})
            .queue(function (assetGraph) {
                expect(assetGraph.findAssets({fileName: 'bogus.js'})[0], 'to have the same AST as', value);
            })
            .run(function (err) {
                done(err, !err && assetGraph.findAssets()[0].parseTree);
            });
    });

    it('should replace a primitive value', function (done) {
        expect({
            text: 'var bar = FOO;',
            defines: {
                FOO: '"foo"'
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'foo';
            /* jshint ignore:end */
        }, done);
    });

    it('should not replace an undefined value', function (done) {
        expect({
            text: 'var bar = FOO;',
            defines: {
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = FOO;
            /* jshint ignore:end */
        }, done);
    });

    it('should replace an undefined value in an object with undefined', function (done) {
        expect({
            text: 'var bar = FOO.BAR;',
            defines: {
                FOO: {}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = undefined;
            /* jshint ignore:end */
        }, done);
    });

    it('should replace an undefined value in a nested object with undefined', function (done) {
        expect({
            text: 'var bar = !BAZ.FOO.BAR;',
            defines: {
                BAZ: {}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = !undefined;
            /* jshint ignore:end */
        }, done);
    });

    it('should not replace the LHS of an assignment', function (done) {
        expect({
            text: 'var FOO = "bar";',
            defines: {
                FOO: new uglifyJs.AST_String({value: 'foo'})
            }
        }, 'to come out as', 'var FOO = "bar";', done);
    });

    it('should replace complex value', function (done) {
        expect({
            text: 'var bar = FOO;',
            defines: {
                FOO: {quux: {baz: 123}}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = {quux: {baz: 123}};
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with dot notation', function (done) {
        expect({
            text: 'var bar = FOO.quux;',
            defines: {
                FOO: {quux: 'baz'}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'baz';
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with bracket notation', function (done) {
        expect({
            text: 'var bar = FOO["quux"];',
            defines: {
                FOO: {quux: 'baz'}
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'baz';
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with mixed notation', function (done) {
        expect({
            text: 'var bar = FOO["quux"].baz;',
            defines: {
                FOO: { quux: { baz: 'foo' } }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'foo';
            /* jshint ignore:end */
        }, done);
    });

    it('should work with numbers and bracket notation', function (done) {
        expect({
            text: 'var bar = FOO[1];',
            defines: {
                FOO: { 1: 'baz' }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = 'baz';
            /* jshint ignore:end */
        }, done);
    });

    it('should replace nested value with undefined if no value is found', function (done) {
        var infos = [];
        assetGraph.on('info', function (err) {
            infos.push(err);
        });
        expect({
            text: 'var qux = FOO.bar.baz.quux',
            defines: {
                FOO: { bar: { baz: {} } }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var qux = undefined;
            /* jshint ignore:end */
        }, passError(done, function () {
            expect(infos, 'to have length', 1);
            expect(infos[0].message, 'to equal', 'Could not find a value for "FOO.bar.baz.quux". Replacing with undefined.');
            done();
        }));
    });

    it('should proceed as far as possible if contents of brackets is not a constant', function (done) {
        expect({
            text: 'var bar = FOO[function () { return "bar"; }];',
            defines: {
                FOO: { bar: 'baz' }
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            var bar = { bar: 'baz' }[function () { return "bar"; }];
            /* jshint ignore:end */
        }, done);
    });

    // Wishful thinking:
    it('should support dot notation in the LHS', function (done) {
        expect({
            text: 'console.log(123);',
            defines: {
                'console.log': 'foo.bar'
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            foo.bar(123);
            /* jshint ignore:end */
        }, done);
    });

    it('should support bracket notation in the LHS', function (done) {
        expect({
            text: 'alert(123 + hereIs["the thing"]);',
            defines: {
                'hereIs["the thing"]': 987
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            alert(123 + 987);
            /* jshint ignore:end */
        }, done);
    });

    it('should support a complex expression in the LHS', function (done) {
        expect({
            text: '123 + foo(1 + 2);',
            defines: {
                'foo(1 + 2)': '456'
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            123 + 456;
            /* jshint ignore:end */
        }, done);
    });

    it('should not use the same AST node instance when replacing multiple occurrences', function (done) {
        expect({
            text: 'FOO + FOO',
            defines: {
                FOO: 2
            }
        }, 'to come out as', function () {
            /* jshint ignore:start */
            2 + 2;
            /* jshint ignore:end */
        }, passError(done, function (parseTree) {
            var binOp = parseTree.body[0].body;
            expect(binOp, 'to be an', uglifyJs.AST_Binary);
            expect(binOp.left, 'not to be', binOp.right);
            done();
        }));
    });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users'),
	projects = require('../../app/controllers/projects');

module.exports = function(app) {
	// Project Routes
	app.route('/projects')
	    .get(projects.list)
	    .post(users.requiresLogin, projects.create);

	app.route('/projects/:projectId')
		.get(projects.read)
		.put(users.requiresLogin, projects.hasAuthorization, projects.update)
		.delete(users.requiresLogin, projects.hasAuthorization, projects.delete);

    app.route('/projects/:projectId/GeneratePlateTemplate')
        .post(users.requiresLogin, projects.generatePlateTemplate);

    app.route('/projects/:projectId/GeneratePlates')
        .post(users.requiresLogin, projects.generatePlates);

	// Finish by binding the project middleware
	app.param('projectId', projects.projectByID);
};
<commit_msg>Viewing list of projects requires login<commit_after>'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users'),
	projects = require('../../app/controllers/projects');

module.exports = function(app) {
	// Project Routes
	app.route('/projects')
	    .get(users.requiresLogin, projects.list)
	    .post(users.requiresLogin, projects.create);

	app.route('/projects/:projectId')
		.get(projects.read)
		.put(users.requiresLogin, projects.hasAuthorization, projects.update)
		.delete(users.requiresLogin, projects.hasAuthorization, projects.delete);

    app.route('/projects/:projectId/GeneratePlateTemplate')
        .post(users.requiresLogin, projects.generatePlateTemplate);

    app.route('/projects/:projectId/GeneratePlates')
        .post(users.requiresLogin, projects.generatePlates);

	// Finish by binding the project middleware
	app.param('projectId', projects.projectByID);
};
<|endoftext|>


<commit_before>(function (factory) {
    typeof define === 'function' && define.amd ? define(factory) :
    factory();
}((function () { 'use strict';

    /**
     * The code was extracted from:
     * https://github.com/davidchambers/Base64.js
     */

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function InvalidCharacterError(message) {
        this.message = message;
    }

    InvalidCharacterError.prototype = new Error();
    InvalidCharacterError.prototype.name = "InvalidCharacterError";

    function polyfill(input) {
        var str = String(input).replace(/=+$/, "");
        if (str.length % 4 == 1) {
            throw new InvalidCharacterError(
                "'atob' failed: The string to be decoded is not correctly encoded."
            );
        }
        for (
            // initialize result and counters
            var bc = 0, bs, buffer, idx = 0, output = "";
            // get next character
            (buffer = str.charAt(idx++));
            // character found in table? initialize bit storage and add its ascii value;
            ~buffer &&
            ((bs = bc % 4 ? bs * 64 + buffer : buffer),
                // and if not first of each 4 characters,
                // convert the first 8 bits to one ascii character
                bc++ % 4) ?
            (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) :
            0
        ) {
            // try to find character in table (0-63, not found => -1)
            buffer = chars.indexOf(buffer);
        }
        return output;
    }

    var atob = (typeof window !== "undefined" &&
        window.atob &&
        window.atob.bind(window)) ||
    polyfill;

    function b64DecodeUnicode(str) {
        return decodeURIComponent(
            atob(str).replace(/(.)/g, function(m, p) {
                var code = p.charCodeAt(0).toString(16).toUpperCase();
                if (code.length < 2) {
                    code = "0" + code;
                }
                return "%" + code;
            })
        );
    }

    function base64_url_decode(str) {
        var output = str.replace(/-/g, "+").replace(/_/g, "/");
        switch (output.length % 4) {
            case 0:
                break;
            case 2:
                output += "==";
                break;
            case 3:
                output += "=";
                break;
            default:
                throw "Illegal base64url string!";
        }

        try {
            return b64DecodeUnicode(output);
        } catch (err) {
            return atob(output);
        }
    }

    function InvalidTokenError(message) {
        this.message = message;
    }

    InvalidTokenError.prototype = new Error();
    InvalidTokenError.prototype.name = "InvalidTokenError";

    function jwtDecode(token, options) {
        if (typeof token !== "string") {
            throw new InvalidTokenError("Invalid token specified");
        }

        options = options || {};
        var pos = options.header === true ? 0 : 1;
        try {
            return JSON.parse(base64_url_decode(token.split(".")[pos]));
        } catch (e) {
            throw new InvalidTokenError("Invalid token specified: " + e.message);
        }
    }

    /*
     * Expose the function on the window object
     */

    //use amd or just throught to window object.
    if (window) {
        if (typeof window.define == "function" && window.define.amd) {
            window.define("jwt_decode", function() {
                return jwtDecode;
            });
        } else if (window) {
            window.jwt_decode = jwtDecode;
        }
    }

})));
//# sourceMappingURL=jwt-decode.js.map
<commit_msg>Update UMD build<commit_after>(function (factory) {
    typeof define === 'function' && define.amd ? define(factory) :
    factory();
}((function () { 'use strict';

    /**
     * The code was extracted from:
     * https://github.com/davidchambers/Base64.js
     */

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function InvalidCharacterError(message) {
        this.message = message;
    }

    InvalidCharacterError.prototype = new Error();
    InvalidCharacterError.prototype.name = "InvalidCharacterError";

    function polyfill(input) {
        var str = String(input).replace(/=+$/, "");
        if (str.length % 4 == 1) {
            throw new InvalidCharacterError(
                "'atob' failed: The string to be decoded is not correctly encoded."
            );
        }
        for (
            // initialize result and counters
            var bc = 0, bs, buffer, idx = 0, output = "";
            // get next character
            (buffer = str.charAt(idx++));
            // character found in table? initialize bit storage and add its ascii value;
            ~buffer &&
            ((bs = bc % 4 ? bs * 64 + buffer : buffer),
                // and if not first of each 4 characters,
                // convert the first 8 bits to one ascii character
                bc++ % 4) ?
            (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) :
            0
        ) {
            // try to find character in table (0-63, not found => -1)
            buffer = chars.indexOf(buffer);
        }
        return output;
    }

    var atob = (typeof window !== "undefined" &&
        window.atob &&
        window.atob.bind(window)) ||
    polyfill;

    function b64DecodeUnicode(str) {
        return decodeURIComponent(
            atob(str).replace(/(.)/g, function(m, p) {
                var code = p.charCodeAt(0).toString(16).toUpperCase();
                if (code.length < 2) {
                    code = "0" + code;
                }
                return "%" + code;
            })
        );
    }

    function base64_url_decode(str) {
        var output = str.replace(/-/g, "+").replace(/_/g, "/");
        switch (output.length % 4) {
            case 0:
                break;
            case 2:
                output += "==";
                break;
            case 3:
                output += "=";
                break;
            default:
                throw "Illegal base64url string!";
        }

        try {
            return b64DecodeUnicode(output);
        } catch (err) {
            return atob(output);
        }
    }

    function InvalidTokenError(message) {
        this.message = message;
    }

    InvalidTokenError.prototype = new Error();
    InvalidTokenError.prototype.name = "InvalidTokenError";

    function jwtDecode(token, options) {
        if (typeof token !== "string") {
            throw new InvalidTokenError("Invalid token specified");
        }

        options = options || {};
        var pos = options.header === true ? 0 : 1;
        try {
            return JSON.parse(base64_url_decode(token.split(".")[pos]));
        } catch (e) {
            throw new InvalidTokenError("Invalid token specified: " + e.message);
        }
    }

    /*
     * Expose the function on the window object
     */

    //use amd or just through the window object.
    if (window) {
        if (typeof window.define == "function" && window.define.amd) {
            window.define("jwt_decode", function() {
                return jwtDecode;
            });
        } else if (window) {
            window.jwt_decode = jwtDecode;
        }
    }

})));
//# sourceMappingURL=jwt-decode.js.map
<|endoftext|>


<commit_before>var t = TrelloPowerUp.iframe();

t.render(function(){
    populateForm();
    t.sizeTo('#content');
});

var populateForm = function() {
    var members = {};
    return t.board('all')
    .then(function(board) {
        members = board.members;
        UMTrello.populateSelectListBasedOnData('idsReporter', members, 'Select a Reporter', function(list) {
            return {
                name: list.name,
                value: list.id
            };
        });
        UMTrello.populateSelectListBasedOnData('idsAssignee', members, 'Select an Assignee', function(list) {
            return {
                name: list.name,
                value: list.id
            };
        });
        return t.get('card', 'shared', UMTrello.constants.data.ids, {})
        .then(function(data) {
            updateFormState(data);
        });
    });
};

var updateFormState = function(data) {
    document.getElementById('idsWhat').value = data.what;
    document.getElementById('idsReporter').value = data.reporter;
    document.getElementById('idsAssignee').value = data.assignee;
};

var handleIDSSave = function (e) {
    UMTrello.disableButton('updateIDS');
    UMTrello.disableButton('deleteIDS');
    var data = {
        reporter: UMTrello.selectListSelectedValue('idsReporter'),
        assignee: UMTrello.selectListSelectedValue('idsAssignee'),
        what: document.getElementById('idsWhat').value
    };
    return t.set('card', 'shared', UMTrello.constants.data.ids, data)
    .then(function() {
        UMTrello.enableButton('updateIDS');
        UMTrello.enableButton('deleteIDS');
    });
};

var handleIDSDelete = function (e) {
    UMTrello.disableButton('updateIDS');
    UMTrello.disableButton('deleteIDS');
    return t.remove('card', 'shared', UMTrello.constants.data.ids)
    .then(function() {
        t.closePopup();
    });
};

<commit_msg>Updating IDS data handling<commit_after>var t = TrelloPowerUp.iframe();

t.render(function(){
    populateForm();
    t.sizeTo('#content');
});

var populateForm = function() {
    var members = {};
    return t.board('all')
    .then(function(board) {
        members = board.members;
        console.log(members);
        console.dir(members);
        UMTrello.populateSelectListBasedOnData('idsReporter', members, 'Select a Reporter', function(member) {
            return {
                name: member.fullName,
                value: member.id
            };
        });
        UMTrello.populateSelectListBasedOnData('idsAssignee', members, 'Select an Assignee', function(member) {
            return {
                name: member.fullName,
                value: member.id
            };
        });
        return t.get('card', 'shared', UMTrello.constants.data.ids, {})
        .then(function(data) {
            updateFormState(data);
        });
    });
};

var updateFormState = function(data) {
    document.getElementById('idsWhat').value = data.what ? data.what : '';
    document.getElementById('idsReporter').value = data.reporter;
    document.getElementById('idsAssignee').value = data.assignee;
};

var handleIDSSave = function (e) {
    UMTrello.disableButton('updateIDS');
    UMTrello.disableButton('deleteIDS');
    var data = {
        reporter: UMTrello.selectListSelectedValue('idsReporter'),
        assignee: UMTrello.selectListSelectedValue('idsAssignee'),
        what: document.getElementById('idsWhat').value
    };
    return t.set('card', 'shared', UMTrello.constants.data.ids, data)
    .then(function() {
        UMTrello.enableButton('updateIDS');
        UMTrello.enableButton('deleteIDS');
    });
};

var handleIDSDelete = function (e) {
    UMTrello.disableButton('updateIDS');
    UMTrello.disableButton('deleteIDS');
    return t.remove('card', 'shared', UMTrello.constants.data.ids)
    .then(function() {
        t.closePopup();
    });
};

<|endoftext|>


<commit_before>import { argv } from 'yargs'
import config from '../config'
import webpackConfig from './webpack.config'

const debug = require('debug')('app:karma')
debug('Create configuration.')

const karmaConfig = {
  basePath: '../', // project root in relation to bin/karma.js
  files: [
    './node_modules/phantomjs-polyfill/bind-polyfill.js',
    {
      pattern: `./${config.dir_test}/test-bundler.js`,
      watched: false,
      served: true,
      included: true
    }
  ],
  singleRun: !argv.watch,
  frameworks: ['mocha', 'chai-sinon', 'chai-as-promised', 'chai'],
  preprocessors: {
    [`${config.dir_test}/test-bundler.js`]: ['webpack', 'sourcemap']
  },
  reporters: ['spec'],
  browsers: ['PhantomJS'],
  webpack: {
    devtool: 'inline-source-map',
    resolve: webpackConfig.resolve,
    plugins: webpackConfig.plugins,
    module: {
      loaders: webpackConfig.module.loaders
    },
    sassLoader: webpackConfig.sassLoader
  },
  webpackMiddleware: {
    noInfo: true
  },
  coverageReporter: {
    reporters: config.coverage_reporters
  }
}

if (config.coverage_enabled) {
  karmaConfig.reporters.push('coverage')
  karmaConfig.webpack.module.preLoaders = [{
    test: /\.(js|jsx)$/,
    include: new RegExp(config.dir_client),
    loader: 'isparta',
    exclude: /node_modules/
  }]
}

export default (cfg) => cfg.set(karmaConfig)
<commit_msg>fixes #26<commit_after>import { argv } from 'yargs'
import config from '../config'
import webpackConfig from './webpack.config'

const debug = require('debug')('app:karma')
debug('Create configuration.')

const karmaConfig = {
  basePath: '../', // project root in relation to bin/karma.js
  files: [
    './node_modules/phantomjs-polyfill/bind-polyfill.js',
    {
      pattern: `./${config.dir_test}/test-bundler.js`,
      watched: false,
      served: true,
      included: true
    }
  ],
  singleRun: !argv.watch,
  frameworks: ['mocha', 'chai-sinon', 'chai-as-promised', 'chai'],
  preprocessors: {
    [`${config.dir_test}/test-bundler.js`]: ['webpack', 'sourcemap']
  },
  reporters: ['spec'],
  browsers: ['PhantomJS'],
  webpack: {
    devtool: 'inline-source-map',
    resolve: {
      ...webpackConfig.resolve,
      alias: {
        'sinon': 'sinon/pkg/sinon'
      }
    },
    plugins: webpackConfig.plugins,
    externals: {
      'jsdom': 'window',
      'cheerio': 'window',
      'react/lib/ReactContext': 'window',
      'react/lib/ExecutionEnvironment': true
    },
    module: {
      noParse: [
        /node_modules\/sinon\//,
      ],
      loaders: webpackConfig.module.loaders
    },
    sassLoader: webpackConfig.sassLoader
  },
  webpackMiddleware: {
    noInfo: true
  },
  coverageReporter: {
    reporters: config.coverage_reporters
  }
}

if (config.coverage_enabled) {
  karmaConfig.reporters.push('coverage')
  karmaConfig.webpack.module.preLoaders = [{
    test: /\.(js|jsx)$/,
    include: new RegExp(config.dir_client),
    loader: 'isparta',
    exclude: /node_modules/
  }]
}

export default (cfg) => cfg.set(karmaConfig)
<|endoftext|>