<commit_before>/*
 * jitsu.js: Top-level include for the jitsu module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var jitsu = exports;

var path = require('path');

// Failure HTTP Response codes based
// off of `/lib/broodmother/slave/service.js`
var failCodes = jitsu.failCodes = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Not Authorized',
  404: 'Item not found',
  409: 'Conflict',
  500: 'Internal Server Error'
};

// Success HTTP Response codes based
// off of `/lib/broodmother/slave/service.js`
var successCodes = jitsu.successCodes = {
  200: 'OK',
  201: 'Created'
};

jitsu.skipAuth          = false;
jitsu.started           = false;
jitsu.utils             = require('./jitsu/utils');
jitsu.package           = require('./jitsu/package');
jitsu.log               = require('cliff');
jitsu.logFile           = new (require('./jitsu/utils/logfile').LogFile)(path.join(process.env.HOME, '.jitsulog'));
jitsu.api               = {};
jitsu.api.Client        = require('nodejitsu-api').Client;
jitsu.api.Apps          = require('nodejitsu-api').Apps;
jitsu.api.Databases     = require('nodejitsu-api').Databases;
jitsu.api.Logs          = require('nodejitsu-api').Logs;
jitsu.api.Snapshots     = require('nodejitsu-api').Snapshots;
jitsu.api.Users         = require('nodejitsu-api').Users;
jitsu.prompt            = require('prompt');
jitsu.prompt.properties = require('./jitsu/properties').properties;
jitsu.prompt.override   = require('optimist').argv;
jitsu.config            = require('./jitsu/config');
jitsu.commands          = require('./jitsu/commands');

//
// Alias the appropriate commands for simplier CLI usage
//
jitsu.commands.alias('create', { resource: 'apps',   command: 'create' });
jitsu.commands.alias('deploy', { resource: 'apps',   command: 'deploy' });
jitsu.commands.alias('list',   { resource: 'apps',   command: 'list' });
jitsu.commands.alias('conf',   { resource: 'config', command: 'list' });
jitsu.commands.alias('login',  { resource: 'users',  command: 'login' });
jitsu.commands.alias('logout', { resource: 'users',  command: 'logout' });
jitsu.commands.alias('signup', { resource: 'users',  command: 'create' });
jitsu.commands.alias('whoami', { resource: 'users',  command: 'whoami' });

var eyes = require('eyes'),
    winston = require('winston'),
    colors = require('colors');

//
// Setup `jitsu` to use `pkginfo` to expose version
//
require('pkginfo')(module, 'version');

//
// ### function start (command, callback)
// #### @command {string} Command to execute once started
// #### @callback {function} Continuation to pass control to when complete.
// Starts the jitsu CLI and runs the specified command.
//
jitsu.start = function (argv, callback) {
  var command = argv._;

  //
  // Special -v command for showing current version without winston formatting
  //
  if (argv.version || argv.v) {
    console.log('v' + jitsu.version);
    process.exit(0);
  }

  //
  // Check for --no-colors/--colors option, without hitting the config file
  // yet
  //
  (typeof argv.colors == "undefined" || argv.colors) || (colors.mode = "none");

  // Setup the initial prompt but don't leave it open
  jitsu.prompt.start().pause();

  //
  // Default to the `help` command.
  //
  command[0] || (command[0] = 'help');

  jitsu.utils.checkVersion(function (err) {
    if (err) return callback();
    jitsu.config.load(function (err) {
      if (err) {
        jitsu.welcome();
        callback(err);
        return jitsu.showError.apply(null, [command[0]].concat(arguments));
      }

      //
      // --no-colors option turns off output coloring, and so does setting
      // colors: false in ~/.jitsuconf (see
      // https://github.com/nodejitsu/jitsu/issues/101 )
      //
      jitsu.config.get('colors') || (colors.mode = "none");

      jitsu.welcome();

      var username = jitsu.config.get('username');
      if (!username && jitsu.commands.requiresAuth(command[0])) {
        return jitsu.setupUser(function (err) {
          if (err) {
            callback(err);
            return jitsu.showError.apply(jitsu, [command[0]].concat(arguments));
          }

          var username = jitsu.config.get('username');
          winston.info('Successfully configured user ' + username.magenta);
          return command.length > 0 ? jitsu.exec(command, callback) : callback();
        });
      }

      return jitsu.exec(command, callback)
    });
  });
};

//
// ### function welcome ()
// Print welcome message.
//
jitsu.welcome = function () {
  winston.info('Welcome to ' + 'Nodejitsu'.grey);
  winston.info('It worked if it ends with ' + 'Nodejitsu'.grey + ' ok'.green.bold);
};

//
// ### function exec (command, callback)
// #### @command {string} Command to execute
// #### @callback {function} Continuation to pass control to when complete.
// Runs the specified command in the jitsu CLI.
//
jitsu.exec = function (command, callback) {
  function execCommand (err) {
    if (err) {
      return callback(err);
    }

    //
    // Remark: This is a temporary fix for aliasing init=>install,
    // was having a few issues with the alias command on the install resource
    //
    if (command[0] === 'init'){
      command[0] = 'install';
    }

    // Alias db to databases
    if (command[0] === 'db'){
      command[0] = 'databases';
    }

    // Allow `jitsu logs` as a shortcut for `jitsu logs app`
    if (command[0] === 'logs' && command.length === 1) {
      command[1] = 'app';
    }

    winston.info('Executing command ' + command.join(' ').magenta);
    jitsu.commands.run(command, function (err, shallow) {
      if (err) {
        callback(err);
        return jitsu.showError(command.join(' '), err, shallow);
      }

      //
      // TODO (indexzero): Something here
      //
      callback();
    });
  }

  return !jitsu.started ? jitsu.setup(execCommand) : execCommand();
};

//
// ### function setup (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Sets up the instances of the Resource clients for jitsu.
// there is no io here, yet this function is ASYNC.
//
jitsu.setup = function (callback) {
  if (jitsu.started === true) {
    return callback();
  }

  jitsu.users = new jitsu.api.Users(jitsu.config);
  jitsu.apps = new jitsu.api.Apps(jitsu.config);
  jitsu.snapshots = new jitsu.api.Snapshots(jitsu.config);
  jitsu.databases = new jitsu.api.Databases(jitsu.config);
  jitsu.logs = new jitsu.api.Logs(jitsu.config);
  jitsu.started = true;

  callback();
};

//
// ### function auth (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Attempts to authenicate the user identified in `jitsu.config.get('username'|'password')`
//
jitsu.auth = function (callback) {
  if (jitsu.skipAuth) {
    return callback();
  }

  var username = jitsu.config.get('username');
  winston.silly('Attempting to authenticate as ' + username.magenta);
  jitsu.users.auth(function (err, success) {
    if (err || !success) {
      winston.error('Unable to Authenticate as ' + username.magenta);
      winston.error(err.message);
      return callback(err);
    }

    jitsu.skipAuth = true;
    winston.info('Authenticated as ' + username.magenta);
    return callback();
  })
}

//
// ### function setupUser (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk.
//
jitsu.setupUser = function (callback) {
  winston.warn('You will need to login to continue');
  winston.info('To login, you will need an activated nodejitsu account');
  winston.help('You can create an account using the ' + 'jitsu signup'.magenta + ' command');
  jitsu.setupUserNoWarn(callback);
};

//
// ### function setupUserNoWarn (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk without a warning
//
jitsu.setupUserNoWarn = function(callback) {
  //
  // Attempt to get the password three times.
  //
  var tries = 0;

  function offerReset (username) {
    jitsu.prompt.get(['reset'], function (err, res) {
      if (err) {
        return callback(err);
      }
      if (/^y[es]+/i.test(res['request password reset'])) {
        return jitsu.commands.run(['users', 'forgot', username], callback);
      }

      callback(new Error('Invalid username / password.'));
    });
  }

  (function setupAuth () {
    jitsu.prompt.get(['username', 'password'], function (err, result) {
      if (err) {
        return callback(err);
      }

      jitsu.config.set('username', result.username);
      jitsu.config.set('password', result.password);
      jitsu.setup(function () {
        jitsu.auth(function (err) {
          //
          // Increment the auth attempts
          //
          tries += 1;

          if (err) {
            if (tries >= 3) {
              winston.error('Three failed login attempts');
              winston.info('Would you like to reset your password?');
              return offerReset(result.username);
            }
            return setupAuth();
          }

          jitsu.config.save(function (err) {
            return err ? callback(err) : callback();
          });
        });
      });
    });
  })();
};

//
// ### function showError (command, err, shallow, skip)
// #### @command {string} Command which has errored.
// #### @err {Error} Error received for the command.
// #### @shallow {boolean} Value indicating if a deep stack should be displayed
// #### @skip {boolean} Value indicating if this error should be forcibly suppressed.
// Displays the `err` to the user for the `command` supplied.
//
jitsu.showError = function (command, err, shallow, skip) {
  var stack;

  if (err.statusCode !== '403' && !skip) {
    winston.error('Error running command ' + command.magenta);

    if (!jitsu.config.get('nolog')) {
      jitsu.logFile.log(err);
    }

    if (err.message) {
      winston.error(err.message);
    }

    if (err.result) {
      if (err.result.error) {
        winston.error(err.result.error);
      }

      if (err.result.result && err.result.result.error) {
        if (err.result.result.error.stderr) {
          winston.error('');
          winston.error('There was an error while attempting to start your application.');
          winston.error(err.result.result.error.message);
          if (err.result.result.error.blame) {
            winston.error(err.result.result.error.blame.message);
            winston.error('');
            winston.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }
          winston.error('Error output from your application:');
          winston.error('');
          err.result.result.error.stderr.split('\n').forEach(function (line) {
            winston.error(line);
          })
        }
        else if (err.result.result.error.stack && jitsu.config.get('debug')) {
          winston.error('There was an error while attempting to deploy your application.');
          winston.error('');
          winston.error(err.result.result.error.message);
          if (err.result.result.error.blame) {
            winston.error(err.result.result.error.blame.message);
            winston.error('');
            winston.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }
          winston.error('Error output from Haibu:');
          winston.error('');
          stack = err.result.result.error.result || err.result.result.error.stack;
          stack.split('\n').forEach(function (line) {
            winston.error(line);
          });
        }
      }
      else if (err.result.stack) {
        winston.warn('Error returned from Nodejitsu');
        err.result.stack.split('\n').forEach(function (line) {
          winston.error(line);
        })
      }
    }
    else {
      if (err.stack && !shallow) {
        err.stack.split('\n').forEach(function (trace) {
          winston.error(trace);
        });
      }
    }
  }

  winston.info('Nodejitsu '.grey + 'not ok'.red.bold);
};
<commit_msg>[fix] Fix for error reporting edge-case.<commit_after>/*
 * jitsu.js: Top-level include for the jitsu module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var jitsu = exports;

var path = require('path');

// Failure HTTP Response codes based
// off of `/lib/broodmother/slave/service.js`
var failCodes = jitsu.failCodes = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Not Authorized',
  404: 'Item not found',
  409: 'Conflict',
  500: 'Internal Server Error'
};

// Success HTTP Response codes based
// off of `/lib/broodmother/slave/service.js`
var successCodes = jitsu.successCodes = {
  200: 'OK',
  201: 'Created'
};

jitsu.skipAuth          = false;
jitsu.started           = false;
jitsu.utils             = require('./jitsu/utils');
jitsu.package           = require('./jitsu/package');
jitsu.log               = require('cliff');
jitsu.logFile           = new (require('./jitsu/utils/logfile').LogFile)(path.join(process.env.HOME, '.jitsulog'));
jitsu.api               = {};
jitsu.api.Client        = require('nodejitsu-api').Client;
jitsu.api.Apps          = require('nodejitsu-api').Apps;
jitsu.api.Databases     = require('nodejitsu-api').Databases;
jitsu.api.Logs          = require('nodejitsu-api').Logs;
jitsu.api.Snapshots     = require('nodejitsu-api').Snapshots;
jitsu.api.Users         = require('nodejitsu-api').Users;
jitsu.prompt            = require('prompt');
jitsu.prompt.properties = require('./jitsu/properties').properties;
jitsu.prompt.override   = require('optimist').argv;
jitsu.config            = require('./jitsu/config');
jitsu.commands          = require('./jitsu/commands');

//
// Alias the appropriate commands for simplier CLI usage
//
jitsu.commands.alias('create', { resource: 'apps',   command: 'create' });
jitsu.commands.alias('deploy', { resource: 'apps',   command: 'deploy' });
jitsu.commands.alias('list',   { resource: 'apps',   command: 'list' });
jitsu.commands.alias('conf',   { resource: 'config', command: 'list' });
jitsu.commands.alias('login',  { resource: 'users',  command: 'login' });
jitsu.commands.alias('logout', { resource: 'users',  command: 'logout' });
jitsu.commands.alias('signup', { resource: 'users',  command: 'create' });
jitsu.commands.alias('whoami', { resource: 'users',  command: 'whoami' });

var eyes = require('eyes'),
    winston = require('winston'),
    colors = require('colors');

//
// Setup `jitsu` to use `pkginfo` to expose version
//
require('pkginfo')(module, 'version');

//
// ### function start (command, callback)
// #### @command {string} Command to execute once started
// #### @callback {function} Continuation to pass control to when complete.
// Starts the jitsu CLI and runs the specified command.
//
jitsu.start = function (argv, callback) {
  var command = argv._;

  //
  // Special -v command for showing current version without winston formatting
  //
  if (argv.version || argv.v) {
    console.log('v' + jitsu.version);
    process.exit(0);
  }

  //
  // Check for --no-colors/--colors option, without hitting the config file
  // yet
  //
  (typeof argv.colors == "undefined" || argv.colors) || (colors.mode = "none");

  // Setup the initial prompt but don't leave it open
  jitsu.prompt.start().pause();

  //
  // Default to the `help` command.
  //
  command[0] || (command[0] = 'help');

  jitsu.utils.checkVersion(function (err) {
    if (err) return callback();
    jitsu.config.load(function (err) {
      if (err) {
        jitsu.welcome();
        callback(err);
        return jitsu.showError.apply(null, [command[0]].concat(arguments));
      }

      //
      // --no-colors option turns off output coloring, and so does setting
      // colors: false in ~/.jitsuconf (see
      // https://github.com/nodejitsu/jitsu/issues/101 )
      //
      jitsu.config.get('colors') || (colors.mode = "none");

      jitsu.welcome();

      var username = jitsu.config.get('username');
      if (!username && jitsu.commands.requiresAuth(command[0])) {
        return jitsu.setupUser(function (err) {
          if (err) {
            callback(err);
            return jitsu.showError.apply(jitsu, [command[0]].concat(arguments));
          }

          var username = jitsu.config.get('username');
          winston.info('Successfully configured user ' + username.magenta);
          return command.length > 0 ? jitsu.exec(command, callback) : callback();
        });
      }

      return jitsu.exec(command, callback)
    });
  });
};

//
// ### function welcome ()
// Print welcome message.
//
jitsu.welcome = function () {
  winston.info('Welcome to ' + 'Nodejitsu'.grey);
  winston.info('It worked if it ends with ' + 'Nodejitsu'.grey + ' ok'.green.bold);
};

//
// ### function exec (command, callback)
// #### @command {string} Command to execute
// #### @callback {function} Continuation to pass control to when complete.
// Runs the specified command in the jitsu CLI.
//
jitsu.exec = function (command, callback) {
  function execCommand (err) {
    if (err) {
      return callback(err);
    }

    //
    // Remark: This is a temporary fix for aliasing init=>install,
    // was having a few issues with the alias command on the install resource
    //
    if (command[0] === 'init'){
      command[0] = 'install';
    }

    // Alias db to databases
    if (command[0] === 'db'){
      command[0] = 'databases';
    }

    // Allow `jitsu logs` as a shortcut for `jitsu logs app`
    if (command[0] === 'logs' && command.length === 1) {
      command[1] = 'app';
    }

    winston.info('Executing command ' + command.join(' ').magenta);
    jitsu.commands.run(command, function (err, shallow) {
      if (err) {
        callback(err);
        return jitsu.showError(command.join(' '), err, shallow);
      }

      //
      // TODO (indexzero): Something here
      //
      callback();
    });
  }

  return !jitsu.started ? jitsu.setup(execCommand) : execCommand();
};

//
// ### function setup (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Sets up the instances of the Resource clients for jitsu.
// there is no io here, yet this function is ASYNC.
//
jitsu.setup = function (callback) {
  if (jitsu.started === true) {
    return callback();
  }

  jitsu.users = new jitsu.api.Users(jitsu.config);
  jitsu.apps = new jitsu.api.Apps(jitsu.config);
  jitsu.snapshots = new jitsu.api.Snapshots(jitsu.config);
  jitsu.databases = new jitsu.api.Databases(jitsu.config);
  jitsu.logs = new jitsu.api.Logs(jitsu.config);
  jitsu.started = true;

  callback();
};

//
// ### function auth (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Attempts to authenicate the user identified in `jitsu.config.get('username'|'password')`
//
jitsu.auth = function (callback) {
  if (jitsu.skipAuth) {
    return callback();
  }

  var username = jitsu.config.get('username');
  winston.silly('Attempting to authenticate as ' + username.magenta);
  jitsu.users.auth(function (err, success) {
    if (err || !success) {
      winston.error('Unable to Authenticate as ' + username.magenta);
      winston.error(err.message);
      return callback(err);
    }

    jitsu.skipAuth = true;
    winston.info('Authenticated as ' + username.magenta);
    return callback();
  })
}

//
// ### function setupUser (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk.
//
jitsu.setupUser = function (callback) {
  winston.warn('You will need to login to continue');
  winston.info('To login, you will need an activated nodejitsu account');
  winston.help('You can create an account using the ' + 'jitsu signup'.magenta + ' command');
  jitsu.setupUserNoWarn(callback);
};

//
// ### function setupUserNoWarn (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk without a warning
//
jitsu.setupUserNoWarn = function(callback) {
  //
  // Attempt to get the password three times.
  //
  var tries = 0;

  function offerReset (username) {
    jitsu.prompt.get(['reset'], function (err, res) {
      if (err) {
        return callback(err);
      }
      if (/^y[es]+/i.test(res['request password reset'])) {
        return jitsu.commands.run(['users', 'forgot', username], callback);
      }

      callback(new Error('Invalid username / password.'));
    });
  }

  (function setupAuth () {
    jitsu.prompt.get(['username', 'password'], function (err, result) {
      if (err) {
        return callback(err);
      }

      jitsu.config.set('username', result.username);
      jitsu.config.set('password', result.password);
      jitsu.setup(function () {
        jitsu.auth(function (err) {
          //
          // Increment the auth attempts
          //
          tries += 1;

          if (err) {
            if (tries >= 3) {
              winston.error('Three failed login attempts');
              winston.info('Would you like to reset your password?');
              return offerReset(result.username);
            }
            return setupAuth();
          }

          jitsu.config.save(function (err) {
            return err ? callback(err) : callback();
          });
        });
      });
    });
  })();
};

//
// ### function showError (command, err, shallow, skip)
// #### @command {string} Command which has errored.
// #### @err {Error} Error received for the command.
// #### @shallow {boolean} Value indicating if a deep stack should be displayed
// #### @skip {boolean} Value indicating if this error should be forcibly suppressed.
// Displays the `err` to the user for the `command` supplied.
//
jitsu.showError = function (command, err, shallow, skip) {
  var stack;

  if (err.statusCode !== '403' && !skip) {
    winston.error('Error running command ' + command.magenta);

    if (!jitsu.config.get('nolog')) {
      jitsu.logFile.log(err);
    }

    if (err.message) {
      winston.error(err.message);
    }

    if (err.result) {
      if (err.result.error) {
        winston.error(err.result.error);
      }

      if (err.result.result && err.result.result.error) {
        if (err.result.result.error.stderr || err.result.result.error.stdout) {
          winston.error('');
          winston.error('There was an error while attempting to start your application.');
          winston.error(err.result.result.error.message);
          if (err.result.result.error.blame) {
            winston.error(err.result.result.error.blame.message);
            winston.error('');
            winston.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }
          winston.error('Error output from your application:');
          winston.error('');
          if (err.result.result.error.stdout) {
            err.result.result.error.stdout.split('\n').forEach(function (line) {
              winston.error(line);
            });
          }
          if (err.result.result.error.stderr) {
            err.result.result.error.stderr.split('\n').forEach(function (line) {
              winston.error(line);
            });
          }
        }
        else if (err.result.result.error.stack && jitsu.config.get('debug')) {
          winston.error('There was an error while attempting to deploy your application.');
          winston.error('');
          winston.error(err.result.result.error.message);
          if (err.result.result.error.blame) {
            winston.error(err.result.result.error.blame.message);
            winston.error('');
            winston.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }
          winston.error('Error output from Haibu:');
          winston.error('');
          stack = err.result.result.error.result || err.result.result.error.stack;
          stack.split('\n').forEach(function (line) {
            winston.error(line);
          });
        }
      }
      else if (err.result.stack) {
        winston.warn('Error returned from Nodejitsu');
        err.result.stack.split('\n').forEach(function (line) {
          winston.error(line);
        });
      }
    }
    else {
      if (err.stack && !shallow) {
        err.stack.split('\n').forEach(function (trace) {
          winston.error(trace);
        });
      }
    }
  }

  winston.info('Nodejitsu '.grey + 'not ok'.red.bold);
};
<|endoftext|>


<commit_before>'use strict'

const gulp = require( 'gulp' )
const babel = require( 'gulp-babel' )

gulp.task( 'default', () =>
  gulp.src( 'src/**/*.js' )
    .pipe( babel( { presets: [ 'es2015' ] } ) )
    .pipe( gulp.dest( 'dist' ) )
)
<commit_msg>Clean up<commit_after><|endoftext|>


<commit_before>var Lexer = require("./lexer")
  , Parser = require("./parser")
  , Compiler = require('./compiler')
  , fs = require('fs')
  , path = require('path')
  , _ = require('underscore');

module.exports = {

  Lexer: Lexer,
  Parser: Parser,
  Compiler: Compiler,

  render: function (source, options) {
    var compiler;
    options = _.defaults((options || {}), defaults());
    compiler = new this.Compiler(source, options);
    return compiler.compile()(options);
  },

  renderFile: function (filename, options) {
    options = _.defaults((options || {}), defaults(filename));
    return this.render(fs.readFileSync(filename, options.encoding), options);
  },

  compile: function (source, options) {
    var compiler;
    options = _.defaults((options || {}), defaults());
    compiler = new this.Compiler(source, options);
    return compiler.compile();
  },

  compileFile: function (filename, options) {
    options = _.defaults((options || {}), defaults(filename));
    return this.compile(fs.readFileSync(filename, options.encoding), options);
  }

};

function defaults (filename) {
  var obj = { encoding: 'utf8', basepath: __dirname };
  if (filename) { obj.basepath = path.dirname(filename); }
  return obj;
}
<commit_msg>condensing<commit_after>var Lexer = require("./lexer")
  , Parser = require("./parser")
  , Compiler = require('./compiler')
  , fs = require('fs')
  , path = require('path')
  , _ = require('underscore');

module.exports = {

  Lexer: Lexer,
  Parser: Parser,
  Compiler: Compiler,

  render: function (source, options) {
    var options = opts(options)
      , compiler = new this.Compiler(source, options);
    return compiler.compile()(options);
  },

  renderFile: function (filename, options) {
    options = opts(options, filename);
    return this.render(fs.readFileSync(filename, options.encoding), options);
  },

  compile: function (source, options) {
    var compiler = new this.Compiler(source, opts(options));
    return compiler.compile();
  },

  compileFile: function (filename, options) {
    options = opts(options, filename);
    return this.compile(fs.readFileSync(filename, options.encoding), options);
  }

};

function opts(options, filename) {
  var defaults = { encoding: 'utf8', basepath: __dirname };
  if (filename) { defaults.basepath = path.dirname(filename); }
  return _.defaults((options || {}), defaults);
}
<|endoftext|>


<commit_before>"use strict";

function Sandwich() {
    // TODO: Create Sandwich class
}

module.exports = {
    Sandwich: Sandwich,
    Recipe: {/* TODO: Create Recipie class */},
    Topping: {/* TODO: Create Topping class */}
};
<commit_msg>Change todo comments<commit_after>"use strict";

function Sandwich() {
    // TODO: Create Sandwich class
}

module.exports = {
    Sandwich: Sandwich,
    Recipe: null, // TODO: Create Recipie class
    Topping: null // TODO: Create Topping class
};
<|endoftext|>


<commit_before>
var dom      = exports.dom = require("./jsdom/level3/index").dom,
    features = require('./jsdom/browser/documentfeatures'),
    fs       = require("fs"),
    pkg      = JSON.parse(fs.readFileSync(__dirname + "/../package.json")),
    request  = require('request'),
    URL      = require('url');

var style = require('./jsdom/level2/style');
exports.defaultLevel = dom.level3.html;
exports.browserAugmentation = require("./jsdom/browser/index").browserAugmentation;
exports.windowAugmentation = require("./jsdom/browser/index").windowAugmentation;

// Proxy feature functions to features module.
['availableDocumentFeatures',
 'defaultDocumentFeatures',
 'applyDocumentFeatures'].forEach(function (propName) {
  exports.__defineGetter__(propName, function () {
    return features[propName];
  });
  exports.__defineSetter__(propName, function (val) {
    return features[propName] = val;
  });
});

exports.debugMode = false;

var createWindow = exports.createWindow = require("./jsdom/browser/index").createWindow;

exports.__defineGetter__('version', function() {
  return pkg.version;
});

exports.level = function (level, feature) {
	if(!feature) feature = 'core'
	return require('./jsdom/level' + level + '/' + feature).dom['level' + level][feature]
}

exports.jsdom = function (html, level, options) {

  options = options || {};
  if(typeof level == "string") {
    level = exports.level(level, 'html')
  } else {
    level   = level || exports.defaultLevel;
  }

  if (!options.url) {
    options.url = (module.parent.id === 'jsdom') ?
                  module.parent.parent.filename  :
                  module.parent.filename;
  }

  if (options.features && options.features.QuerySelector) {
    require("./jsdom/selectors/index").applyQuerySelectorPrototype(level);
  }

  var browser = exports.browserAugmentation(level, options),
      doc     = (browser.HTMLDocument)             ?
                 new browser.HTMLDocument(options) :
                 new browser.Document(options);

  features.applyDocumentFeatures(doc, options.features);

  if (typeof html === 'undefined' || html === null) {
    doc.write('');
  } else {
    doc.write(html + '');
  }

  if (doc.close && !options.deferClose) {
    doc.close();
  }

  // Kept for backwards-compatibility. The window is lazily created when
  // document.parentWindow or document.defaultView is accessed.
  doc.createWindow = function() {
    // Remove ourself
    if (doc.createWindow) {
      delete doc.createWindow;
    }
    return doc.parentWindow;
  };

  return doc;
};

exports.html = function(html, level, options) {
  html += '';

  // TODO: cache a regex and use it here instead
  //       or make the parser handle it
  var htmlLowered = html.toLowerCase();

  // body
  if (!~htmlLowered.indexOf('<body')) {
    html = '' + html + '';
  }

  // html
  if (!~htmlLowered.indexOf('<html')) {
    html = '' + html + '';
  }
  return exports.jsdom(html, level, options);
};

exports.jQueryify = exports.jsdom.jQueryify = function (window /* path [optional], callback */) {

  if (!window || !window.document) { return; }

  var args = Array.prototype.slice.call(arguments),
      callback = (typeof(args[args.length - 1]) === 'function') && args.pop(),
      path,
      jQueryTag = window.document.createElement("script");

  if (args.length > 1 && typeof(args[1] === 'string')) {
    path = args[1];
  }

  var features = window.document.implementation._features;

  window.document.implementation.addFeature('FetchExternalResources', ['script']);
  window.document.implementation.addFeature('ProcessExternalResources', ['script']);
  window.document.implementation.addFeature('MutationEvents', ["1.0"]);
  jQueryTag.src = path || 'http://code.jquery.com/jquery-latest.js';
  window.document.body.appendChild(jQueryTag);

  jQueryTag.onload = function() {
    if (callback) {
      callback(window, window.jQuery);
    }

    window.document.implementation._features = features;
  };

  return window;
};

exports.env = exports.jsdom.env = function() {
  var
  args        = Array.prototype.slice.call(arguments),
  config      = exports.env.processArguments(args),
  callback    = config.done,
  processHTML = function(err, html) {

    html += '';
    if(err) {
      return callback(err);
    }

    config.scripts = config.scripts || [];
    if (typeof config.scripts === 'string') {
      config.scripts = [config.scripts];
    }

    config.src = config.src || [];
    if (typeof config.src === 'string') {
      config.src = [config.src];
    }

    var
    options    = {
      features: {
        'FetchExternalResources' : false,
        'ProcessExternalResources' : false
      },
      url: config.url
    },
    window     = exports.html(html, null, options).createWindow(),
    features   = window.document.implementation._features,
    docsLoaded = 0,
    totalDocs  = config.scripts.length,
    readyState = null,
    errors     = null;

    if (!window || !window.document) {
      return callback(new Error('JSDOM: a window object could not be created.'));
    }

    window.document.implementation.addFeature('FetchExternalResources', ['script']);
    window.document.implementation.addFeature('ProcessExternalResources', ['script']);
    window.document.implementation.addFeature('MutationEvents', ['1.0']);

    var scriptComplete = function() {
      docsLoaded++;
      if (docsLoaded >= totalDocs) {
        window.document.implementation._features = features;
        callback(errors, window);
      }
    }

    if (config.scripts.length > 0 || config.src.length > 0) {
      config.scripts.forEach(function(src) {
        var script = window.document.createElement('script');
        script.onload = function() {
          scriptComplete()
        };

        script.onerror = function(e) {
          if (!errors) {
            errors = [];
          }
          errors.push(e.error);
          scriptComplete();
        };

        script.src = src;
        try {
          // project against invalid dom
          // ex: http://www.google.com/foo#bar
          window.document.documentElement.appendChild(script);
        } catch(e) {
          if(!errors) {
            errors=[];
          }
          errors.push(e.error || e.message);
          callback(errors, window);
        }
      });

      config.src.forEach(function(src) {
        var script = window.document.createElement('script');
        script.onload = function() {
          process.nextTick(scriptComplete);
        };

        script.onerror = function(e) {
          if (!errors) {
            errors = [];
          }
          errors.push(e.error || e.message);
          // nextTick so that an exception within scriptComplete won't cause
          // another script onerror (which would be an infinite loop)
          process.nextTick(scriptComplete);
        };

        script.text = src;
        window.document.documentElement.appendChild(script);
        window.document.documentElement.removeChild(script);
      });
    } else {
      callback(errors, window);
    }
  };

  config.html += '';

  // Handle markup
  if (config.html.indexOf("\n") > 0 || config.html.match(/^\W*</)) {
    processHTML(null, config.html);

  // Handle url/file
  } else {
    var url = URL.parse(config.html);
    config.url = config.url || url.href;
    if (url.hostname) {
      request({ uri: url,
                encoding: config.encoding || 'utf8',
                headers: config.headers || {}
              },
              function(err, request, body) {
                processHTML(err, body);
      });
    } else {
      fs.readFile(url.pathname, processHTML);
    }
  }
};

/*
  Since jsdom.env() is a helper for quickly and easily setting up a
  window with scripts and such already loaded into it, the arguments
  should be fairly flexible.  Here are the requirements

  1) collect `html` (url, string, or file on disk)  (STRING)
  2) load `code` into the window (array of scripts) (ARRAY)
  3) callback when resources are `done`             (FUNCTION)
  4) configuration                                  (OBJECT)

  Rules:
  + if there is one argument it had better be an object with atleast
    a `html` and `done` property (other properties are gravy)

  + arguments above are pulled out of the arguments and put into the
    config object that is returned
*/
exports.env.processArguments = function(args) {
  if (!args || !args.length || args.length < 1) {
    throw new Error('No arguments passed to jsdom.env().');
  }

  var
  props = {
    'html'    : true,
    'done'    : true,
    'scripts' : false,
    'config'  : false,
    'url'     : false  // the URL for location.href if different from html
  },
  propKeys = Object.keys(props),
  config = {
    code : []
  },
  l    = args.length
  ;
  if (l === 1) {
    config = args[0];
  } else {
    args.forEach(function(v) {
      var type = typeof v;
      if (!v) {
        return;
      }
      if (type === 'string' || v + '' === v) {
        config.html = v;
      } else if (type === 'object') {
        // Array
        if (v.length && v[0]) {
          config.scripts = v;
        } else {
          // apply missing required properties if appropriate
          propKeys.forEach(function(req) {

            if (typeof v[req] !== 'undefined' &&
                typeof config[req] === 'undefined') {

              config[req] = v[req];
              delete v[req];
            }
          });
          config.config = v;
        }
      } else if (type === 'function') {
        config.done = v;
      }
    });
  }

  propKeys.forEach(function(req) {
    var required = props[req];
    if (required && typeof config[req] === 'undefined') {
      throw new Error("jsdom.env requires a '" + req + "' argument");
    }
  });
  return config;
};
<commit_msg>Land: jsdom.env() may now be passed a features object<commit_after>
var dom      = exports.dom = require("./jsdom/level3/index").dom,
    features = require('./jsdom/browser/documentfeatures'),
    fs       = require("fs"),
    pkg      = JSON.parse(fs.readFileSync(__dirname + "/../package.json")),
    request  = require('request'),
    URL      = require('url');

var style = require('./jsdom/level2/style');
exports.defaultLevel = dom.level3.html;
exports.browserAugmentation = require("./jsdom/browser/index").browserAugmentation;
exports.windowAugmentation = require("./jsdom/browser/index").windowAugmentation;

// Proxy feature functions to features module.
['availableDocumentFeatures',
 'defaultDocumentFeatures',
 'applyDocumentFeatures'].forEach(function (propName) {
  exports.__defineGetter__(propName, function () {
    return features[propName];
  });
  exports.__defineSetter__(propName, function (val) {
    return features[propName] = val;
  });
});

exports.debugMode = false;

var createWindow = exports.createWindow = require("./jsdom/browser/index").createWindow;

exports.__defineGetter__('version', function() {
  return pkg.version;
});

exports.level = function (level, feature) {
	if(!feature) feature = 'core'
	return require('./jsdom/level' + level + '/' + feature).dom['level' + level][feature]
}

exports.jsdom = function (html, level, options) {

  options = options || {};
  if(typeof level == "string") {
    level = exports.level(level, 'html')
  } else {
    level   = level || exports.defaultLevel;
  }

  if (!options.url) {
    options.url = (module.parent.id === 'jsdom') ?
                  module.parent.parent.filename  :
                  module.parent.filename;
  }

  if (options.features && options.features.QuerySelector) {
    require("./jsdom/selectors/index").applyQuerySelectorPrototype(level);
  }

  var browser = exports.browserAugmentation(level, options),
      doc     = (browser.HTMLDocument)             ?
                 new browser.HTMLDocument(options) :
                 new browser.Document(options);

  features.applyDocumentFeatures(doc, options.features);

  if (typeof html === 'undefined' || html === null) {
    doc.write('');
  } else {
    doc.write(html + '');
  }

  if (doc.close && !options.deferClose) {
    doc.close();
  }

  // Kept for backwards-compatibility. The window is lazily created when
  // document.parentWindow or document.defaultView is accessed.
  doc.createWindow = function() {
    // Remove ourself
    if (doc.createWindow) {
      delete doc.createWindow;
    }
    return doc.parentWindow;
  };

  return doc;
};

exports.html = function(html, level, options) {
  html += '';

  // TODO: cache a regex and use it here instead
  //       or make the parser handle it
  var htmlLowered = html.toLowerCase();

  // body
  if (!~htmlLowered.indexOf('<body')) {
    html = '' + html + '';
  }

  // html
  if (!~htmlLowered.indexOf('<html')) {
    html = '' + html + '';
  }
  return exports.jsdom(html, level, options);
};

exports.jQueryify = exports.jsdom.jQueryify = function (window /* path [optional], callback */) {

  if (!window || !window.document) { return; }

  var args = Array.prototype.slice.call(arguments),
      callback = (typeof(args[args.length - 1]) === 'function') && args.pop(),
      path,
      jQueryTag = window.document.createElement("script");

  if (args.length > 1 && typeof(args[1] === 'string')) {
    path = args[1];
  }

  var features = window.document.implementation._features;

  window.document.implementation.addFeature('FetchExternalResources', ['script']);
  window.document.implementation.addFeature('ProcessExternalResources', ['script']);
  window.document.implementation.addFeature('MutationEvents', ["1.0"]);
  jQueryTag.src = path || 'http://code.jquery.com/jquery-latest.js';
  window.document.body.appendChild(jQueryTag);

  jQueryTag.onload = function() {
    if (callback) {
      callback(window, window.jQuery);
    }

    window.document.implementation._features = features;
  };

  return window;
};

exports.env = exports.jsdom.env = function() {
  var
  args        = Array.prototype.slice.call(arguments),
  config      = exports.env.processArguments(args),
  callback    = config.done,
  processHTML = function(err, html) {

    html += '';
    if(err) {
      return callback(err);
    }

    config.scripts = config.scripts || [];
    if (typeof config.scripts === 'string') {
      config.scripts = [config.scripts];
    }

    config.src = config.src || [];
    if (typeof config.src === 'string') {
      config.src = [config.src];
    }

    var
    options    = {
      features: config.features || {
        'FetchExternalResources' : false,
        'ProcessExternalResources' : false
      },
      url: config.url
    },
    window     = exports.html(html, null, options).createWindow(),
    features   = window.document.implementation._features,
    docsLoaded = 0,
    totalDocs  = config.scripts.length,
    readyState = null,
    errors     = null;

    if (!window || !window.document) {
      return callback(new Error('JSDOM: a window object could not be created.'));
    }

    window.document.implementation.addFeature('FetchExternalResources', ['script']);
    window.document.implementation.addFeature('ProcessExternalResources', ['script']);
    window.document.implementation.addFeature('MutationEvents', ['1.0']);

    var scriptComplete = function() {
      docsLoaded++;
      if (docsLoaded >= totalDocs) {
        window.document.implementation._features = features;
        callback(errors, window);
      }
    }

    if (config.scripts.length > 0 || config.src.length > 0) {
      config.scripts.forEach(function(src) {
        var script = window.document.createElement('script');
        script.onload = function() {
          scriptComplete()
        };

        script.onerror = function(e) {
          if (!errors) {
            errors = [];
          }
          errors.push(e.error);
          scriptComplete();
        };

        script.src = src;
        try {
          // project against invalid dom
          // ex: http://www.google.com/foo#bar
          window.document.documentElement.appendChild(script);
        } catch(e) {
          if(!errors) {
            errors=[];
          }
          errors.push(e.error || e.message);
          callback(errors, window);
        }
      });

      config.src.forEach(function(src) {
        var script = window.document.createElement('script');
        script.onload = function() {
          process.nextTick(scriptComplete);
        };

        script.onerror = function(e) {
          if (!errors) {
            errors = [];
          }
          errors.push(e.error || e.message);
          // nextTick so that an exception within scriptComplete won't cause
          // another script onerror (which would be an infinite loop)
          process.nextTick(scriptComplete);
        };

        script.text = src;
        window.document.documentElement.appendChild(script);
        window.document.documentElement.removeChild(script);
      });
    } else {
      callback(errors, window);
    }
  };

  config.html += '';

  // Handle markup
  if (config.html.indexOf("\n") > 0 || config.html.match(/^\W*</)) {
    processHTML(null, config.html);

  // Handle url/file
  } else {
    var url = URL.parse(config.html);
    config.url = config.url || url.href;
    if (url.hostname) {
      request({ uri: url,
                encoding: config.encoding || 'utf8',
                headers: config.headers || {}
              },
              function(err, request, body) {
                processHTML(err, body);
      });
    } else {
      fs.readFile(url.pathname, processHTML);
    }
  }
};

/*
  Since jsdom.env() is a helper for quickly and easily setting up a
  window with scripts and such already loaded into it, the arguments
  should be fairly flexible.  Here are the requirements

  1) collect `html` (url, string, or file on disk)  (STRING)
  2) load `code` into the window (array of scripts) (ARRAY)
  3) callback when resources are `done`             (FUNCTION)
  4) configuration                                  (OBJECT)

  Rules:
  + if there is one argument it had better be an object with atleast
    a `html` and `done` property (other properties are gravy)

  + arguments above are pulled out of the arguments and put into the
    config object that is returned
*/
exports.env.processArguments = function(args) {
  if (!args || !args.length || args.length < 1) {
    throw new Error('No arguments passed to jsdom.env().');
  }

  var
  props = {
    'html'    : true,
    'done'    : true,
    'scripts' : false,
    'config'  : false,
    'url'     : false  // the URL for location.href if different from html
  },
  propKeys = Object.keys(props),
  config = {
    code : []
  },
  l    = args.length
  ;
  if (l === 1) {
    config = args[0];
  } else {
    args.forEach(function(v) {
      var type = typeof v;
      if (!v) {
        return;
      }
      if (type === 'string' || v + '' === v) {
        config.html = v;
      } else if (type === 'object') {
        // Array
        if (v.length && v[0]) {
          config.scripts = v;
        } else {
          // apply missing required properties if appropriate
          propKeys.forEach(function(req) {

            if (typeof v[req] !== 'undefined' &&
                typeof config[req] === 'undefined') {

              config[req] = v[req];
              delete v[req];
            }
          });
          config.config = v;
        }
      } else if (type === 'function') {
        config.done = v;
      }
    });
  }

  propKeys.forEach(function(req) {
    var required = props[req];
    if (required && typeof config[req] === 'undefined') {
      throw new Error("jsdom.env requires a '" + req + "' argument");
    }
  });
  return config;
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var nano = require('gulp-cssnano');
var discard_comments = require('postcss-discard-comments');
var combine_duplicated_selectors = require('postcss-combine-duplicated-selectors');
var sorting = require('postcss-sorting');
var less = require('gulp-less');

var APP_VERSION = '1.4.0';
var BUILD_PATH = 'public/build/' + APP_VERSION;
var VENDOR_ASSETS_PATH = 'public/assets/vendor/';
var JS_ASSETS_PATH = 'public/assets/js/';
var CSS_ASSETS_PATH = 'public/assets/css/';
var LESS_ASSETS_PATH = 'public/assets/less/';
var SEMANTIC_VERSION = '2.3.1';
var SEMANTIC_PATH = VENDOR_ASSETS_PATH + 'semantic/' + SEMANTIC_VERSION + '/components/';
var PRISM_VERSION = '1.15.0';

var loaderCss = function () {
    return gulp.src([
        CSS_ASSETS_PATH + 'loader.css'
    ])
        .pipe(concat('lo.css'))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var fontsCss = function () {
    return gulp.src([
        CSS_ASSETS_PATH + 'fonts.css'
    ])
        .pipe(concat('fo.css'))
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var old__frontendCss = function () {
    return gulp.src([
        SEMANTIC_PATH + 'reset.css',
        SEMANTIC_PATH + 'site.css',
        SEMANTIC_PATH + 'container.css',
        SEMANTIC_PATH + 'divider.css',
        SEMANTIC_PATH + 'header.css',
        SEMANTIC_PATH + 'image.css',
        SEMANTIC_PATH + 'list.css',
        SEMANTIC_PATH + 'segment.css',
        SEMANTIC_PATH + 'breadcrumb.css',
        SEMANTIC_PATH + 'grid.css',
        SEMANTIC_PATH + 'menu.css',
        CSS_ASSETS_PATH + 'frontend.css'
    ])
        .pipe(concat('f.css'))
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var frontendCss = function () {
    return gulp.src([
        LESS_ASSETS_PATH + 'overrides/semantic/semantic.less',
        CSS_ASSETS_PATH + 'frontend.css'
    ])
        .pipe(concat('f.css'))
        .pipe(less())
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var frontendJs = function () {
    return gulp.src([
        JS_ASSETS_PATH + 'frontend.js'
    ])
        .pipe(concat('f.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var highlightCss = function () {
    return gulp.src([
        VENDOR_ASSETS_PATH + 'prism/' + PRISM_VERSION + '/prism.css'
    ])
        .pipe(concat('h.css'))
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var highlightJs = function () {
    return gulp.src([
        VENDOR_ASSETS_PATH + 'prism/' + PRISM_VERSION + '/prism.js',
        JS_ASSETS_PATH + 'highlight.js'
    ])
        .pipe(concat('h.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var countersJs = function () {
    return gulp.src([
        JS_ASSETS_PATH + 'counters.js'
    ])
        .pipe(concat('c.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var svgIconsLoaderJs = function () {
    return gulp.src([
        JS_ASSETS_PATH + 'icons-loader.js'
    ])
        .pipe(concat('ilo.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var svgSprite = function () {
    var svgstore = require('gulp-svgstore');
    var svgmin = require('gulp-svgmin');
    var rename = require('gulp-rename');

    return gulp.src('public/assets/img/icons/*.svg')
        .pipe(rename({prefix: 'fi-'}))
        .pipe(svgmin())
        .pipe(svgstore({
            inlineSvg: true
        }))
        .pipe(gulp.dest(BUILD_PATH));
};

gulp.task('loader css', gulp.parallel(loaderCss));
gulp.task('fonts css', gulp.parallel(fontsCss));
gulp.task('frontend css', gulp.parallel(frontendCss));
gulp.task('highlight css', gulp.parallel(highlightCss));
gulp.task('highlight js', gulp.parallel(highlightJs));
gulp.task('counters js', gulp.parallel(countersJs));
gulp.task('svg icons loader js', gulp.parallel(svgIconsLoaderJs));
gulp.task('svg sprite', gulp.parallel(svgSprite));

gulp.task('PRODUCTION', gulp.parallel(
    loaderCss,
    fontsCss,
    frontendCss,
    highlightCss,
    highlightJs,
    countersJs,
    svgIconsLoaderJs,
    svgSprite
));
<commit_msg>tag version 1.4.1<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var nano = require('gulp-cssnano');
var discard_comments = require('postcss-discard-comments');
var combine_duplicated_selectors = require('postcss-combine-duplicated-selectors');
var sorting = require('postcss-sorting');
var less = require('gulp-less');

var APP_VERSION = '1.4.1';
var BUILD_PATH = 'public/build/' + APP_VERSION;
var VENDOR_ASSETS_PATH = 'public/assets/vendor/';
var JS_ASSETS_PATH = 'public/assets/js/';
var CSS_ASSETS_PATH = 'public/assets/css/';
var LESS_ASSETS_PATH = 'public/assets/less/';
var SEMANTIC_VERSION = '2.3.1';
var SEMANTIC_PATH = VENDOR_ASSETS_PATH + 'semantic/' + SEMANTIC_VERSION + '/components/';
var PRISM_VERSION = '1.15.0';

var loaderCss = function () {
    return gulp.src([
        CSS_ASSETS_PATH + 'loader.css'
    ])
        .pipe(concat('lo.css'))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var fontsCss = function () {
    return gulp.src([
        CSS_ASSETS_PATH + 'fonts.css'
    ])
        .pipe(concat('fo.css'))
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var old__frontendCss = function () {
    return gulp.src([
        SEMANTIC_PATH + 'reset.css',
        SEMANTIC_PATH + 'site.css',
        SEMANTIC_PATH + 'container.css',
        SEMANTIC_PATH + 'divider.css',
        SEMANTIC_PATH + 'header.css',
        SEMANTIC_PATH + 'image.css',
        SEMANTIC_PATH + 'list.css',
        SEMANTIC_PATH + 'segment.css',
        SEMANTIC_PATH + 'breadcrumb.css',
        SEMANTIC_PATH + 'grid.css',
        SEMANTIC_PATH + 'menu.css',
        CSS_ASSETS_PATH + 'frontend.css'
    ])
        .pipe(concat('f.css'))
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var frontendCss = function () {
    return gulp.src([
        LESS_ASSETS_PATH + 'overrides/semantic/semantic.less',
        CSS_ASSETS_PATH + 'frontend.css'
    ])
        .pipe(concat('f.css'))
        .pipe(less())
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var frontendJs = function () {
    return gulp.src([
        JS_ASSETS_PATH + 'frontend.js'
    ])
        .pipe(concat('f.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var highlightCss = function () {
    return gulp.src([
        VENDOR_ASSETS_PATH + 'prism/' + PRISM_VERSION + '/prism.css'
    ])
        .pipe(concat('h.css'))
        .pipe(postcss([
            discard_comments({removeAll: true}),
            combine_duplicated_selectors(),
            autoprefixer(),
            sorting()
        ]))
        .pipe(nano())
        .pipe(gulp.dest(BUILD_PATH));
};

var highlightJs = function () {
    return gulp.src([
        VENDOR_ASSETS_PATH + 'prism/' + PRISM_VERSION + '/prism.js',
        JS_ASSETS_PATH + 'highlight.js'
    ])
        .pipe(concat('h.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var countersJs = function () {
    return gulp.src([
        JS_ASSETS_PATH + 'counters.js'
    ])
        .pipe(concat('c.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var svgIconsLoaderJs = function () {
    return gulp.src([
        JS_ASSETS_PATH + 'icons-loader.js'
    ])
        .pipe(concat('ilo.js'))
        .pipe(uglify())
        .pipe(gulp.dest(BUILD_PATH));
};

var svgSprite = function () {
    var svgstore = require('gulp-svgstore');
    var svgmin = require('gulp-svgmin');
    var rename = require('gulp-rename');

    return gulp.src('public/assets/img/icons/*.svg')
        .pipe(rename({prefix: 'fi-'}))
        .pipe(svgmin())
        .pipe(svgstore({
            inlineSvg: true
        }))
        .pipe(gulp.dest(BUILD_PATH));
};

gulp.task('loader css', gulp.parallel(loaderCss));
gulp.task('fonts css', gulp.parallel(fontsCss));
gulp.task('frontend css', gulp.parallel(frontendCss));
gulp.task('highlight css', gulp.parallel(highlightCss));
gulp.task('highlight js', gulp.parallel(highlightJs));
gulp.task('counters js', gulp.parallel(countersJs));
gulp.task('svg icons loader js', gulp.parallel(svgIconsLoaderJs));
gulp.task('svg sprite', gulp.parallel(svgSprite));

gulp.task('PRODUCTION', gulp.parallel(
    loaderCss,
    fontsCss,
    frontendCss,
    highlightCss,
    highlightJs,
    countersJs,
    svgIconsLoaderJs,
    svgSprite
));
<|endoftext|>


<commit_before>'use strict';

const Path = require('path');

const Hapi = require('@hapi/hapi');
const Hoek = require('@hapi/hoek');
const Joi = require('@hapi/joi');

const internals = {};

internals.schema = {
    options: Joi.object({
        relativeTo: Joi.string(),
        preRegister: Joi.func().allow(false)
    }),
    manifest: Joi.object({
        server: Joi.object(),
        register: Joi.object({
            plugins: Joi.array(),
            options: Joi.any()
        })
    })
};

exports.compose = async function (manifest, options = {}) {

    Joi.assert(options, internals.schema.options, 'Invalid options');
    Joi.assert(manifest, internals.schema.manifest, 'Invalid manifest');

    const serverOpts = internals.parseServer(manifest.server || {}, options.relativeTo);
    const server = Hapi.server(serverOpts);

    if (options.preRegister) {
        await options.preRegister(server);
    }

    if (manifest.register && manifest.register.plugins) {
        const plugins = manifest.register.plugins.map((plugin) => {

            return internals.parsePlugin(plugin, options.relativeTo);
        });

        await server.register(plugins, manifest.register.options || {});
    }

    return server;
};

internals.parseServer = function (serverOpts, relativeTo) {

    if (serverOpts.cache) {
        serverOpts = Hoek.clone(serverOpts);

        const caches = [];
        const config = [].concat(serverOpts.cache);
        for (let i = 0; i < config.length; ++i) {
            let item = config[i];
            if (typeof item === 'string') {
                item = { provider: item };
            }

            if (typeof item.provider === 'string') {
                let strategy = item.provider;
                if (relativeTo && strategy[0] === '.') {
                    strategy = Path.join(relativeTo, strategy);
                }

                item.provider = require(strategy);
            }

            caches.push(item);
        }

        serverOpts.cache = caches;
    }

    return serverOpts;
};

internals.parsePlugin = function (plugin, relativeTo) {

    if (typeof plugin === 'string') {
        return internals.requireRelativeTo(plugin, relativeTo);
    }

    if (typeof plugin.plugin === 'string') {
        const pluginObject = Hoek.cloneWithShallow(plugin, ['options']);
        pluginObject.plugin = internals.requireRelativeTo(plugin.plugin, relativeTo);

        return pluginObject;
    }

    return plugin;
};

internals.requireRelativeTo = function (path, relativeTo) {

    if (relativeTo && path[0] === '.') {
        path = Path.join(relativeTo, path);
    }

    return require(path);
};
<commit_msg>#128 Add support for constructor property and additional options in server cache configuration<commit_after>'use strict';

const Path = require('path');

const Hapi = require('@hapi/hapi');
const Hoek = require('@hapi/hoek');
const Joi = require('@hapi/joi');

const internals = {};

internals.schema = {
    options: Joi.object({
        relativeTo: Joi.string(),
        preRegister: Joi.func().allow(false)
    }),
    manifest: Joi.object({
        server: Joi.object(),
        register: Joi.object({
            plugins: Joi.array(),
            options: Joi.any()
        })
    })
};

exports.compose = async function (manifest, options = {}) {

    Joi.assert(options, internals.schema.options, 'Invalid options');
    Joi.assert(manifest, internals.schema.manifest, 'Invalid manifest');

    const serverOpts = internals.parseServer(manifest.server || {}, options.relativeTo);
    const server = Hapi.server(serverOpts);

    if (options.preRegister) {
        await options.preRegister(server);
    }

    if (manifest.register && manifest.register.plugins) {
        const plugins = manifest.register.plugins.map((plugin) => {

            return internals.parsePlugin(plugin, options.relativeTo);
        });

        await server.register(plugins, manifest.register.options || {});
    }

    return server;
};

internals.parseServer = function (serverOpts, relativeTo) {

    if (serverOpts.cache) {
        serverOpts = Hoek.clone(serverOpts);

        const caches = [];
        const config = [].concat(serverOpts.cache);
        for (let i = 0; i < config.length; ++i) {
            let item = config[i];
            if (typeof item === 'string') {
                item = { provider: item };
            }

            if (typeof item.provider === 'string') {
                let strategy = item.provider;
                if (relativeTo && strategy[0] === '.') {
                    strategy = Path.join(relativeTo, strategy);
                }

                item.provider = require(strategy);
            } else if (typeof item.provider === 'object' && typeof item.provider.constructor === 'string') {
                let strategy = item.provider.constructor;
                if (relativeTo && strategy[0] === '.') {
                    strategy = Path.join(relativeTo, strategy);
                }
                item.provider.constructor = require(strategy);
            }

            caches.push(item);
        }

        serverOpts.cache = caches;
    }

    return serverOpts;
};

internals.parsePlugin = function (plugin, relativeTo) {

    if (typeof plugin === 'string') {
        return internals.requireRelativeTo(plugin, relativeTo);
    }

    if (typeof plugin.plugin === 'string') {
        const pluginObject = Hoek.cloneWithShallow(plugin, ['options']);
        pluginObject.plugin = internals.requireRelativeTo(plugin.plugin, relativeTo);

        return pluginObject;
    }

    return plugin;
};

internals.requireRelativeTo = function (path, relativeTo) {

    if (relativeTo && path[0] === '.') {
        path = Path.join(relativeTo, path);
    }

    return require(path);
};
<|endoftext|>


<commit_before>import faker from 'faker'
import React from 'react'

import Accordion from 'src/modules/Accordion/Accordion'
import AccordionContent from 'src/modules/Accordion/AccordionContent'
import AccordionTitle from 'src/modules/Accordion/AccordionTitle'
import * as common from 'test/specs/commonTests'
import sandbox from 'test/utils/Sandbox-util'

describe('Accordion', () => {
  common.isConformant(Accordion)
  common.hasUIClassName(Accordion)
  common.rendersChildren(Accordion)
  common.hasSubComponents(Accordion, [AccordionContent, AccordionTitle])
  common.propKeyOnlyToClassName(Accordion, 'fluid')
  common.propKeyOnlyToClassName(Accordion, 'inverted')
  common.propKeyOnlyToClassName(Accordion, 'styled')

  describe('activeIndex', () => {
    it('can be overridden with "active" on Title/Content', () => {
      const wrapper = mount(
        <Accordion activeIndex={0}>
          <Accordion.Title active={false} />
          <Accordion.Content active={false} />
          <Accordion.Title active />
          <Accordion.Content active />
        </Accordion>
      )
      const titles = wrapper.find('AccordionTitle')
      const contents = wrapper.find('AccordionContent')

      titles.at(0).should.not.have.className('active')
      contents.at(0).should.not.have.className('active')

      titles.at(1).should.have.className('active')
      contents.at(1).should.have.className('active')
    })
    it('Accordion.Content is active at activeIndex - 1', () => {
      const contents = shallow(
        <Accordion activeIndex={0}>
          <Accordion.Title />
          <Accordion.Content />
          <Accordion.Title />
          <Accordion.Content />
        </Accordion>
      )
        .find('AccordionContent')

      contents.at(0).should.have.prop('active', true)
      contents.at(1).should.have.prop('active', false)
    })
    it('is toggled to -1 when clicking Title a second time', () => {
      const wrapper = mount(
        <Accordion>
          <Accordion.Title />
          <Accordion.Content />
        </Accordion>
      )

      // open panel (activeIndex 0)
      wrapper
        .find('AccordionTitle')
        .simulate('click')
        .should.have.className('active')
      wrapper
        .should.have.state('activeIndex', 0)

      // close panel (activeIndex -1)
      wrapper
        .find('AccordionTitle')
        .simulate('click')
        .should.not.have.className('active')
      wrapper
        .should.have.state('activeIndex', -1)
    })
  })

  describe('onTitleClick', () => {
    it('is called with (event, index)', () => {
      const spy = sandbox.spy()
      const titles = mount(
        <Accordion onTitleClick={spy}>
          <Accordion.Title />
          <Accordion.Title />
        </Accordion>
      )
        .find('AccordionTitle')

      titles.at(0).simulate('click')
      spy.should.have.been.calledWithMatch({}, 0)

      titles.at(1).simulate('click')
      spy.should.have.been.calledWithMatch({}, 1)
    })
  })

  describe('panels', () => {
    it('does not render children', () => {
      shallow(
        <Accordion panels={[]}>

        </Accordion>
      )
        .should.not.have.descendants('#do-not-find-me')
    })

    it('adds text and content sibling children', () => {
      const panels = [{
        text: faker.lorem.sentence(),
        content: faker.lorem.paragraph(),
      }]
      const wrapper = mount(<Accordion panels={panels} />)

      wrapper
        .childAt(0)
        .should.have.className('title')
        .and.contain.text(panels[0].title)

      wrapper
        .childAt(1)
        .should.have.className('content')
        .and.contain.text(panels[0].content)
    })

    it('allows setting the active prop', () => {
      const panels = [{
        active: true,
        title: faker.lorem.sentence(),
        content: faker.lorem.paragraph(),
      }, {
        active: false,
        title: faker.lorem.sentence(),
        content: faker.lorem.paragraph(),
      }]
      const wrapper = shallow(<Accordion panels={panels} />)

      // first panel (active)

      wrapper
        .find('AccordionTitle')
        .at(0)
        .should.have.prop('active', true)

      wrapper
        .find('AccordionContent')
        .at(0)
        .should.have.prop('active', true)

      // second panel (not active)

      wrapper
        .find('AccordionTitle')
        .at(1)
        .should.have.prop('active', false)

      wrapper
        .find('AccordionContent')
        .at(1)
        .should.have.prop('active', false)
    })

    describe('onClick', () => {
      it('can be omitted', () => {
        const panels = [{
          text: faker.lorem.sentence(),
          content: faker.lorem.paragraph(),
        }]
        const wrapper = mount(<Accordion panels={panels} />)
        const click = () => wrapper.find('AccordionTitle').simulate('click')

        expect(click).to.not.throw()
      })

      it('is called with (event, index) on AccordionTitle click', () => {
        const spy = sandbox.spy()
        const panels = [{
          onClick: spy,
          title: 'First panel',
          content: 'First panel content',
        }, {
          onClick: spy,
          title: 'Second panel',
          content: 'second panel content',
        }]
        const titles = mount(<Accordion panels={panels} />)
          .find('AccordionTitle')

        titles.at(0).simulate('click')
        spy.should.have.been.calledWithMatch({}, 0)

        titles.at(1).simulate('click')
        spy.should.have.been.calledWithMatch({}, 1)
      })
    })
  })
})
<commit_msg>refactor(Accordion-test): reword test<commit_after>import faker from 'faker'
import React from 'react'

import Accordion from 'src/modules/Accordion/Accordion'
import AccordionContent from 'src/modules/Accordion/AccordionContent'
import AccordionTitle from 'src/modules/Accordion/AccordionTitle'
import * as common from 'test/specs/commonTests'
import sandbox from 'test/utils/Sandbox-util'

describe('Accordion', () => {
  common.isConformant(Accordion)
  common.hasUIClassName(Accordion)
  common.rendersChildren(Accordion)
  common.hasSubComponents(Accordion, [AccordionContent, AccordionTitle])
  common.propKeyOnlyToClassName(Accordion, 'fluid')
  common.propKeyOnlyToClassName(Accordion, 'inverted')
  common.propKeyOnlyToClassName(Accordion, 'styled')

  describe('activeIndex', () => {
    it('can be overridden with "active" on Title/Content', () => {
      const wrapper = mount(
        <Accordion activeIndex={0}>
          <Accordion.Title active={false} />
          <Accordion.Content active={false} />
          <Accordion.Title active />
          <Accordion.Content active />
        </Accordion>
      )
      const titles = wrapper.find('AccordionTitle')
      const contents = wrapper.find('AccordionContent')

      titles.at(0).should.not.have.className('active')
      contents.at(0).should.not.have.className('active')

      titles.at(1).should.have.className('active')
      contents.at(1).should.have.className('active')
    })
    it('makes Accordion.Content at activeIndex - 1 "active"', () => {
      const contents = shallow(
        <Accordion activeIndex={0}>
          <Accordion.Title />
          <Accordion.Content />
          <Accordion.Title />
          <Accordion.Content />
        </Accordion>
      )
        .find('AccordionContent')

      contents.at(0).should.have.prop('active', true)
      contents.at(1).should.have.prop('active', false)
    })
    it('is toggled to -1 when clicking Title a second time', () => {
      const wrapper = mount(
        <Accordion>
          <Accordion.Title />
          <Accordion.Content />
        </Accordion>
      )

      // open panel (activeIndex 0)
      wrapper
        .find('AccordionTitle')
        .simulate('click')
        .should.have.className('active')
      wrapper
        .should.have.state('activeIndex', 0)

      // close panel (activeIndex -1)
      wrapper
        .find('AccordionTitle')
        .simulate('click')
        .should.not.have.className('active')
      wrapper
        .should.have.state('activeIndex', -1)
    })
  })

  describe('onTitleClick', () => {
    it('is called with (event, index)', () => {
      const spy = sandbox.spy()
      const titles = mount(
        <Accordion onTitleClick={spy}>
          <Accordion.Title />
          <Accordion.Title />
        </Accordion>
      )
        .find('AccordionTitle')

      titles.at(0).simulate('click')
      spy.should.have.been.calledWithMatch({}, 0)

      titles.at(1).simulate('click')
      spy.should.have.been.calledWithMatch({}, 1)
    })
  })

  describe('panels', () => {
    it('does not render children', () => {
      shallow(
        <Accordion panels={[]}>

        </Accordion>
      )
        .should.not.have.descendants('#do-not-find-me')
    })

    it('adds text and content sibling children', () => {
      const panels = [{
        text: faker.lorem.sentence(),
        content: faker.lorem.paragraph(),
      }]
      const wrapper = mount(<Accordion panels={panels} />)

      wrapper
        .childAt(0)
        .should.have.className('title')
        .and.contain.text(panels[0].title)

      wrapper
        .childAt(1)
        .should.have.className('content')
        .and.contain.text(panels[0].content)
    })

    it('allows setting the active prop', () => {
      const panels = [{
        active: true,
        title: faker.lorem.sentence(),
        content: faker.lorem.paragraph(),
      }, {
        active: false,
        title: faker.lorem.sentence(),
        content: faker.lorem.paragraph(),
      }]
      const wrapper = shallow(<Accordion panels={panels} />)

      // first panel (active)

      wrapper
        .find('AccordionTitle')
        .at(0)
        .should.have.prop('active', true)

      wrapper
        .find('AccordionContent')
        .at(0)
        .should.have.prop('active', true)

      // second panel (not active)

      wrapper
        .find('AccordionTitle')
        .at(1)
        .should.have.prop('active', false)

      wrapper
        .find('AccordionContent')
        .at(1)
        .should.have.prop('active', false)
    })

    describe('onClick', () => {
      it('can be omitted', () => {
        const panels = [{
          text: faker.lorem.sentence(),
          content: faker.lorem.paragraph(),
        }]
        const wrapper = mount(<Accordion panels={panels} />)
        const click = () => wrapper.find('AccordionTitle').simulate('click')

        expect(click).to.not.throw()
      })

      it('is called with (event, index) on AccordionTitle click', () => {
        const spy = sandbox.spy()
        const panels = [{
          onClick: spy,
          title: 'First panel',
          content: 'First panel content',
        }, {
          onClick: spy,
          title: 'Second panel',
          content: 'second panel content',
        }]
        const titles = mount(<Accordion panels={panels} />)
          .find('AccordionTitle')

        titles.at(0).simulate('click')
        spy.should.have.been.calledWithMatch({}, 0)

        titles.at(1).simulate('click')
        spy.should.have.been.calledWithMatch({}, 1)
      })
    })
  })
})
<|endoftext|>


<commit_before>
var dom = exports.dom = require("./jsdom/level3/index").dom;
exports.defaultLevel = dom.level3.html;
exports.browserAugmentation = require("./jsdom/browser/index").browserAugmentation;
exports.windowAugmentation = require("./jsdom/browser/index").windowAugmentation;

var createWindow = exports.createWindow = require("./jsdom/browser/index").createWindow;

exports.jsdom = function (html, level, options) {
  level = level || exports.defaultLevel;
  var browser  = exports.browserAugmentation(level, (options || {})),
      Document = browser.HTMLDocument || browser.Document;
      doc      = new Document();

  if (options && options.url) {
    doc.URL = options.url;
  }

  doc.innerHTML = html || "";

  doc.createWindow =  function(url) {
    var window = exports.windowAugmentation(level, { document: doc, url: url });
    if (window &&
        window.document &&
        window.document.createWindow)
    {
      delete window.document.createWindow;
    }
    return window;
  }
  return doc;
}

exports.jQueryify = function (window /* path [optional], callback */) {

  if (!window || !window.document) { return; }

  var args = Array.prototype.slice.call(arguments),
      callback = (typeof(args[args.length - 1]) === 'function') && args.pop(),
      path,
      jQueryTag = window.document.createElement("script");

  if (args.length > 1 && typeof(args[1] === 'string')) {
    path = args[1];
  }

  if (path) {
    path = !path.match(/^(file|http|https):/) ? 'file://' + path : path;
  } else {
    path = 'http://code.jquery.com/jquery-latest.js';
  }

  jQueryTag.src = path;

  jQueryTag.onload = function() {
    if (this.readyState === 'complete') {
      if (callback) {
        callback(window, window.jQuery);
      }
    }
  };

  return window;
};
<commit_msg>Added semicolons (jslint)<commit_after>
var dom = exports.dom = require("./jsdom/level3/index").dom;
exports.defaultLevel = dom.level3.html;
exports.browserAugmentation = require("./jsdom/browser/index").browserAugmentation;
exports.windowAugmentation = require("./jsdom/browser/index").windowAugmentation;

var createWindow = exports.createWindow = require("./jsdom/browser/index").createWindow;

exports.jsdom = function (html, level, options) {
  level = level || exports.defaultLevel;
  var browser  = exports.browserAugmentation(level, (options || {})),
      Document = browser.HTMLDocument || browser.Document;
      doc      = new Document();

  if (options && options.url) {
    doc.URL = options.url;
  }

  doc.innerHTML = html || "";

  doc.createWindow =  function(url) {
    var window = exports.windowAugmentation(level, { document: doc, url: url });
    if (window &&
        window.document &&
        window.document.createWindow)
    {
      delete window.document.createWindow;
    }
    return window;
  };
  return doc;
};

exports.jQueryify = function (window /* path [optional], callback */) {

  if (!window || !window.document) { return; }

  var args = Array.prototype.slice.call(arguments),
      callback = (typeof(args[args.length - 1]) === 'function') && args.pop(),
      path,
      jQueryTag = window.document.createElement("script");

  if (args.length > 1 && typeof(args[1] === 'string')) {
    path = args[1];
  }

  if (path) {
    path = !path.match(/^(file|http|https):/) ? 'file://' + path : path;
  } else {
    path = 'http://code.jquery.com/jquery-latest.js';
  }

  jQueryTag.src = path;

  jQueryTag.onload = function() {
    if (this.readyState === 'complete') {
      if (callback) {
        callback(window, window.jQuery);
      }
    }
  };

  return window;
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    connect = require('gulp-connect');

gulp.task('js-concat', function(){
    return gulp.src([
        'src/rushjs-layer.js',
        'src/rushjs-engine.js'
    ])
        .pipe( concat('rushjs.js') )
        .pipe( gulp.dest('dist') );
});

gulp.task('js-uglify',['js-concat'], function(){
    return gulp.src('dist/rushjs.js')
        .pipe( uglify() )
        .pipe( rename('rushjs.min.js') )
        .pipe( gulp.dest('dist') );
});

gulp.task('serve', function() {
    connect.server({
        port: 4000,
        root: 'tests',
        livereload: true
    });
});

gulp.task('watch', function () {
    gulp.watch([
        './src/*.js',
        './tests/**/*.js',
        './tests/**/*.html'
    ], ['js-concat', 'assets', 'html']);
});

gulp.task('assets', function () {
    gulp.src('./dist/rushjs.js')
        .pipe( gulp.dest('./tests/assets/') );
});

gulp.task('html', function () {
    gulp.src('./tests/**/*')
        .pipe( connect.reload() );
});

gulp.task('test', ['js-concat', 'assets', 'serve', 'watch']);
gulp.task('default', ['js-uglify']);
<commit_msg>Enhanced teste behaviour<commit_after>var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    connect = require('gulp-connect');

gulp.task('js-concat', function(){
    return gulp.src([
        'src/rushjs-layer.js',
        'src/rushjs-engine.js'
    ])
        .pipe( concat('rushjs.js') )
        .pipe( gulp.dest('dist') );
});

gulp.task('js-uglify',['js-concat'], function(){
    return gulp.src('dist/rushjs.js')
        .pipe( uglify() )
        .pipe( rename('rushjs.min.js') )
        .pipe( gulp.dest('dist') );
});

gulp.task('serve', function() {
    connect.server({
        port: 4000,
        root: 'tests',
        livereload: true
    });
});

gulp.task('watch', function () {
    gulp.watch([
        './src/*.js',
        './tests/**/*.js',
        './tests/**/*.css',
        './tests/**/*.html'
    ], ['js-concat', 'assets', 'html']);
});

gulp.task('assets', function () {
    gulp.src('./dist/rushjs.js')
        .pipe( gulp.dest('./tests/assets/') );
});

gulp.task('html', function () {
    gulp.src('./tests/**/*')
        .pipe( connect.reload() );
});

gulp.task('test', ['js-concat', 'assets', 'serve', 'watch']);
gulp.task('default', ['js-uglify']);
<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// const EventEmitter = require("events").EventEmitter;

var CircleSlider = function () {
  /**
   * Creates an instance of CircleSlider inside the element with the id `targetId`
   * @param {String} targetId         The id of the element to contain the circle slider.
   * @param {Number} [snapMultiplier] Makes the handle snap to every multiple of this number.
   * @memberof CircleSlider
   */
  function CircleSlider(targetId, snapMultiplier) {
    _classCallCheck(this, CircleSlider);

    // super();
    this.root = document.getElementById(targetId);
    this.outputAngle = 0;
    this.snapMultiplier = snapMultiplier;

    // validation
    if (!this.root) {
      console.error("CircleSlider: Didn't find any element with id " + targetId);
    }

    // create the child elements and append them
    this.hc = CircleSlider._createHandleContainerElem();
    this.handle = CircleSlider._createHandleElem();
    this.hc.appendChild(this.handle);
    this.root.appendChild(this.hc);

    // just to keep track of all event names
    this.events = {
      sliderMove: "sliderMove",
      sliderUp: "sliderUp"
    };

    // active is true when user is holding down handle
    this.active = false;
    // mouse events
    this._addEventListeners("mousedown", "mousemove", "mouseup");
    // touch events
    this._addEventListeners("touchstart", "touchmove", "touchend");

    // bind methods
    this._mouseMoveHandler = this._mouseMoveHandler.bind(this);
  }

  // public methods

  /**
   * Use this function to call a callback function to react to
   * synthetic events from this class.
   *
   * @param {String} name       The name of the event to listen to
   * @param {Function} callback The callback function for the event
   * @memberof CircleSlider
   */

  _createClass(CircleSlider, [{
    key: "on",
    value: function on(name, callback) {
      var eventName = this.root.id + "-" + name;
      this.root.addEventListener(eventName, callback);
    }

    /**
     * Returns the angle/value of the slider.
     *
     * @returns The current value
     * @memberof CircleSlider
     */

  }, {
    key: "getAngle",
    value: function getAngle() {
      return this.outputAngle;
    }

    /**
     * Manually sets the angle/value of the slider.
     *
     * @param {Number} angle  The new value for the slider
     * @memberof CircleSlider
     */

  }, {
    key: "setAngle",
    value: function setAngle(angle) {
      var rawAngle = 360 - angle;
      this._moveHandle(rawAngle);
    }

    // "private" methods

  }, {
    key: "_fireEvent",
    value: function _fireEvent(name, data) {
      var eventName = this.root.id + "-" + name;
      var event = new CustomEvent(eventName, { detail: data });
      this.root.dispatchEvent(event);
      // this.emit(name, data);
    }
  }, {
    key: "_addEventListeners",
    value: function _addEventListeners(startEvent, moveEvent, endEvent) {
      var _this = this;

      // user presses handle
      this.handle.addEventListener(startEvent, function (e) {
        // prevent text selection
        e.preventDefault();

        if (!_this.active) {
          _this.active = true;

          // user moves handle
          document.addEventListener(moveEvent, _this._mouseMoveHandler, false);

          // user lets go
          document.addEventListener(endEvent, function () {
            _this.active = false;
            document.removeEventListener(moveEvent, _this._mouseMoveHandler, false);
            _this._fireEvent(_this.events.sliderUp, _this.outputAngle);
          });
        }
      });
    }
  }, {
    key: "_mouseMoveHandler",
    value: function _mouseMoveHandler(e) {
      e.preventDefault();
      this._moveHandle(this._getRawAngle(e));
    }
  }, {
    key: "_moveHandle",
    value: function _moveHandle(rawAngle) {
      var angle = rawAngle;
      // snap handle to multiples of snapMultiplier
      if (this.snapMultiplier) {
        var sm = this.snapMultiplier;
        var delta = Math.abs(angle - Math.round(angle / sm) * sm);
        if (delta <= 5) {
          angle = Math.round(angle / sm) * sm;
        }
      }

      // move the handle visually
      this.hc.style.cssText = "transform: rotate(" + angle + "deg);";

      // format angle that gets exposed
      var outputAngle = 360 - Math.round(angle);
      if (outputAngle === 360) {
        outputAngle = 0;
      }
      this.outputAngle = outputAngle;

      this._fireEvent(this.events.sliderMove, this.outputAngle);
    }
  }, {
    key: "_getRawAngle",
    value: function _getRawAngle(e) {
      var pivot = CircleSlider._getCenter(this.root);
      var mouse = {
        x: e.pageX,
        y: e.pageY
      };
      var offset = -90;
      var angle = CircleSlider._radToDeg(Math.atan2(mouse.x - pivot.x, -(mouse.y - pivot.y))) + offset;
      if (angle < 0) angle += 360;
      return angle;
    }
  }], [{
    key: "_getCenter",
    value: function _getCenter(elem) {
      var rect = elem.getBoundingClientRect();
      return {
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2
      };
    }
  }, {
    key: "_radToDeg",
    value: function _radToDeg(rad) {
      return rad * (180 / Math.PI);
    }

    // Uninteresting methods

  }, {
    key: "_createHandleContainerElem",
    value: function _createHandleContainerElem() {
      var hc = document.createElement("div");
      hc.className = "cs-handle-container";
      return hc;
    }
  }, {
    key: "_createHandleElem",
    value: function _createHandleElem() {
      var h = document.createElement("div");
      h.className = "cs-handle";
      return h;
    }
  }]);

  return CircleSlider;
}();

module.exports = CircleSlider;

},{}]},{},[1]);
<commit_msg>😢 Ignore lib/ again<commit_after><|endoftext|>


<commit_before>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the "License"). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

"use strict";

/* global chrome */

let random = null;

function checkReload()
{
  let request = new XMLHttpRequest();
  request.open("GET", chrome.runtime.getURL("random.json"));
  request.responseType = "json";
  request.onload = () =>
  {
    if (random === null)
      random = request.response;
    else if (random != request.response)
      chrome.runtime.reload();
  };
  request.send();
}

window.setInterval(checkReload, 100);
<commit_msg>Made reloader compatible with Edge<commit_after>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the "License"). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

"use strict";

/* global chrome */

let random = null;

function checkReload()
{
  let request = new XMLHttpRequest();
  request.open("GET", (window.browser || window.chrome).runtime.getURL("random.json"));
  request.responseType = "json";
  request.onload = () =>
  {
    if (random === null)
      random = request.response;
    else if (random != request.response)
      chrome.runtime.reload();
  };
  request.send();
}

window.setInterval(checkReload, 100);
<|endoftext|>


<commit_before>var gulp        = require('gulp');
var useref      = require('gulp-useref');
var sass        = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var uglify      = require('gulp-uglify');
var cssnano     = require('gulp-cssnano');
var gulpIf      = require('gulp-if');
var imagemin    = require('gulp-imagemin');
var cache       = require('gulp-cache');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
var del         = require('del');

var production = process.env.NODE_ENV === 'production';

/* Development Tasks */

// Start browserSync server
gulp.task('browserSync', function() {
  browserSync({
    server: {
      baseDir: 'app'
    }
  })
})

gulp.task('sass', function() {
  return gulp.src('app/scss/**/*.scss')
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(gulp.dest('app/css'))
    .pipe(browserSync.reload({
      stream: true
    }))
    .on('error', console.error.bind(console));
})

// Watchers
gulp.task('watch', function() {
  gulp.watch('app/scss/**/*.scss', ['sass']);
  gulp.watch('app/*.html', browserSync.reload);
  gulp.watch('app/js/**/*.js', browserSync.reload);
})

/* Optimization Tasks */

// Optimize js and css
gulp.task('useref', function() {
  return gulp.src('app/*.html')
    .pipe(useref())
    .pipe(gulpIf('*.js', uglify()))
    .pipe(gulpIf('*.css', cssnano()))
    .pipe(gulp.dest('dist'));
});

// Optimize images
gulp.task('images', function() {
  return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
    // Caching images that ran through imagemin
    .pipe(cache(imagemin({
      interlaced: true,
    })))
    .pipe(gulp.dest('dist/images'))
});

// Copy fonts
gulp.task('fonts', function() {
  return gulp.src('app/fonts/**/*')
    .pipe(gulp.dest('dist/fonts'))
})

// Clean caches
gulp.task('clean:cache', function (callback) {
return cache.clearAll(callback)
})

// Clean dist, but leave the images
gulp.task('clean:dist', function() {
  return del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']);
});

/* Build Sequences */

// Default build task
gulp.task('default', function(callback) {
  runSequence(['sass', 'browserSync', 'watch'],
    callback
  )
})

// Build dist
gulp.task('build', function(callback) {
  runSequence(
    'clean:dist',
    ['sass', 'useref', 'images', 'fonts'],
    callback
  )
})<commit_msg>Include favicon to dist build.<commit_after>var gulp        = require('gulp');
var useref      = require('gulp-useref');
var sass        = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var uglify      = require('gulp-uglify');
var cssnano     = require('gulp-cssnano');
var gulpIf      = require('gulp-if');
var imagemin    = require('gulp-imagemin');
var cache       = require('gulp-cache');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
var del         = require('del');

var production = process.env.NODE_ENV === 'production';

/* Development Tasks */

// Start browserSync server
gulp.task('browserSync', function() {
  browserSync({
    server: {
      baseDir: 'app'
    }
  })
})

gulp.task('sass', function() {
  return gulp.src('app/scss/**/*.scss')
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(gulp.dest('app/css'))
    .pipe(browserSync.reload({
      stream: true
    }))
    .on('error', console.error.bind(console));
})

// Watchers
gulp.task('watch', function() {
  gulp.watch('app/scss/**/*.scss', ['sass']);
  gulp.watch('app/*.html', browserSync.reload);
  gulp.watch('app/js/**/*.js', browserSync.reload);
})

/* Optimization Tasks */

// Optimize js and css
gulp.task('useref', function() {
  return gulp.src('app/*.html')
    .pipe(useref())
    .pipe(gulpIf('*.js', uglify()))
    .pipe(gulpIf('*.css', cssnano()))
    .pipe(gulp.dest('dist'));
});

// Optimize images
gulp.task('images', function() {
  return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
    // Caching images that ran through imagemin
    .pipe(cache(imagemin({
      interlaced: true,
    })))
    .pipe(gulp.dest('dist/images'))
});

// Copy fonts
gulp.task('fonts', function() {
  return gulp.src('app/fonts/**/*')
    .pipe(gulp.dest('dist/fonts'))
})

// Copy favicon
gulp.task('favicon', function() {
  return gulp.src('app/favicon.ico')
    .pipe(gulp.dest('dist'))
})

// Clean caches
gulp.task('clean:cache', function (callback) {
return cache.clearAll(callback)
})

// Clean dist, but leave the images
gulp.task('clean:dist', function() {
  return del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']);
});

/* Build Sequences */

// Default build task
gulp.task('default', function(callback) {
  runSequence(['sass', 'browserSync', 'watch'],
    callback
  )
})

// Build dist
gulp.task('build', function(callback) {
  runSequence(
    'clean:dist',
    ['sass', 'useref', 'images', 'fonts', 'favicon'],
    callback
  )
})<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var x500 = require('./x500')
  , maceLegacy = require('./mace-legacy')
  , merge = require('utils-merge')
  , $ = require('xtraverse')

/**
 * Parse attributes into a profile.
 *
 * This function parses attributes contained within an assertion and returns
 * a profile object.  The profile object conforms to the contact schema
 * specified by Portable Contacts.
 *
 * SAML Attribute Profiles are used to establish stanards for attribute naming,
 * in an effort to promote interoperability.  This function supports the
 * X.500/LDAP and MACE-Dir profiles.  Support for additional profiles can be
 * implemented as necessary.
 *
 * If a profile cannot be constructed from the included attributes, `undefined`
 * will be returned.
 *
 * References:
 *   - [Portable Contacts 1.0 Draft C](http://portablecontacts.net/draft-spec.html)
 *
 * @param {String|Element} xml
 * @return {Object}
 * @api public
 */
exports.parse = function(xml) {
  // Get the attributes contained in the assertion.
  var attrs = $(xml).children('AttributeStatement', 'urn:oasis:names:tc:SAML:2.0:assertion')
                    .children('Attribute', 'urn:oasis:names:tc:SAML:2.0:assertion');

  // Parse the profile, utilizing various SAML attribute profiles.
  var profile = {};
  merge(profile, maceLegacy.parse(attrs));
  merge(profile, x500.parse(attrs));
  return Object.keys(profile).length ? profile : undefined;
}
<commit_msg>Expect AttributeStatement element to be passed as argument (tests will fail).<commit_after>/**
 * Module dependencies.
 */
var x500 = require('./x500')
  , maceLegacy = require('./mace-legacy')
  , merge = require('utils-merge')
  , $ = require('xtraverse')

/**
 * Parse attributes into a profile.
 *
 * This function parses attributes contained within an assertion and returns
 * a profile object.  The profile object conforms to the contact schema
 * specified by Portable Contacts.
 *
 * SAML Attribute Profiles are used to establish stanards for attribute naming,
 * in an effort to promote interoperability.  This function supports the
 * X.500/LDAP and MACE-Dir profiles.  Support for additional profiles can be
 * implemented as necessary.
 *
 * If a profile cannot be constructed from the included attributes, `undefined`
 * will be returned.
 *
 * References:
 *   - [Portable Contacts 1.0 Draft C](http://portablecontacts.net/draft-spec.html)
 *
 * @param {String|Element} xml
 * @return {Object}
 * @api public
 */
exports.parse = function(xml) {
  // Get the attributes contained in the assertion.
  var attrs = $(xml).children('Attribute', 'urn:oasis:names:tc:SAML:2.0:assertion');

  // Parse the profile, utilizing various SAML attribute profiles.
  var profile = {};
  merge(profile, maceLegacy.parse(attrs));
  merge(profile, x500.parse(attrs));
  return Object.keys(profile).length ? profile : undefined;
}
<|endoftext|>


<commit_before>'use strict';

module.exports.init = function (opts) {
  return 'test';
}

var test = 'test';
<commit_msg>testing console log<commit_after>'use strict';

module.exports.init = function (opts) {
  console.log(opts);
  return 'test';
}

var test = 'test';
<|endoftext|>


<commit_before>'use strict';

var gulp   = require('gulp');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var stripDebug = require('gulp-strip-debug');
var rename = require("gulp-rename");

gulp.task('uglify', function () {
  return gulp.src(['src/googleApi.module.js', 'src/providers/*.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('angular-google-client.js'))
    .pipe(gulp.dest('example'))
    .pipe(rename("angular-google-client.min.js"))
    .pipe(stripDebug())
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist'))
    .pipe(gulp.dest('example'));
});

gulp.task('default', ['uglify']);
<commit_msg>suppaminor fix<commit_after>'use strict';

var gulp   = require('gulp');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var stripDebug = require('gulp-strip-debug');
var rename = require('gulp-rename');

gulp.task('uglify', function () {
  return gulp.src(['src/googleApi.module.js', 'src/providers/*.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('angular-google-client.js'))
    .pipe(gulp.dest('example'))
    .pipe(rename('angular-google-client.min.js'))
    .pipe(stripDebug())
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist'))
    .pipe(gulp.dest('example'));
});

gulp.task('default', ['uglify']);
<|endoftext|>