<commit_before>/* REQUIRE NODE 6+ TO EVEN START THE BOT */
if (parseFloat(process.versions.node) < 6) {
	throw new Error('Incompatible node version. Please use Node 6 or higher.');
}

/* REQUIRED DEPENDENCIES */
var reload = require('require-reload')(require);
var fs = require('fs');
var Eris = require('eris');

/* REQUIRED FILES */
var config = require('./config.json');
var validateConfig = require('./utils/validateConfig.js');
var CommandManager = require('./utils/CommandManager.js');
var utils = require('./utils/utils.js');
var games = require('./special/games.json');

/* LOCAL VARIABLES */
var logger;
var CommandManagers = [];
var events = {};

commandsProcessed = 0;

validateConfig(config).catch(() => process.exit(0));
logger = new (reload('./utils/Logger.js'))(config.logTimestamp);

var bot = new Eris(config.token, {
	autoReconnect: true,
	disableEveryone: true,
	getAllUsers: true,
	messageLimit: 10,
	sequencerWait: 100,
	moreMentions: true,
	disableEvents: config.disableEvents,
	maxShards: config.shardCount,
	gatewayVersion: 6,
	cleanContent: true
});

function loadCommandSets() {
	return new Promise(resolve => {
		CommandManagers = [];
		for (let prefix in config.commandSets) {
			let color = config.commandSets[prefix].color;
			if (color && !logger.isValidColor(color)) {
				logger.warn(`Log color for ${prefix} invalid`);
				color = undefined;
			}
			CommandManagers.push(new CommandManager(config, prefix, config.commandSets[prefix].dir, color));
		}
		resolve();
	});
}

function initCommandManagers(index = 0) {
	return new Promise((resolve, reject) => {
		CommandManagers[index].initialize(bot, config)
			.then(() => {
				logger.debug(`Loaded CommandManager ${index}`, 'INIT');
				index++;
				if (CommandManagers.length > index) {
					initCommandManagers(index)
						.then(resolve)
						.catch(reject);
				} else {
					resolve();
				}
			}).catch(reject);
	});
}

function loadEvents() {
	return new Promise((resolve, reject) => {
		fs.readdir(__dirname + '/events/', (err, files) => {
			if (err) reject(`Error reading events directory: ${err}`);
			else if (!files) reject('No files in directory events/');
			else {
				for (let name of files) {
					if (name.endsWith('.js')) {
						name = name.replace(/\.js$/, '');
						try {
							events[name] = reload(`./events/${name}.js`);
							initEvent(name);
						} catch (e) {
							logger.error(`${e}\n${e.stack}`, 'Error loading ' + name.replace(/\.js$/, ''));
						}
					}
				}
				resolve();
			}
		});
	});
}

function initEvent(name) {
	if (name === 'messageCreate') {
		bot.on('messageCreate', msg => {
			events.messageCreate.handler(bot, msg, CommandManagers, config);
		});
	} else if (name === 'ready') {
		bot.on('ready', () => {
			events.ready(bot, config, games, utils);
		});
	} else {
		bot.on(name, function() {
			events[name](bot, config, ...arguments);
		});
	}
}

function login() {
	logger.logBold(`Logging in...`, 'green');
	bot.connect().catch(error => {
		logger.error(error, 'LOGIN ERROR');
	});
}

/* INIT EVERYTHING */
loadCommandSets()
	.then(initCommandManagers)
	.then(loadEvents)
	.then(login)
	.catch(error => {
		logger.error(error, 'ERROR IN INIT');
	});

setInterval(() => { // Update the bot's status for each shard every 10 minutes
	if (games.length !== 0 && bot.uptime !== 0 && config.cycleGames === true) {
		bot.shards.forEach(shard => {
			let name = games[~~(Math.random() * games.length)];
			shard.editStatus(null, {name});
		});
	}
}, 600000);

/* IF THE PROCESS EXPERIENCES SIGINT, DISCONNECT EVERYTHING AND NEVER TRY TO RECONNECT */
process.on('SIGINT', () => {
	bot.disconnect({reconnect: false});
	setTimeout(() => {
		process.exit(0);
	}, 5000);
});<commit_msg>added more events<commit_after>/* REQUIRE NODE 6+ TO EVEN START THE BOT */
if (parseFloat(process.versions.node) < 6) {
	throw new Error('Incompatible node version. Please use Node 6 or higher.');
}

/* REQUIRED DEPENDENCIES */
var reload = require('require-reload')(require);
var fs = require('fs');
var Eris = require('eris');

/* REQUIRED FILES */
var config = require('./config.json');
var validateConfig = require('./utils/validateConfig.js');
var CommandManager = require('./utils/CommandManager.js');
var utils = require('./utils/utils.js');
var games = require('./special/games.json');

/* LOCAL VARIABLES */
var logger;
var CommandManagers = [];
var events = {};

commandsProcessed = 0;

validateConfig(config).catch(() => process.exit(0));
logger = new (reload('./utils/Logger.js'))(config.logTimestamp);

var bot = new Eris(config.token, {
	autoReconnect: true,
	disableEveryone: true,
	getAllUsers: true,
	messageLimit: 10,
	sequencerWait: 100,
	moreMentions: true,
	disableEvents: config.disableEvents,
	maxShards: config.shardCount,
	gatewayVersion: 6,
	cleanContent: true
});

function loadCommandSets() {
	return new Promise(resolve => {
		CommandManagers = [];
		for (let prefix in config.commandSets) {
			let color = config.commandSets[prefix].color;
			if (color && !logger.isValidColor(color)) {
				logger.warn(`Log color for ${prefix} invalid`);
				color = undefined;
			}
			CommandManagers.push(new CommandManager(config, prefix, config.commandSets[prefix].dir, color));
		}
		resolve();
	});
}

function initCommandManagers(index = 0) {
	return new Promise((resolve, reject) => {
		CommandManagers[index].initialize(bot, config)
			.then(() => {
				logger.debug(`Loaded CommandManager ${index}`, 'INIT');
				index++;
				if (CommandManagers.length > index) {
					initCommandManagers(index)
						.then(resolve)
						.catch(reject);
				} else {
					resolve();
				}
			}).catch(reject);
	});
}

function loadEvents() {
	return new Promise((resolve, reject) => {
		fs.readdir(__dirname + '/events/', (err, files) => {
			if (err) reject(`Error reading events directory: ${err}`);
			else if (!files) reject('No files in directory events/');
			else {
				for (let name of files) {
					if (name.endsWith('.js')) {
						name = name.replace(/\.js$/, '');
						try {
							events[name] = reload(`./events/${name}.js`);
							initEvent(name);
						} catch (e) {
							logger.error(`${e}\n${e.stack}`, 'Error loading ' + name.replace(/\.js$/, ''));
						}
					}
				}
				resolve();
			}
		});
	});
}

function initEvent(name) {
	if (name === 'messageCreate') {
		bot.on('messageCreate', msg => {
			events.messageCreate.handler(bot, msg, CommandManagers, config);
		});
	} else if (name === 'ready') {
		bot.on('ready', () => {
			events.ready(bot, config, games, utils);
		});
	} else {
		bot.on(name, function() {
			events[name](bot, config, ...arguments);
		});
	}
}

function miscEvents() {
	return new Promise(resolve => {
		if (bot.listeners('error').length === 0) {
			bot.on('error', (e, id) => {
				logger.error(`${e}\n${e.stack}`, `SHARD ${id} ERROR`);
			});
		}
		if (bot.listeners('shardReady').length === 0) {
			bot.on('shardReady', id => {
				logger.logBold(` SHARD ${id} CONNECTED`, 'green');
			});
		}
		if (bot.listeners('disconnected').length === 0) {
			bot.on('disconnected', () => {
				logger.logBold(' DISCONNECTED FROM DISCORD', 'red');
			});
		}
		if (bot.listeners('shardDisconnect').length === 0) {
			bot.on('shardDisconnect', (e, id) => {
				logger.error(e, `SHARD ${id} DISCONNECT`);
			});
		}
		if (bot.listeners('shardResume').length === 0) {
			bot.on('shardResume', id => {
				logger.logBold(` SHARD ${id} RESUMED`, 'green');
			});
		}
		if (bot.listeners('guildCreate').length === 0) {
			bot.on('guildCreate', guild => {
				logger.debug(guild.name, 'GUILD CREATE');
			});
		}
		if (bot.listeners('guildDelete').length === 0) {
			bot.on('guildDelete', (guild, unavailable) => {
				if (unavailable === false) {
					logger.debug(guild.name, 'GUILD REMOVE');
				}
			});
		}
		return resolve();
	});
}

function login() {
	logger.logBold(`Logging in...`, 'green');
	bot.connect().catch(error => {
		logger.error(error, 'LOGIN ERROR');
	});
}

/* INIT EVERYTHING */
loadCommandSets()
	.then(initCommandManagers)
	.then(loadEvents)
	.then(miscEvents)
	.then(login)
	.catch(error => {
		logger.error(error, 'ERROR IN INIT');
	});

setInterval(() => { // Update the bot's status for each shard every 10 minutes
	if (games.length !== 0 && bot.uptime !== 0 && config.cycleGames === true) {
		bot.shards.forEach(shard => {
			let name = games[~~(Math.random() * games.length)];
			shard.editStatus(null, {name});
		});
	}
}, 600000);

/* IF THE PROCESS EXPERIENCES SIGINT, DISCONNECT EVERYTHING AND NEVER TRY TO RECONNECT */
process.on('SIGINT', () => {
	bot.disconnect({reconnect: false});
	setTimeout(() => {
		process.exit(0);
	}, 5000);
});<|endoftext|>


<commit_before>"use strict";

var WSS = require('ws').Server;
var Stream = require('stream');
var sockets = {};

exports.server = WSS;

exports.reset = function () {

    // close all websockets
    for (var socket in sockets) {
        sockets[socket].close();
    }

    // remove socket refs
    sockets = {};
};

exports.mux = mux;
function mux (instance, options) {

    options.id = options.id || UID(5);
    var output = Stream.PassThrough({objectMode: true});
    var stream = Stream.Transform({
        objectMode: true,
        transform: function (chunk, enc, next) {

            // get socket
            if (!stream.socket) {
                stream.socket = getSocket(instance, options.host);

                // cache mux stream
                stream.socket._streams[options.id] = output;
            }

            // send message to socket
            sendFrame(stream.socket, options, 0, chunk);

            next();
        }
    });

    // TODO listen to errors and send an error frame

    stream.socket = options.socket;

    // push response to readable
    output.on('frame', function (frame) {

        // remove stream ref if stream end
        if (frame.type > 0) {
            delete stream.socket._streams[frame.id];
        }

        // handle message types
        switch (frame.type) {
            // write data
            case 0:
                output.write(frame.chunk);
                break;
            // end event
            case 1:
                ouput.end(frame.chunk);
                break;
            // emit error
            case 2:
                output.emit('error', frame.chunk);
                output.end();
                break;
            // invalid
            default:
                var err = new Error('Websocket.demux: Invalid message type "' + type + '"');
                socket.send(createFrame({to: options.to}, err.stack));
        }
    });

    stream.on('error', function (err) {
        sendFrame(stream.socket, options, 2, err.message);
    });

    stream.on('finish', function () {
        if (stream.socket) {
            sendFrame(stream.socket, options, 1);
        }
    });

    return {i: stream, o: output};
}

exports.demux = demux;
function demux (instance, session) {

    return function (frame) {

        var socket = frame.target;
        frame = parseFrame(frame.data);
        frame.socket = socket;
        frame.session = session;

        // send error back
        if (frame.err) {
            socket.send(createFrame({to: instance._name}, frame.err.stack));
        }

        // emit or get stream
        socket._streams = socket._streams || {};
        var stream = socket._streams[frame.id];
        if (!stream) {
            var muxer = mux(instance, frame);
            stream = instance.flow(frame.emit, frame);
            stream.o.on('error', muxer.i.emit.bind(muxer.i, 'error'));
            stream.o.pipe(muxer.i);
            muxer.o.pipe(stream.i);
            stream.i.write(frame.chunk);
            return;
        }

        stream.emit('frame', frame);
    };
}

function getSocket (instance, host) {

    // check client host
    host = host || (window ? window.location.host : undefined);
    if (!host) {
        return new Error('Websocket.getSocket: No host.');
    }

    // get socket
    var socket = sockets[host];
    if (!socket) {
        socket = new WebSocket('wss://' + host);
        sockets[host] = socket;
        socket.onopen = function () {
            if (socket._frameBuf.length) {
                socket._frameBuf.forEach(socket.send.bind(socket));
                socket._frameBuf = [];
            }
        };
        socket.onclose = socketEnd;
        socket.onend = socketEnd;
        socket.onerror = function (err) {
            for (var stream in socket._streams) {
                socket._streams[stream].emit('error', err);
            }
        };
        socket.onmessage = demux(instance, {client: true});
        socket._streams = {};
    }

    socket._frameBuf = socket._frameBuf || [];
    return socket;
}

function sendFrame (socket, frame, type, data) {
    frame.type = type;
    frame = createFrame(frame, data);

    if (socket.readyState !== 1) {
        socket._frameBuf.push(frame);
    } else {
        socket.send(frame);
    }
}

function parseFrame (chunk) {

    try {
        chunk = JSON.parse(chunk.toString());
    } catch (err) {
        return {err: err};
    }

    var instance = chunk[0];
    var eventNme = chunk[1];
    var streamId = chunk[2];
    var type = chunk[3];
    var data = chunk[4];

    if (
        chunk.length < 4 ||
        typeof instance !== 'string' || !instance ||
        typeof eventNme !== 'string' || !eventNme ||
        typeof streamId !== 'string' || !streamId ||
        typeof type !== 'number' || type < 0 || type > 2
    ) {
        chunk = {err: new Error('Socket.mux: Invalid frame.')};
    }

    return {
        to: instance,
        emit: eventNme,
        id: streamId,
        type: type,
        chunk: data
    };
}

function createFrame (config, data) {

    config = config || {
        to: '@',
        emit: 'error',
        id: 'err',
        type: '2'
    };

    var frame = [
        config.to,
        config.emit,
        config.id,
        config.type,
    ];

    if (data !== undefined) {
        frame.push(data);
    }

    try {
        frame = JSON.stringify(frame);
    } catch (err) {
        frame = JSON.stringfy(['@', 'error', 'err', 2, err.stack]);
    }

    return frame;
}

function socketEnd () {
    var socket = this;
    for (var stream in socket._streams) {
        socket._streams[stream].end();
    }
    socket._streams = {};
}

function UID (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};
<commit_msg>ws module can not be bundled for a client<commit_after>"use strict";

var Stream = require('stream');
var sockets = {};

exports.reset = function () {

    // close all websockets
    for (var socket in sockets) {
        sockets[socket].close();
    }

    // remove socket refs
    sockets = {};
};

exports.mux = mux;
function mux (instance, options) {

    options.id = options.id || UID(5);
    var output = Stream.PassThrough({objectMode: true});
    var stream = Stream.Transform({
        objectMode: true,
        transform: function (chunk, enc, next) {

            // get socket
            if (!stream.socket) {
                stream.socket = getSocket(instance, options.host);

                // cache mux stream
                stream.socket._streams[options.id] = output;
            }

            // send message to socket
            sendFrame(stream.socket, options, 0, chunk);

            next();
        }
    });

    // TODO listen to errors and send an error frame

    stream.socket = options.socket;

    // push response to readable
    output.on('frame', function (frame) {

        // remove stream ref if stream end
        if (frame.type > 0) {
            delete stream.socket._streams[frame.id];
        }

        // handle message types
        switch (frame.type) {
            // write data
            case 0:
                output.write(frame.chunk);
                break;
            // end event
            case 1:
                ouput.end(frame.chunk);
                break;
            // emit error
            case 2:
                output.emit('error', frame.chunk);
                output.end();
                break;
            // invalid
            default:
                var err = new Error('Websocket.demux: Invalid message type "' + type + '"');
                socket.send(createFrame({to: options.to}, err.stack));
        }
    });

    stream.on('error', function (err) {
        sendFrame(stream.socket, options, 2, err.message);
    });

    stream.on('finish', function () {
        if (stream.socket) {
            sendFrame(stream.socket, options, 1);
        }
    });

    return {i: stream, o: output};
}

exports.demux = demux;
function demux (instance, session) {

    return function (frame) {

        var socket = frame.target;
        frame = parseFrame(frame.data);
        frame.socket = socket;
        frame.session = session;

        // send error back
        if (frame.err) {
            socket.send(createFrame({to: instance._name}, frame.err.stack));
        }

        // emit or get stream
        socket._streams = socket._streams || {};
        var stream = socket._streams[frame.id];
        if (!stream) {
            var muxer = mux(instance, frame);
            stream = instance.flow(frame.emit, frame);
            stream.o.on('error', muxer.i.emit.bind(muxer.i, 'error'));
            stream.o.pipe(muxer.i);
            muxer.o.pipe(stream.i);
            stream.i.write(frame.chunk);
            return;
        }

        stream.emit('frame', frame);
    };
}

function getSocket (instance, host) {

    // check client host
    host = host || (window ? window.location.host : undefined);
    if (!host) {
        return new Error('Websocket.getSocket: No host.');
    }

    // get socket
    var socket = sockets[host];
    if (!socket) {
        socket = new WebSocket('wss://' + host);
        sockets[host] = socket;
        socket.onopen = function () {
            if (socket._frameBuf.length) {
                socket._frameBuf.forEach(socket.send.bind(socket));
                socket._frameBuf = [];
            }
        };
        socket.onclose = socketEnd;
        socket.onend = socketEnd;
        socket.onerror = function (err) {
            for (var stream in socket._streams) {
                socket._streams[stream].emit('error', err);
            }
        };
        socket.onmessage = demux(instance, {client: true});
        socket._streams = {};
    }

    socket._frameBuf = socket._frameBuf || [];
    return socket;
}

function sendFrame (socket, frame, type, data) {
    frame.type = type;
    frame = createFrame(frame, data);

    if (socket.readyState !== 1) {
        socket._frameBuf.push(frame);
    } else {
        socket.send(frame);
    }
}

function parseFrame (chunk) {

    try {
        chunk = JSON.parse(chunk.toString());
    } catch (err) {
        return {err: err};
    }

    var instance = chunk[0];
    var eventNme = chunk[1];
    var streamId = chunk[2];
    var type = chunk[3];
    var data = chunk[4];

    if (
        chunk.length < 4 ||
        typeof instance !== 'string' || !instance ||
        typeof eventNme !== 'string' || !eventNme ||
        typeof streamId !== 'string' || !streamId ||
        typeof type !== 'number' || type < 0 || type > 2
    ) {
        chunk = {err: new Error('Socket.mux: Invalid frame.')};
    }

    return {
        to: instance,
        emit: eventNme,
        id: streamId,
        type: type,
        chunk: data
    };
}

function createFrame (config, data) {

    config = config || {
        to: '@',
        emit: 'error',
        id: 'err',
        type: '2'
    };

    var frame = [
        config.to,
        config.emit,
        config.id,
        config.type,
    ];

    if (data !== undefined) {
        frame.push(data);
    }

    try {
        frame = JSON.stringify(frame);
    } catch (err) {
        frame = JSON.stringfy(['@', 'error', 'err', 2, err.stack]);
    }

    return frame;
}

function socketEnd () {
    var socket = this;
    for (var stream in socket._streams) {
        socket._streams[stream].end();
    }
    socket._streams = {};
}

function UID (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs'),
    path = require('path'),
    parse = require('url').parse,
    http = require('http'),
    exec = require('child_process').exec,
    rootpath = path.resolve(process.argv[2] || '.'),
    port = parseInt(process.argv[3]) || 4567,
    tmpl = fs.readFileSync(require.resolve('./template.html'), 'utf8'),
    hookpath = require.resolve('./hooks/post-receive'),
    hookVersion = parseHookVersion(hookpath),
    guiVersion = require('./package.json').version,
    ansiRe = new RegExp('\033\\[(\\d+)m', 'g'),
    statusChars = ['✓', '✗', '—'];

function esc(str) {
  return str.replace(/'/g, '"');
}

function fdate(d) {
  return d.toDateString() + ' ' + d.toLocaleTimeString();
}

function colorize(text) {
  var count = 0;
  return text.replace(ansiRe, function(_, code) {
    var res;
    if (code === '0') {
      res = new Array(count+1).join('');
      count = 0;
    } else {
      res = '';
      count++;
    }
    return res;
  })+new Array(count+1).join('');
};

function logExec(cmd, callback) {
  console.log('Execting shell command:', cmd);
  exec(cmd, function (err, stdout, stderr) {
    console.log(err, stderr);
    if (callback) callback(err, stdout, stderr);
  });
}
function copyHook(to, runner, match, callback) {
  var eto = esc(to), er = esc(runner), em = esc(match);
  logExec("cp '"+esc(hookpath)+"' '"+eto+"/hooks/post-receive' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.runner '"+er+"' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.match '"+em+"'",
  callback);
}

function invokeHook(to, before, after, ref, callback) {
  var eref = esc(ref);
  logExec("cd '"+esc(to)+"' && git fetch origin '"+eref+":"+eref+"' && "+
    "echo '"+esc(before+" "+after+" "+ref)+"' | hooks/post-receive",
  callback);
}

function parseHookVersion(hookpath) {
  var m;
  if (!fs.existsSync(hookpath)) return;
  m = fs.readFileSync(hookpath, 'utf8').match(/TINCIV=([\d.]+)/);
  return m !== null ? m[1] : false;
}

function template(model) {
  var html = tmpl, i;
  for (i in model) html = html.split('{{'+i+'}}').join(model[i]);
  return html;
}

function logToHtml(log) {
  return '

' +
    statusChars[log.status] + ' ' + log.ref +
    ' '+ fdate(log.ctime) + ' ' + log.rev +
    '
' + '
' +
    colorize(log.log.replace(/\r?\n/g, '
')) + '

';
}

function parseLog(log) {
  var refm;
  if (!log.log) {
    log.log = fs.readFileSync(log.path, 'utf8').trim();
    log.ref = (refm = /# ref refs\/(?:heads|tags)\/(.*)/.exec(log.log), refm ? refm[1] : '');
    log.exitcode = log.log.slice(log.log.lastIndexOf('\n')+1).split(' ').slice(-1)[0];
    log.status = /^\d+$/.test(log.exitcode) ? (log.exitcode==='0' ? 0 : 1) : 2;
  }
  return log;
}

function logs(tincipath) {
  var res = {logs:[], dict:{}};
  if (fs.existsSync(tincipath)) {
    res.logs = fs.readdirSync(tincipath).filter(function(file){
      return file.slice(-4) === '.log';
    }).map(function(file) {
      var filepath = path.join(tincipath, file),
          rev = path.basename(file, '.log');
      return res.dict[rev] = {
        path: filepath,
        rev: rev,
        ctime: fs.statSync(filepath).ctime
      };
    }).sort(function(a, b){ return a.ctime - b.ctime; });
  }
  return res;
}

http.createServer(function(req, res) {
  var url = parse(req.url, true),
      pathname = path.resolve(rootpath, './'+url.pathname),
      format = url.query.format || 'html',
      model = {}, data = '?', logs_, ls, dict,
      page, reponame, tincipath, hookv;
  if (pathname.indexOf(rootpath) === 0 && fs.existsSync(pathname)) {
    reponame = path.basename(pathname, '.git');
    if (fs.existsSync(path.join(pathname, 'hooks'))) {
      if ('invoke' in url.query) {
        req.on('data', function(chunk) { data += chunk; })
        .on('end', function() {
          var gitinfo;
          try {
            gitinfo = JSON.parse(parse(data, true).query.payload);
            invokeHook(pathname, gitinfo.before, gitinfo.after, gitinfo.ref);
            res.writeHead(200);
          } catch (ex) {
            res.writeHead(500);
            console.log('Error on invoke call: '+ex.message);
          }
          res.end();
        });
        return;
      }
      hookv = parseHookVersion(path.resolve(pathname, 'hooks', 'post-receive'));
      model = {
          title: reponame,
          status: 2,
          logs: [],
          guiVersion: guiVersion,
          hookVersion: hookVersion,
          installedVersion: hookv
      };
      if ('update' in url.query) {
        if (url.query.runner) {
          copyHook(
            pathname,
            url.query.runner,
            url.query.match||'master',
            function () {
              res.writeHead(302, { 'Location': url.pathname });
              res.end();
            }
          );
          return;
        } else {
          if (hookv != null) model.overwrite = 'show';
          model.config = 'show';
        }
      } else if (hookv) {
        tincipath = path.join(pathname, '.tinci');
        logs_ = logs(tincipath);
        ls = logs_.logs;
        dict = logs_.dict;
        if (ls.length) model.status = parseLog(ls[ls.length-1]).status;
        model.logs = (function(){
          if (url.query.log) {
            return [dict[url.query.log]];
          } else {
            page = (url.query.page || Math.max(0,ls.length-10)+',').split(',');
            return ls.slice(
              page[0],
              page[1] === ''
                ? undefined
                : parseInt(page[0])+(parseInt(page[1])||10)
            );
          }
        })().map(function(log) { return parseLog(log); }).reverse();
      } else {
        res.writeHead(302, { 'Location': url.pathname+'?update' });
        res.end();
        return;
      }
      if (format === 'html') {
        model.status = statusChars[model.status];
        model.logs = model.logs.map(function(log) {
          return log ? logToHtml(log) : '';
        }).join('');
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(template(model));
      } else if (url.query.log && format === 'text') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(model.logs[0].log);
      } else {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(model));
      }
    } else {
      res.writeHead(500);
      res.end("Directory not a bare git repo?");
    }
  } else {
    res.writeHead(404);
    res.end("Directory not found.");
  }
}).listen(port);

console.log('tinci vision at http://localhost:'+port+'/your/git/repo');
<commit_msg>Fallback listening port to env variable PORT after cli argument<commit_after>#!/usr/bin/env node

var fs = require('fs'),
    path = require('path'),
    parse = require('url').parse,
    http = require('http'),
    exec = require('child_process').exec,
    rootpath = path.resolve(process.argv[2] || '.'),
    port = parseInt(process.argv[3]) || process.env.PORT || 4567,
    tmpl = fs.readFileSync(require.resolve('./template.html'), 'utf8'),
    hookpath = require.resolve('./hooks/post-receive'),
    hookVersion = parseHookVersion(hookpath),
    guiVersion = require('./package.json').version,
    ansiRe = new RegExp('\033\\[(\\d+)m', 'g'),
    statusChars = ['✓', '✗', '—'];

function esc(str) {
  return str.replace(/'/g, '"');
}

function fdate(d) {
  return d.toDateString() + ' ' + d.toLocaleTimeString();
}

function colorize(text) {
  var count = 0;
  return text.replace(ansiRe, function(_, code) {
    var res;
    if (code === '0') {
      res = new Array(count+1).join('');
      count = 0;
    } else {
      res = '';
      count++;
    }
    return res;
  })+new Array(count+1).join('');
};

function logExec(cmd, callback) {
  console.log('Execting shell command:', cmd);
  exec(cmd, function (err, stdout, stderr) {
    console.log(err, stderr);
    if (callback) callback(err, stdout, stderr);
  });
}
function copyHook(to, runner, match, callback) {
  var eto = esc(to), er = esc(runner), em = esc(match);
  logExec("cp '"+esc(hookpath)+"' '"+eto+"/hooks/post-receive' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.runner '"+er+"' && "+
    "git config -f '"+eto+"/config' --replace-all tinci.match '"+em+"'",
  callback);
}

function invokeHook(to, before, after, ref, callback) {
  var eref = esc(ref);
  logExec("cd '"+esc(to)+"' && git fetch origin '"+eref+":"+eref+"' && "+
    "echo '"+esc(before+" "+after+" "+ref)+"' | hooks/post-receive",
  callback);
}

function parseHookVersion(hookpath) {
  var m;
  if (!fs.existsSync(hookpath)) return;
  m = fs.readFileSync(hookpath, 'utf8').match(/TINCIV=([\d.]+)/);
  return m !== null ? m[1] : false;
}

function template(model) {
  var html = tmpl, i;
  for (i in model) html = html.split('{{'+i+'}}').join(model[i]);
  return html;
}

function logToHtml(log) {
  return '

' +
    statusChars[log.status] + ' ' + log.ref +
    ' '+ fdate(log.ctime) + ' ' + log.rev +
    '
' + '
' +
    colorize(log.log.replace(/\r?\n/g, '
')) + '

';
}

function parseLog(log) {
  var refm;
  if (!log.log) {
    log.log = fs.readFileSync(log.path, 'utf8').trim();
    log.ref = (refm = /# ref refs\/(?:heads|tags)\/(.*)/.exec(log.log), refm ? refm[1] : '');
    log.exitcode = log.log.slice(log.log.lastIndexOf('\n')+1).split(' ').slice(-1)[0];
    log.status = /^\d+$/.test(log.exitcode) ? (log.exitcode==='0' ? 0 : 1) : 2;
  }
  return log;
}

function logs(tincipath) {
  var res = {logs:[], dict:{}};
  if (fs.existsSync(tincipath)) {
    res.logs = fs.readdirSync(tincipath).filter(function(file){
      return file.slice(-4) === '.log';
    }).map(function(file) {
      var filepath = path.join(tincipath, file),
          rev = path.basename(file, '.log');
      return res.dict[rev] = {
        path: filepath,
        rev: rev,
        ctime: fs.statSync(filepath).ctime
      };
    }).sort(function(a, b){ return a.ctime - b.ctime; });
  }
  return res;
}

http.createServer(function(req, res) {
  var url = parse(req.url, true),
      pathname = path.resolve(rootpath, './'+url.pathname),
      format = url.query.format || 'html',
      model = {}, data = '?', logs_, ls, dict,
      page, reponame, tincipath, hookv;
  if (pathname.indexOf(rootpath) === 0 && fs.existsSync(pathname)) {
    reponame = path.basename(pathname, '.git');
    if (fs.existsSync(path.join(pathname, 'hooks'))) {
      if ('invoke' in url.query) {
        req.on('data', function(chunk) { data += chunk; })
        .on('end', function() {
          var gitinfo;
          try {
            gitinfo = JSON.parse(parse(data, true).query.payload);
            invokeHook(pathname, gitinfo.before, gitinfo.after, gitinfo.ref);
            res.writeHead(200);
          } catch (ex) {
            res.writeHead(500);
            console.log('Error on invoke call: '+ex.message);
          }
          res.end();
        });
        return;
      }
      hookv = parseHookVersion(path.resolve(pathname, 'hooks', 'post-receive'));
      model = {
          title: reponame,
          status: 2,
          logs: [],
          guiVersion: guiVersion,
          hookVersion: hookVersion,
          installedVersion: hookv
      };
      if ('update' in url.query) {
        if (url.query.runner) {
          copyHook(
            pathname,
            url.query.runner,
            url.query.match||'master',
            function () {
              res.writeHead(302, { 'Location': url.pathname });
              res.end();
            }
          );
          return;
        } else {
          if (hookv != null) model.overwrite = 'show';
          model.config = 'show';
        }
      } else if (hookv) {
        tincipath = path.join(pathname, '.tinci');
        logs_ = logs(tincipath);
        ls = logs_.logs;
        dict = logs_.dict;
        if (ls.length) model.status = parseLog(ls[ls.length-1]).status;
        model.logs = (function(){
          if (url.query.log) {
            return [dict[url.query.log]];
          } else {
            page = (url.query.page || Math.max(0,ls.length-10)+',').split(',');
            return ls.slice(
              page[0],
              page[1] === ''
                ? undefined
                : parseInt(page[0])+(parseInt(page[1])||10)
            );
          }
        })().map(function(log) { return parseLog(log); }).reverse();
      } else {
        res.writeHead(302, { 'Location': url.pathname+'?update' });
        res.end();
        return;
      }
      if (format === 'html') {
        model.status = statusChars[model.status];
        model.logs = model.logs.map(function(log) {
          return log ? logToHtml(log) : '';
        }).join('');
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(template(model));
      } else if (url.query.log && format === 'text') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(model.logs[0].log);
      } else {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(model));
      }
    } else {
      res.writeHead(500);
      res.end("Directory not a bare git repo?");
    }
  } else {
    res.writeHead(404);
    res.end("Directory not found.");
  }
}).listen(port);

console.log('tinci vision at http://localhost:'+port);
<|endoftext|>


<commit_before>function Queue() {
  this._queue = [];
}

Queue.prototype.add = function(fn) {
  this._queue.push(fn);
  return this;
}

Queue.prototype._virginScope = function(cb){
  var executed = false;
  return function() {
    if (executed) throw new Error('callback can\'t be executed twice');
    executed = true;
    cb.apply(this, Array.prototype.slice.call(arguments));
  }
}

Queue.prototype.run = function(cb) {
  var q = this;
  var next = function(error) {
    if (error) return cb(error);
    var task = q._queue.shift();
    if (task) {
      task(q._virginScope(next));
    } else {
      cb();
    }
  }
  next();
}
<commit_msg>ADD: extend execution prevention to false values<commit_after>function Queue() {
  this._queue = [];
}

Queue.prototype.add = function(fn) {
  this._queue.push(fn);
  return this;
}

Queue.prototype._virginScope = function(cb){
  var executed = false;
  return function() {
    if (executed) throw new Error('callback can\'t be executed twice');
    executed = true;
    cb.apply(this, Array.prototype.slice.call(arguments));
  }
}

Queue.prototype.run = function(cb) {
  var q = this;
  var next = function(error) {
    if (error !== void 0) return cb(error);
    var task = q._queue.shift();
    if (task) {
      task(q._virginScope(next));
    } else {
      cb();
    }
  }
  next();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
*  Cek Resi CLI
*  (c) 2016 Ipan Ardian
*
*  A command line app to tracking AWB number
*  For details, see the web site: https://github.com/ipanardian/cekresi-cli
*  The MIT License
*/
'use strict'

const VERSION = 'v1.0.7'

if (process.argv.length <= 2) {
    console.log("Usage: cekresi-cli AWB_NUMBER")
    process.exit(-1)
}

var param = process.argv[2]
if (param == '--version') {
	console.log(VERSION)
	process.exit(-1)
}
else if (param.length < 5 || !param.match(/^[a-z0-9]+$/i)) {
	console.log('Invalid AWB Number')
	process.exit(-1)
}

var Horseman = require('node-horseman')
var cheerio = require('cheerio')
var tabletojson = require('tabletojson')
var Table = require('cli-table')
var colors = require('colors')
var Spinner = require('cli-spinner').Spinner
var spinner = new Spinner('Checking... %s ')
spinner.setSpinnerString(7)
spinner.start()

var horseman = new Horseman()
	horseman
	.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.3")
	.on('error', function(message, trace) {
		console.log(message)
	})
	.on('timeout', function(message) {
		console.log('Timeout\n')
	})
	.open('http://cekresi.com/?noresi='+param)
	.click("#cekresi")
	.waitFor(function(selector) {
		return $(selector).is(':visible')
	}, '#results', true)
	.evaluate(function() {
		return document.querySelector('#results').innerHTML
	})
	.then(function(result) {
		cekresi.load(result).parse()
	})
	.finally(function() {
	    horseman.close()
	    spinner.stop()
	    return
	})

var cekresi = {
	result: null,
	tablesAsJson: null,
	infoExpedisi: null,
	el: null,
	checkResult() {
		return (this.result != '' && this.infoExpedisi != '' ? true:false)
	},
	load(res) {
		this.parseHTML(res)
		this.result = res
		this.infoExpedisi = this.el('h3.top_title').text()
		return this
	},
	parseHTML(html) {
		this.el = cheerio.load(html)
	},
	parseDeliveryInfo() {
		var deliveryTable = new Table()
		for (let tr in this.tablesAsJson[0]){
			let row = []
			for (let td in this.tablesAsJson[0][tr]) {
				row.push(this.tablesAsJson[0][tr][td])
			}
			deliveryTable.push(row)
		}
		print(deliveryTable.toString())
	},
	parseActivityInfo() {
		let header = []
		let body = []
		for (let i = 1; i <= this.tablesAsJson.length - 1; i++) {
			for (let tr in this.tablesAsJson[i]) {
				let row = []
				for (let td in this.tablesAsJson[i][tr]) {
					if (body.length < 1)
						header.push(td)

					row.push(this.tablesAsJson[i][tr][td])
				}
				body.push(row)
			}
		}
		var activityTable = new Table({head: header})
		for (let item in body) {
			activityTable.push(body[item])
		}
		print(activityTable.toString())
	},
	parse() {
		if (this.checkResult()) {
			this.tablesAsJson = tabletojson.convert(this.result)
			print('\n==================== '+ this.infoExpedisi.yellow +' =========================\n')
			this.parseDeliveryInfo()
			print('')
			this.parseActivityInfo()
		}
		else {
			print('\nMaaf no resi yang anda masukkan sementara tidak dapat kami proses'.yellow)
		}
		print('\nFor details: https://github.com/ipanardian/cekresi-cli')
	}
}

function print(msg) {
	console.log(msg)
}<commit_msg>Short argument for version<commit_after>#!/usr/bin/env node
/**
*  Cek Resi CLI
*  (c) 2016 Ipan Ardian
*
*  A command line app to tracking AWB number
*  For details, see the web site: https://github.com/ipanardian/cekresi-cli
*  The MIT License
*/
'use strict'

const VERSION = 'v1.0.7'

if (process.argv.length <= 2) {
    console.log("Usage: cekresi-cli AWB_NUMBER")
    process.exit(-1)
}

var param = process.argv[2]
if (param == '--version' || param == '-v') {
	console.log(VERSION)
	process.exit(-1)
}
else if (param.length < 5 || !param.match(/^[a-z0-9]+$/i)) {
	console.log('Invalid AWB Number')
	process.exit(-1)
}

var Horseman = require('node-horseman')
var cheerio = require('cheerio')
var tabletojson = require('tabletojson')
var Table = require('cli-table')
var colors = require('colors')
var Spinner = require('cli-spinner').Spinner
var spinner = new Spinner('Checking... %s ')
spinner.setSpinnerString(7)
spinner.start()

var horseman = new Horseman()
	horseman
	.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.3")
	.on('error', function(message, trace) {
		console.log(message)
	})
	.on('timeout', function(message) {
		console.log('Timeout\n')
	})
	.open('http://cekresi.com/?noresi='+param)
	.click("#cekresi")
	.waitFor(function(selector) {
		return $(selector).is(':visible')
	}, '#results', true)
	.evaluate(function() {
		return document.querySelector('#results').innerHTML
	})
	.then(function(result) {
		cekresi.load(result).parse()
	})
	.finally(function() {
	    horseman.close()
	    spinner.stop()
	    return
	})

var cekresi = {
	result: null,
	tablesAsJson: null,
	infoExpedisi: null,
	el: null,
	checkResult() {
		return (this.result != '' && this.infoExpedisi != '' ? true:false)
	},
	load(res) {
		this.parseHTML(res)
		this.result = res
		this.infoExpedisi = this.el('h3.top_title').text()
		return this
	},
	parseHTML(html) {
		this.el = cheerio.load(html)
	},
	parseDeliveryInfo() {
		var deliveryTable = new Table()
		for (let tr in this.tablesAsJson[0]){
			let row = []
			for (let td in this.tablesAsJson[0][tr]) {
				row.push(this.tablesAsJson[0][tr][td])
			}
			deliveryTable.push(row)
		}
		print(deliveryTable.toString())
	},
	parseActivityInfo() {
		let header = []
		let body = []
		for (let i = 1; i <= this.tablesAsJson.length - 1; i++) {
			for (let tr in this.tablesAsJson[i]) {
				let row = []
				for (let td in this.tablesAsJson[i][tr]) {
					if (body.length < 1)
						header.push(td)

					row.push(this.tablesAsJson[i][tr][td])
				}
				body.push(row)
			}
		}
		var activityTable = new Table({head: header})
		for (let item in body) {
			activityTable.push(body[item])
		}
		print(activityTable.toString())
	},
	parse() {
		if (this.checkResult()) {
			this.tablesAsJson = tabletojson.convert(this.result)
			print('\n==================== '+ this.infoExpedisi.yellow +' =========================\n')
			this.parseDeliveryInfo()
			print('')
			this.parseActivityInfo()
		}
		else {
			print('\nMaaf no resi yang anda masukkan sementara tidak dapat kami proses'.yellow)
		}
		print('\nFor details: https://github.com/ipanardian/cekresi-cli')
	}
}

function print(msg) {
	console.log(msg)
}<|endoftext|>


<commit_before>var moduleFactory = require('./lib/shared/ModuleFactory.js');
var request = require('./lib/shared/Request.js');
var reply = require('./lib/shared/Reply.js');
var errorHandler = require('./lib/shared/ErrorHandler.js');
var user = require('./lib/shared/User.js');
var fs = require('fs');

// sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');

// sign with RSA SHA256
var cert = fs.readFileSync('rsa.pub');  // get private key

exports.handler = function(event, context){
  if(context.functionName == "tsLogin"){
	  event.RIN = event.email;
  } else {
	  event.RIN = Number(event.RIN);
  }
  console.log(event);
  var callingFunction = context.functionName;
  var token = event.sessionToken;

  var req = request(token,event,context);
  var rep = reply(req);
  var err = errorHandler(req);
  //NEED TO LOOKUP IN USERDB FIRST, FIX

  var decoded = {};
  if(typeof token != 'undefined'){
    try {
      decoded = jwt.verify(token, cert, { algorithms: ['RS256'] });
    } catch(err) {
      console.log(err);
      console.log('token invalid');
    }
  }
  else {
    decoded.RIN = parseInt(Number(event.email));
  }

  console.log('Loading user');
  var usr = user(decoded.RIN,token);

  var module = moduleFactory(callingFunction, usr, req, rep);
  module.run();
  console.log('Module completed execution');

};

var serve = function(){
  // Encapsulate expressJS dependency
  var express = require('express');
  var app = express();

  // Enable CORS
  app.use(function(request, result, next) {
    result.header('Access-Control-Allow-Origin', '*');
    result.header('Access-Control-Allow-Headers',
                  'Origin, X-Requested-With, Content-Type, Accept');
    next();
  });

  // Enable POST parsing
  var bodyParser = require('body-parser');
  app.use(bodyParser.json()); // Parses application/json
  app.use(bodyParser.urlencoded({extended: true})); // Parses form encoded

  // Generate event and context for Lambda handler
  var genEventContext = function(request, response){
    console.log('Received request');
    // Make a context object
    var context = {};
    // Set up callbacks
    context.succeed = context.fail = function(payload){
      //console.log('Sending payload: ', payload);
      //console.log('Using response: ', response);
      response.send(payload);
    };
    // Get root URL
    context.functionName = request.path.split('/')[2];

    // Make a fake evt
    var evt = {};

    var extend = function(target, source) {
      for(var index in source){
        target[index] = source[index];
      }
    }
    // Concatenate with query string
    extend(evt, request.query);
    // Concatenate with body
    extend(evt, request.body);

    return { evt: evt, context: context };
  }

  var callLambda = function(eventContext){
    console.log('Calling exports handler');
    try {
      exports.handler(eventContext.evt, eventContext.context);
    } catch(error) {
      console.error('Failed to run module ',
                    eventContext.context.functionName,
                    'for reason:', error);
    }
  }

  // Create GET handler
  app.get('/api/*', function(request, response) {
    var eventContext = genEventContext(request, response);
    eventContext.context.httpMethod = 'GET';
    callLambda(eventContext);
  });

  // Create POST handler
  app.post('/api/*', function(request, response) {
    var eventContext = genEventContext(request, response);
    eventContext.context.httpMethod = 'POST';
    callLambda(eventContext);
  });

  var staticWebLocation = require('process').env.STATIC_WEB_DIR || './StaticWeb/dist';

  // Serve static content
  app.use('/', express.static(staticWebLocation));

  // Start server
  var listener = app.listen(5000, function(){
    console.log('Server started, serving from', staticWebLocation);
  });
};

serve();
<commit_msg>Style, readability, changes<commit_after>var moduleFactory = require('./lib/shared/ModuleFactory.js');
var request = require('./lib/shared/Request.js');
var reply = require('./lib/shared/Reply.js');
var errorHandler = require('./lib/shared/ErrorHandler.js');
var user = require('./lib/shared/User.js');
var fs = require('fs');

// sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');

// sign with RSA SHA256
var cert = fs.readFileSync('rsa.pub');  // get private key

// Server Settings
var SERVER_PORT = 5000;

exports.handler = function(event, context){
  if(context.functionName == "tsLogin"){
	  event.RIN = event.email;
  } else {
	  event.RIN = Number(event.RIN);
  }
  console.log(event);
  var callingFunction = context.functionName;
  var token = event.sessionToken;

  var req = request(token,event,context);
  var rep = reply(req);
  var err = errorHandler(req);
  //NEED TO LOOKUP IN USERDB FIRST, FIX

  var decoded = {};
  if(typeof token != 'undefined'){
    try {
      decoded = jwt.verify(token, cert, { algorithms: ['RS256'] });
    } catch(err) {
      console.log(err);
      console.log('token invalid');
    }
  }
  else {
    decoded.RIN = parseInt(Number(event.email));
  }

  console.log('Loading user');
  var usr = user(decoded.RIN,token);

  var module = moduleFactory(callingFunction, usr, req, rep);
  module.run();
  console.log('Module completed execution');

};

var serve = function(){
  // Encapsulate expressJS dependency
  var express = require('express');
  var app = express();

  // Enable CORS
  app.use(function(request, result, next) {
    result.header('Access-Control-Allow-Origin', '*');
    result.header('Access-Control-Allow-Headers',
                  'Origin, X-Requested-With, Content-Type, Accept');
    next();
  });

  // Enable POST parsing
  var bodyParser = require('body-parser');
  app.use(bodyParser.json()); // Parses application/json
  app.use(bodyParser.urlencoded({extended: true})); // Parses form encoded

  // Generate event and context for Lambda handler
  var genEventContext = function(request, response){
    console.log('Received request');
    // Make a context object
    var context = {};
    // Set up callbacks
    context.succeed = context.fail = function(payload){
      console.log('Sending payload: ', payload);
      response.send(payload);
    };
    // Get root URL
    context.functionName = request.path.split('/')[2];

    // Make a fake evt
    var evt = {};

    var extend = function(target, source) {
      for(var index in source){
        target[index] = source[index];
      }
    }
    // Concatenate with query string
    extend(evt, request.query);
    // Concatenate with body
    extend(evt, request.body);

    return { evt: evt, context: context };
  }

  var callLambda = function(eventContext){
    console.log('Calling exports handler');
    try {
      exports.handler(eventContext.evt, eventContext.context);
    } catch(error) {
      console.error('Failed to run module ',
                    eventContext.context.functionName,
                    'for reason:', error);
    }
  }

  // Create GET handler
  app.get('/api/*', function(request, response) {
    var eventContext = genEventContext(request, response);
    eventContext.context.httpMethod = 'GET';
    callLambda(eventContext);
  });

  // Create POST handler
  app.post('/api/*', function(request, response) {
    var eventContext = genEventContext(request, response);
    eventContext.context.httpMethod = 'POST';
    callLambda(eventContext);
  });

  var staticWebLocation = require('process').env.STATIC_WEB_DIR ||
                                            './StaticWeb/dist';

  // Serve static content
  app.use('/', express.static(staticWebLocation));

  // Start server
  var listener = app.listen(SERVER_PORT, function(){
    console.log('Server started, serving from', staticWebLocation);
  });
};

serve();
<|endoftext|>


<commit_before>var babylonToEspree = require("./babylon-to-espree");
var pick            = require("lodash.pickby");
var Module          = require("module");
var path            = require("path");
var parse           = require("babylon").parse;
var t               = require("babel-types");
var tt              = require("babylon").tokTypes;
var traverse        = require("babel-traverse").default;
var codeFrame       = require("babel-code-frame");

var hasPatched = false;
var eslintOptions = {};

function createModule(filename) {
  var mod = new Module(filename);
  mod.filename = filename;
  mod.paths = Module._nodeModulePaths(path.dirname(filename));
  return mod;
}

function monkeypatch() {
  if (hasPatched) return;
  hasPatched = true;

  var eslintLoc;
  try {
    // avoid importing a local copy of eslint, try to find a peer dependency
    eslintLoc = Module._resolveFilename("eslint", module.parent);
  } catch (err) {
    try {
      // avoids breaking in jest where module.parent is undefined
      eslintLoc = require.resolve("eslint");
    } catch (err) {
      throw new ReferenceError("couldn't resolve eslint");
    }
  }

  // get modules relative to what eslint will load
  var eslintMod = createModule(eslintLoc);
  // contains all the instances of estraverse so we can modify them if necessary
  var estraverses = [];
  // ESLint v1.9.0 uses estraverse directly to work around https://github.com/npm/npm/issues/9663
  var estraverseOfEslint = eslintMod.require("estraverse");
  estraverses.push(estraverseOfEslint);
  Object.assign(estraverseOfEslint.VisitorKeys, t.VISITOR_KEYS);

  estraverses.forEach(function (estraverse) {
    estraverse.VisitorKeys.MethodDefinition.push("decorators");
    estraverse.VisitorKeys.Property.push("decorators");
  });

  // monkeypatch escope
  var escopeLoc = Module._resolveFilename("escope", eslintMod);
  var escopeMod = createModule(escopeLoc);
  var escope  = require(escopeLoc);
  var analyze = escope.analyze;
  escope.analyze = function (ast, opts) {
    opts.ecmaVersion = eslintOptions.ecmaVersion;
    opts.sourceType = eslintOptions.sourceType;
    if (eslintOptions.globalReturn !== undefined) {
      opts.nodejsScope = eslintOptions.globalReturn;
    }

    var results = analyze.call(this, ast, opts);
    return results;
  };

  // monkeypatch escope/referencer
  var referencerLoc;
  try {
    referencerLoc = Module._resolveFilename("./referencer", escopeMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/referencer");
  }
  var referencerMod = createModule(referencerLoc);
  var referencer = require(referencerLoc);
  if (referencer.__esModule) {
    referencer = referencer.default;
  }

  // reference Definition
  var definitionLoc;
  try {
    definitionLoc = Module._resolveFilename("./definition", referencerMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/definition");
  }
  var Definition = require(definitionLoc).Definition;

  // if there are decorators, then visit each
  function visitDecorators(node) {
    if (!node.decorators) {
      return;
    }
    for (var i = 0; i < node.decorators.length; i++) {
      if (node.decorators[i].expression) {
        this.visit(node.decorators[i]);
      }
    }
  }

  // iterate through part of t.VISITOR_KEYS
  var visitorKeysMap = pick(t.VISITOR_KEYS, function(k) {
    return t.FLIPPED_ALIAS_KEYS.Flow.concat([
      "ArrayPattern",
      "ClassDeclaration",
      "ClassExpression",
      "FunctionDeclaration",
      "FunctionExpression",
      "Identifier",
      "ObjectPattern",
      "RestElement"
    ]).indexOf(k) === -1;
  });

  var propertyTypes = {
    // loops
    callProperties: { type: "loop", values: ["value"] },
    indexers: { type: "loop", values: ["key", "value"] },
    properties: { type: "loop", values: ["value"] },
    types: { type: "loop" },
    params: { type: "loop" },
    // single property
    argument: { type: "single" },
    elementType: { type: "single" },
    qualification: { type: "single" },
    rest: { type: "single" },
    returnType: { type: "single" },
    // others
    typeAnnotation: { type: "typeAnnotation" },
    typeParameters: { type: "typeParameters" },
    id: { type: "id" }
  };

  function visitTypeAnnotation(node) {
    // get property to check (params, id, etc...)
    var visitorValues = visitorKeysMap[node.type];
    if (!visitorValues) {
      return;
    }

    // can have multiple properties
    for (var i = 0; i < visitorValues.length; i++) {
      var visitorValue = visitorValues[i];
      var propertyType = propertyTypes[visitorValue];
      var nodeProperty = node[visitorValue];
      // check if property or type is defined
      if (propertyType == null || nodeProperty == null) {
        continue;
      }
      if (propertyType.type === "loop") {
        for (var j = 0; j < nodeProperty.length; j++) {
          if (Array.isArray(propertyType.values)) {
            for (var k = 0; k < propertyType.values.length; k++) {
              checkIdentifierOrVisit.call(this, nodeProperty[j][propertyType.values[k]]);
            }
          } else {
            checkIdentifierOrVisit.call(this, nodeProperty[j]);
          }
        }
      } else if (propertyType.type === "single") {
        checkIdentifierOrVisit.call(this, nodeProperty);
      } else if (propertyType.type === "typeAnnotation") {
        visitTypeAnnotation.call(this, node.typeAnnotation);
      } else if (propertyType.type === "typeParameters") {
        for (var l = 0; l < node.typeParameters.params.length; l++) {
          checkIdentifierOrVisit.call(this, node.typeParameters.params[l]);
        }
      } else if (propertyType.type === "id") {
        if (node.id.type === "Identifier") {
          checkIdentifierOrVisit.call(this, node.id);
        } else {
          visitTypeAnnotation.call(this, node.id);
        }
      }
    }
  }

  function checkIdentifierOrVisit(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    } else if (node.type === "Identifier") {
      this.visit(node);
    } else {
      visitTypeAnnotation.call(this, node);
    }
  }

  function nestTypeParamScope(manager, node) {
    var parentScope = manager.__currentScope;
    var scope = new escope.Scope(manager, "type-parameters", parentScope, node, false);
    manager.__nestScope(scope);
    for (var j = 0; j < node.typeParameters.params.length; j++) {
      var name = node.typeParameters.params[j];
      scope.__define(name, new Definition("TypeParameter", name, name));
    }
    scope.__define = function() {
      return parentScope.__define.apply(parentScope, arguments);
    };
    return scope;
  }

  // visit decorators that are in: ClassDeclaration / ClassExpression
  var visitClass = referencer.prototype.visitClass;
  referencer.prototype.visitClass = function(node) {
    visitDecorators.call(this, node);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    // visit flow type: ClassImplements
    if (node.implements) {
      for (var i = 0; i < node.implements.length; i++) {
        checkIdentifierOrVisit.call(this, node.implements[i]);
      }
    }
    if (node.superTypeParameters) {
      for (var k = 0; k < node.superTypeParameters.params.length; k++) {
        checkIdentifierOrVisit.call(this, node.superTypeParameters.params[k]);
      }
    }
    visitClass.call(this, node);
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit decorators that are in: Property / MethodDefinition
  var visitProperty = referencer.prototype.visitProperty;
  referencer.prototype.visitProperty = function(node) {
    if (node.value && node.value.type === "TypeCastExpression") {
      visitTypeAnnotation.call(this, node.value);
    }
    visitDecorators.call(this, node);
    visitProperty.call(this, node);
  };

  // visit ClassProperty as a Property.
  referencer.prototype.ClassProperty = function(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    }
    this.visitProperty(node);
  };

  // visit flow type in FunctionDeclaration, FunctionExpression, ArrowFunctionExpression
  var visitFunction = referencer.prototype.visitFunction;
  referencer.prototype.visitFunction = function(node) {
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.returnType) {
      checkIdentifierOrVisit.call(this, node.returnType);
    }
    // only visit if function parameters have types
    if (node.params) {
      for (var i = 0; i < node.params.length; i++) {
        var param = node.params[i];
        if (param.typeAnnotation) {
          checkIdentifierOrVisit.call(this, param);
        } else if (t.isAssignmentPattern(param)) {
          if (param.left.typeAnnotation) {
            checkIdentifierOrVisit.call(this, param.left);
          }
        }
      }
    }
    // set ArrayPattern/ObjectPattern visitor keys back to their original. otherwise
    // escope will traverse into them and include the identifiers within as declarations
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = ["properties"];
      estraverse.VisitorKeys.ArrayPattern = ["elements"];
    });
    visitFunction.call(this, node);
    // set them back to normal...
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = t.VISITOR_KEYS.ObjectPattern;
      estraverse.VisitorKeys.ArrayPattern = t.VISITOR_KEYS.ArrayPattern;
    });
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit flow type in VariableDeclaration
  var variableDeclaration = referencer.prototype.VariableDeclaration;
  referencer.prototype.VariableDeclaration = function(node) {
    if (node.declarations) {
      for (var i = 0; i < node.declarations.length; i++) {
        var id = node.declarations[i].id;
        var typeAnnotation = id.typeAnnotation;
        if (typeAnnotation) {
          checkIdentifierOrVisit.call(this, typeAnnotation);
        }
      }
    }
    variableDeclaration.call(this, node);
  };

  function createScopeVariable (node, name) {
    this.currentScope().variableScope.__define(name,
      new Definition(
        "Variable",
        name,
        node,
        null,
        null,
        null
      )
    );
  }

  referencer.prototype.TypeAlias = function(node) {
    createScopeVariable.call(this, node, node.id);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.right) {
      visitTypeAnnotation.call(this, node.right);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };

  referencer.prototype.DeclareModule =
  referencer.prototype.DeclareFunction =
  referencer.prototype.DeclareVariable =
  referencer.prototype.DeclareClass = function(node) {
    if (node.id) {
      createScopeVariable.call(this, node, node.id);
    }

    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };
}

exports.parse = function (code, options) {
  options = options || {};
  eslintOptions.ecmaVersion = options.ecmaVersion = options.ecmaVersion || 6;
  eslintOptions.sourceType = options.sourceType = options.sourceType || "module";
  eslintOptions.allowImportExportEverywhere = options.allowImportExportEverywhere = options.allowImportExportEverywhere || false;
  if (options.sourceType === "module") {
    eslintOptions.globalReturn = false;
  } else {
    delete eslintOptions.globalReturn;
  }

  try {
    monkeypatch();
  } catch (err) {
    console.error(err.stack);
    process.exit(1);
  }

  return exports.parseNoPatch(code, options);
};

exports.parseNoPatch = function (code, options) {
  var opts = {
    sourceType: options.sourceType,
    allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
    allowReturnOutsideFunction: true,
    allowSuperOutsideMethod: true,
    plugins: ["*"]
  };

  var ast;
  try {
    ast = parse(code, opts);
  } catch (err) {
    if (err instanceof SyntaxError) {
      err.lineNumber = err.loc.line;
      err.column = err.loc.column + 1;

      // remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
      err.message = "Line " + err.lineNumber + ": " + err.message.replace(/ \((\d+):(\d+)\)$/, "") +
      // add codeframe
      "\n\n" +
      codeFrame(code, err.lineNumber, err.column, { highlightCode: true });
    }

    throw err;
  }

  // remove EOF token, eslint doesn't use this for anything and it interferes with some rules
  // see https://github.com/babel/babel-eslint/issues/2 for more info
  // todo: find a more elegant way to do this
  ast.tokens.pop();

  // convert tokens
  ast.tokens = babylonToEspree.toTokens(ast.tokens, tt, code);

  // add comments
  babylonToEspree.convertComments(ast.comments);

  // transform esprima and acorn divergent nodes
  babylonToEspree.toAST(ast, traverse, code);

  // ast.program.tokens = ast.tokens;
  // ast.program.comments = ast.comments;
  // ast = ast.program;

  // remove File
  ast.type = "Program";
  ast.sourceType = ast.program.sourceType;
  ast.directives = ast.program.directives;
  ast.body = ast.program.body;
  delete ast.program;
  delete ast._paths;

  babylonToEspree.attachComments(ast, ast.comments, ast.tokens);

  return ast;
};
<commit_msg>Revert "use `*`" (#426)<commit_after>var babylonToEspree = require("./babylon-to-espree");
var pick            = require("lodash.pickby");
var Module          = require("module");
var path            = require("path");
var parse           = require("babylon").parse;
var t               = require("babel-types");
var tt              = require("babylon").tokTypes;
var traverse        = require("babel-traverse").default;
var codeFrame       = require("babel-code-frame");

var hasPatched = false;
var eslintOptions = {};

function createModule(filename) {
  var mod = new Module(filename);
  mod.filename = filename;
  mod.paths = Module._nodeModulePaths(path.dirname(filename));
  return mod;
}

function monkeypatch() {
  if (hasPatched) return;
  hasPatched = true;

  var eslintLoc;
  try {
    // avoid importing a local copy of eslint, try to find a peer dependency
    eslintLoc = Module._resolveFilename("eslint", module.parent);
  } catch (err) {
    try {
      // avoids breaking in jest where module.parent is undefined
      eslintLoc = require.resolve("eslint");
    } catch (err) {
      throw new ReferenceError("couldn't resolve eslint");
    }
  }

  // get modules relative to what eslint will load
  var eslintMod = createModule(eslintLoc);
  // contains all the instances of estraverse so we can modify them if necessary
  var estraverses = [];
  // ESLint v1.9.0 uses estraverse directly to work around https://github.com/npm/npm/issues/9663
  var estraverseOfEslint = eslintMod.require("estraverse");
  estraverses.push(estraverseOfEslint);
  Object.assign(estraverseOfEslint.VisitorKeys, t.VISITOR_KEYS);

  estraverses.forEach(function (estraverse) {
    estraverse.VisitorKeys.MethodDefinition.push("decorators");
    estraverse.VisitorKeys.Property.push("decorators");
  });

  // monkeypatch escope
  var escopeLoc = Module._resolveFilename("escope", eslintMod);
  var escopeMod = createModule(escopeLoc);
  var escope  = require(escopeLoc);
  var analyze = escope.analyze;
  escope.analyze = function (ast, opts) {
    opts.ecmaVersion = eslintOptions.ecmaVersion;
    opts.sourceType = eslintOptions.sourceType;
    if (eslintOptions.globalReturn !== undefined) {
      opts.nodejsScope = eslintOptions.globalReturn;
    }

    var results = analyze.call(this, ast, opts);
    return results;
  };

  // monkeypatch escope/referencer
  var referencerLoc;
  try {
    referencerLoc = Module._resolveFilename("./referencer", escopeMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/referencer");
  }
  var referencerMod = createModule(referencerLoc);
  var referencer = require(referencerLoc);
  if (referencer.__esModule) {
    referencer = referencer.default;
  }

  // reference Definition
  var definitionLoc;
  try {
    definitionLoc = Module._resolveFilename("./definition", referencerMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/definition");
  }
  var Definition = require(definitionLoc).Definition;

  // if there are decorators, then visit each
  function visitDecorators(node) {
    if (!node.decorators) {
      return;
    }
    for (var i = 0; i < node.decorators.length; i++) {
      if (node.decorators[i].expression) {
        this.visit(node.decorators[i]);
      }
    }
  }

  // iterate through part of t.VISITOR_KEYS
  var visitorKeysMap = pick(t.VISITOR_KEYS, function(k) {
    return t.FLIPPED_ALIAS_KEYS.Flow.concat([
      "ArrayPattern",
      "ClassDeclaration",
      "ClassExpression",
      "FunctionDeclaration",
      "FunctionExpression",
      "Identifier",
      "ObjectPattern",
      "RestElement"
    ]).indexOf(k) === -1;
  });

  var propertyTypes = {
    // loops
    callProperties: { type: "loop", values: ["value"] },
    indexers: { type: "loop", values: ["key", "value"] },
    properties: { type: "loop", values: ["value"] },
    types: { type: "loop" },
    params: { type: "loop" },
    // single property
    argument: { type: "single" },
    elementType: { type: "single" },
    qualification: { type: "single" },
    rest: { type: "single" },
    returnType: { type: "single" },
    // others
    typeAnnotation: { type: "typeAnnotation" },
    typeParameters: { type: "typeParameters" },
    id: { type: "id" }
  };

  function visitTypeAnnotation(node) {
    // get property to check (params, id, etc...)
    var visitorValues = visitorKeysMap[node.type];
    if (!visitorValues) {
      return;
    }

    // can have multiple properties
    for (var i = 0; i < visitorValues.length; i++) {
      var visitorValue = visitorValues[i];
      var propertyType = propertyTypes[visitorValue];
      var nodeProperty = node[visitorValue];
      // check if property or type is defined
      if (propertyType == null || nodeProperty == null) {
        continue;
      }
      if (propertyType.type === "loop") {
        for (var j = 0; j < nodeProperty.length; j++) {
          if (Array.isArray(propertyType.values)) {
            for (var k = 0; k < propertyType.values.length; k++) {
              checkIdentifierOrVisit.call(this, nodeProperty[j][propertyType.values[k]]);
            }
          } else {
            checkIdentifierOrVisit.call(this, nodeProperty[j]);
          }
        }
      } else if (propertyType.type === "single") {
        checkIdentifierOrVisit.call(this, nodeProperty);
      } else if (propertyType.type === "typeAnnotation") {
        visitTypeAnnotation.call(this, node.typeAnnotation);
      } else if (propertyType.type === "typeParameters") {
        for (var l = 0; l < node.typeParameters.params.length; l++) {
          checkIdentifierOrVisit.call(this, node.typeParameters.params[l]);
        }
      } else if (propertyType.type === "id") {
        if (node.id.type === "Identifier") {
          checkIdentifierOrVisit.call(this, node.id);
        } else {
          visitTypeAnnotation.call(this, node.id);
        }
      }
    }
  }

  function checkIdentifierOrVisit(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    } else if (node.type === "Identifier") {
      this.visit(node);
    } else {
      visitTypeAnnotation.call(this, node);
    }
  }

  function nestTypeParamScope(manager, node) {
    var parentScope = manager.__currentScope;
    var scope = new escope.Scope(manager, "type-parameters", parentScope, node, false);
    manager.__nestScope(scope);
    for (var j = 0; j < node.typeParameters.params.length; j++) {
      var name = node.typeParameters.params[j];
      scope.__define(name, new Definition("TypeParameter", name, name));
    }
    scope.__define = function() {
      return parentScope.__define.apply(parentScope, arguments);
    };
    return scope;
  }

  // visit decorators that are in: ClassDeclaration / ClassExpression
  var visitClass = referencer.prototype.visitClass;
  referencer.prototype.visitClass = function(node) {
    visitDecorators.call(this, node);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    // visit flow type: ClassImplements
    if (node.implements) {
      for (var i = 0; i < node.implements.length; i++) {
        checkIdentifierOrVisit.call(this, node.implements[i]);
      }
    }
    if (node.superTypeParameters) {
      for (var k = 0; k < node.superTypeParameters.params.length; k++) {
        checkIdentifierOrVisit.call(this, node.superTypeParameters.params[k]);
      }
    }
    visitClass.call(this, node);
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit decorators that are in: Property / MethodDefinition
  var visitProperty = referencer.prototype.visitProperty;
  referencer.prototype.visitProperty = function(node) {
    if (node.value && node.value.type === "TypeCastExpression") {
      visitTypeAnnotation.call(this, node.value);
    }
    visitDecorators.call(this, node);
    visitProperty.call(this, node);
  };

  // visit ClassProperty as a Property.
  referencer.prototype.ClassProperty = function(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    }
    this.visitProperty(node);
  };

  // visit flow type in FunctionDeclaration, FunctionExpression, ArrowFunctionExpression
  var visitFunction = referencer.prototype.visitFunction;
  referencer.prototype.visitFunction = function(node) {
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.returnType) {
      checkIdentifierOrVisit.call(this, node.returnType);
    }
    // only visit if function parameters have types
    if (node.params) {
      for (var i = 0; i < node.params.length; i++) {
        var param = node.params[i];
        if (param.typeAnnotation) {
          checkIdentifierOrVisit.call(this, param);
        } else if (t.isAssignmentPattern(param)) {
          if (param.left.typeAnnotation) {
            checkIdentifierOrVisit.call(this, param.left);
          }
        }
      }
    }
    // set ArrayPattern/ObjectPattern visitor keys back to their original. otherwise
    // escope will traverse into them and include the identifiers within as declarations
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = ["properties"];
      estraverse.VisitorKeys.ArrayPattern = ["elements"];
    });
    visitFunction.call(this, node);
    // set them back to normal...
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = t.VISITOR_KEYS.ObjectPattern;
      estraverse.VisitorKeys.ArrayPattern = t.VISITOR_KEYS.ArrayPattern;
    });
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit flow type in VariableDeclaration
  var variableDeclaration = referencer.prototype.VariableDeclaration;
  referencer.prototype.VariableDeclaration = function(node) {
    if (node.declarations) {
      for (var i = 0; i < node.declarations.length; i++) {
        var id = node.declarations[i].id;
        var typeAnnotation = id.typeAnnotation;
        if (typeAnnotation) {
          checkIdentifierOrVisit.call(this, typeAnnotation);
        }
      }
    }
    variableDeclaration.call(this, node);
  };

  function createScopeVariable (node, name) {
    this.currentScope().variableScope.__define(name,
      new Definition(
        "Variable",
        name,
        node,
        null,
        null,
        null
      )
    );
  }

  referencer.prototype.TypeAlias = function(node) {
    createScopeVariable.call(this, node, node.id);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.right) {
      visitTypeAnnotation.call(this, node.right);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };

  referencer.prototype.DeclareModule =
  referencer.prototype.DeclareFunction =
  referencer.prototype.DeclareVariable =
  referencer.prototype.DeclareClass = function(node) {
    if (node.id) {
      createScopeVariable.call(this, node, node.id);
    }

    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };
}

exports.parse = function (code, options) {
  options = options || {};
  eslintOptions.ecmaVersion = options.ecmaVersion = options.ecmaVersion || 6;
  eslintOptions.sourceType = options.sourceType = options.sourceType || "module";
  eslintOptions.allowImportExportEverywhere = options.allowImportExportEverywhere = options.allowImportExportEverywhere || false;
  if (options.sourceType === "module") {
    eslintOptions.globalReturn = false;
  } else {
    delete eslintOptions.globalReturn;
  }

  try {
    monkeypatch();
  } catch (err) {
    console.error(err.stack);
    process.exit(1);
  }

  return exports.parseNoPatch(code, options);
};

exports.parseNoPatch = function (code, options) {
  var opts = {
    sourceType: options.sourceType,
    allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
    allowReturnOutsideFunction: true,
    allowSuperOutsideMethod: true,
    plugins: [
      "flow",
      "jsx",
      "asyncFunctions",
      "asyncGenerators",
      "classConstructorCall",
      "classProperties",
      "decorators",
      "doExpressions",
      "exponentiationOperator",
      "exportExtensions",
      "functionBind",
      "functionSent",
      "objectRestSpread",
      "trailingFunctionCommas",
      "dynamicImport"
    ]
  };

  var ast;
  try {
    ast = parse(code, opts);
  } catch (err) {
    if (err instanceof SyntaxError) {
      err.lineNumber = err.loc.line;
      err.column = err.loc.column + 1;

      // remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
      err.message = "Line " + err.lineNumber + ": " + err.message.replace(/ \((\d+):(\d+)\)$/, "") +
      // add codeframe
      "\n\n" +
      codeFrame(code, err.lineNumber, err.column, { highlightCode: true });
    }

    throw err;
  }

  // remove EOF token, eslint doesn't use this for anything and it interferes with some rules
  // see https://github.com/babel/babel-eslint/issues/2 for more info
  // todo: find a more elegant way to do this
  ast.tokens.pop();

  // convert tokens
  ast.tokens = babylonToEspree.toTokens(ast.tokens, tt, code);

  // add comments
  babylonToEspree.convertComments(ast.comments);

  // transform esprima and acorn divergent nodes
  babylonToEspree.toAST(ast, traverse, code);

  // ast.program.tokens = ast.tokens;
  // ast.program.comments = ast.comments;
  // ast = ast.program;

  // remove File
  ast.type = "Program";
  ast.sourceType = ast.program.sourceType;
  ast.directives = ast.program.directives;
  ast.body = ast.program.body;
  delete ast.program;
  delete ast._paths;

  babylonToEspree.attachComments(ast, ast.comments, ast.tokens);

  return ast;
};
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});
var borde = [
    "Ja",
    "Nej"
]
var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"

var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

bot.on("message", (message) => {

    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {

        case "h":
        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!github - skickar länken till botens github repo\n!ping - visar botens internal ping (för felsökning)\n!poll <fråga> - Starta en ja eller nej fråga")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema\n!hex - ger dig en slumpmässig färg\n!schemavecka <vecka> - visar schemat från en viss vecka\n!vecka - visar veckan")
                    .setColor("0x111111")
            });
            break;
        case "vecka":
            message.channel.send(weekNumber);
            break;
        case "s":
        case "schema":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+weekNumber+":")
                    .setImage(schemaLink)
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        //case "sv":
        case "schemavecka":
            /*if (message.content = "!schemavecka") {
                var valfriVecka = message.content.substring(13);
            }
            else {
                var valfriVecka = message.content.substring(4);
                console.log(valfriVecka);
            }*/
            var valfriVecka = message.content.substring(13)
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+valfriVecka+":")
                    .setImage("http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+valfriVecka+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847")
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        case "säg":
        case "say":
            var textFromSender = message.content;
            message.delete(0);
            if (message.author.id==="164283691802165250") {
                message.channel.send(message.content.substring(5));
                break;
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
                break;
            }
        case "ping":
            message.channel.send(bot.ping+" ms");
            break;
        case "hex":
            var randomhex = ("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6);
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+randomhex)
                    .setColor("0x"+randomhex)
            });
            break;
        case "poll":
            var question = message.content.substring(6)
            message.delete(0);
            message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.react("👎")
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram")
                   });
            break;
        case "pinpoll":
            var question = message.content.substring(9)
            message.delete(0);
            if (message.author.id==="164283691802165250" || "349987894171271178") {
                message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.react("👎")
                    message.pin()
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram (pinpoll)")
                    });
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
            }
            break;
        case "hd":
        case "hexdisplay":
            var hexMessage = message.content.substring(12)
            if (hexMessage.substr(0, 1) === "#") {
                var hexMessageFix = hexMessage.substing(1)
            }
            else {
                var hexMessageFix = hexMessage
            }
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+hexMessageFix)
                    .setColor("0x"+hexMessageFix)
            });
            break;
        case "borde":
            message.channel.send([Math.floor(Math.random() * borde.length)]);
            break;
        default:
            message.channel.send("```Detta kommando existerar inte (än)\nSkriv !help för att se de kommandon som faktiskt existerar```");

    }
});

bot.login(botToken);<commit_msg>Fixade till !borde<commit_after>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});
var borde = [
    "Ja",
    "Nej"
]
var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"

var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

bot.on("message", (message) => {

    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {

        case "h":
        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!github - skickar länken till botens github repo\n!ping - visar botens internal ping (för felsökning)\n!poll <fråga> - Starta en ja eller nej fråga")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema\n!hex - ger dig en slumpmässig färg\n!schemavecka <vecka> - visar schemat från en viss vecka\n!vecka - visar veckan")
                    .setColor("0x111111")
            });
            break;
        case "vecka":
            message.channel.send(weekNumber);
            break;
        case "s":
        case "schema":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+weekNumber+":")
                    .setImage(schemaLink)
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        //case "sv":
        case "schemavecka":
            /*if (message.content = "!schemavecka") {
                var valfriVecka = message.content.substring(13);
            }
            else {
                var valfriVecka = message.content.substring(4);
                console.log(valfriVecka);
            }*/
            var valfriVecka = message.content.substring(13)
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+valfriVecka+":")
                    .setImage("http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+valfriVecka+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847")
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        case "säg":
        case "say":
            var textFromSender = message.content;
            message.delete(0);
            if (message.author.id==="164283691802165250") {
                message.channel.send(message.content.substring(5));
                break;
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
                break;
            }
        case "ping":
            message.channel.send(bot.ping+" ms");
            break;
        case "hex":
            var randomhex = ("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6);
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+randomhex)
                    .setColor("0x"+randomhex)
            });
            break;
        case "poll":
            var question = message.content.substring(6)
            message.delete(0);
            message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.react("👎")
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram")
                   });
            break;
        case "pinpoll":
            var question = message.content.substring(9)
            message.delete(0);
            if (message.author.id==="164283691802165250" || "349987894171271178") {
                message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.react("👎")
                    message.pin()
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram (pinpoll)")
                    });
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
            }
            break;
        case "hd":
        case "hexdisplay":
            var hexMessage = message.content.substring(12)
            if (hexMessage.substr(0, 1) === "#") {
                var hexMessageFix = hexMessage.substing(1)
            }
            else {
                var hexMessageFix = hexMessage
            }
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+hexMessageFix)
                    .setColor("0x"+hexMessageFix)
            });
            break;
        case "borde":
            message.channel.sendMessage(borde[Math.floor(Math.random()*borde.length)]+message.author.toString());
            break;
        default:
            message.channel.send("```Detta kommando existerar inte (än)\nSkriv !help för att se de kommandon som faktiskt existerar```");

    }
});

bot.login(botToken);<|endoftext|>