<commit_before>#!/usr/bin/env node
const pkg = require('./package.json');
const config = require('./config.js');
const request = require('request');

const cookieJar = request.jar();

const log = require('yalm');

log.loglevel = ['debug', 'info', 'warn', 'error'].indexOf(config.verbosity) !== -1 ? config.verbosity : 'info';

log.info(pkg.name + ' ' + pkg.version + ' starting');

const Mqtt = require('mqtt');

log.info('mqtt trying to connect', config.url);
const mqtt = Mqtt.connect(config.url, {will: {topic: config.name + '/connected', payload: '0', retain: true}});
mqtt.publish(config.name + '/connected', '1');

let connected;

mqtt.on('connect', () => {
    connected = true;
    log.info('mqtt connected ' + config.url);
});

mqtt.on('close', () => {
    if (connected) {
        connected = false;
        log.info('mqtt closed ' + config.url);
    }
});

mqtt.on('error', () => {
    log.error('mqtt error ' + config.url);
});

let numMeters;
const names = {};

getAuthCookie(getMeters);

function getAuthCookie(callback) {
    log.info('login on ' + config.smartmeter);
    request.get({
        url: 'http://' + config.smartmeter + '/index.php',
        jar: cookieJar
    }, (err, res, body) => {
        if (err) {
            log.error('auth failed');
            stop();
        } else {
            mqtt.publish(config.name + '/connected', '2', {retain: true});
            callback();
        }
    });
}

function getMeters() {
    request.get({
        url: 'http://' + config.smartmeter + '/mum-webservice/meters.php',
        jar: cookieJar
    }, (err, res, body) => {
        const data = JSON.parse(body);
        if (data.authentication == false) {
            log.error('auth failure');
            mqtt.publish(config.name + '/connected', '1', {retain: true});
            setTimeout(() => {
                getAuthCookie(getMeters);
            }, 60000);
            return;
        }

        const meters = data.meters;

        numMeters = meters.length;

        for (let i = 0; i < meters.length; i++) {
            names[i] = meters[i].label;
            // Names[i] = names[i].replace(/Teridian/, 'Gesamtverbrauch');
            log.debug(i, meters[i]);
        }

        loop();
    });
}

let meter_index = 0;

function loop() {
    if (++meter_index >= numMeters) {
        meter_index = 0;
    }
    getValue(meter_index, () => {
        setTimeout(loop, config.interval);
    });
}

function getValue(meter_id, callback) {
    request.post({
        jar: cookieJar,
        url: 'http://' + config.smartmeter + '/mum-webservice/consumption.php?meter_id=' + meter_id
    }, (err, res, body) => {
        if (err) {
            log.error(err);
            return;
        }
        try {
            var data = JSON.parse(body);
        } catch (e) {
            log.error(e.message);
            return;
        }
        if (data.authentication == false) {
            mqtt.publish(config.name + '/connected', '1', {retain: true});
            log.error('auth failure');
            getAuthCookie(getMeters);
            return;
        }

        const idx = ('0' + (meter_id + 1)).slice(-2);

        const topic = config.name + '/status/' + names[meter_id];
        const payload = JSON.stringify({val: parseFloat((data[idx + '_power'] * 1000).toFixed(1))});

        log.debug(topic, payload);
        mqtt.publish(topic, payload, {retain: true});
        callback();
    });
}

process.on('SIGINT', () => {
    log.info('got SIGINT. exiting.');
    process.exit(0);
});
process.on('SIGTERM', () => {
    log.info('got SIGTERM. exiting.');
    process.exit(0);
});
<commit_msg>linting<commit_after>#!/usr/bin/env node

const Mqtt = require('mqtt');
const request = require('request');
const log = require('yalm');
const pkg = require('./package.json');
const config = require('./config.js');

const cookieJar = request.jar();

log.loglevel = ['debug', 'info', 'warn', 'error'].indexOf(config.verbosity) === -1 ? 'info' : config.verbosity;

log.info(pkg.name + ' ' + pkg.version + ' starting');

log.info('mqtt trying to connect', config.url);
const mqtt = Mqtt.connect(config.url, {will: {topic: config.name + '/connected', payload: '0', retain: true}});
mqtt.publish(config.name + '/connected', '1');

let connected;

mqtt.on('connect', () => {
    connected = true;
    log.info('mqtt connected ' + config.url);
});

mqtt.on('close', () => {
    if (connected) {
        connected = false;
        log.info('mqtt closed ' + config.url);
    }
});

mqtt.on('error', () => {
    log.error('mqtt error ' + config.url);
});

let numMeters;
const names = {};

getAuthCookie(getMeters);

function getAuthCookie(callback) {
    log.info('login on ' + config.smartmeter);
    request.get({
        url: 'http://' + config.smartmeter + '/index.php',
        jar: cookieJar
    }, err => {
        if (err) {
            log.error('auth failed');
            process.exit(1);
        } else {
            mqtt.publish(config.name + '/connected', '2', {retain: true});
            callback();
        }
    });
}

function getMeters() {
    request.get({
        url: 'http://' + config.smartmeter + '/mum-webservice/meters.php',
        jar: cookieJar
    }, (err, res, body) => {
        if (err) {
            log.error('getMeters failed');
            process.exit(1);
        }
        const data = JSON.parse(body);
        if (!data.authentication) {
            log.error('auth failure');
            mqtt.publish(config.name + '/connected', '1', {retain: true});
            setTimeout(() => {
                getAuthCookie(getMeters);
            }, 60000);
            return;
        }

        const meters = data.meters;

        numMeters = meters.length;

        for (let i = 0; i < meters.length; i++) {
            names[i] = meters[i].label;
            // Names[i] = names[i].replace(/Teridian/, 'Gesamtverbrauch');
            log.debug(i, meters[i]);
        }

        loop();
    });
}

let meterIndex = 0;

function loop() {
    if (++meterIndex >= numMeters) {
        meterIndex = 0;
    }
    getValue(meterIndex, () => {
        setTimeout(loop, config.interval);
    });
}

function getValue(meterId, callback) {
    request.post({
        jar: cookieJar,
        url: 'http://' + config.smartmeter + '/mum-webservice/consumption.php?meter_id=' + meterId
    }, (err, res, body) => {
        if (err) {
            log.error(err);
            return;
        }
        let data;
        try {
            data = JSON.parse(body);
        } catch (err) {
            log.error(err.message);
            return;
        }
        if (!data.authentication) {
            mqtt.publish(config.name + '/connected', '1', {retain: true});
            log.error('auth failure');
            getAuthCookie(getMeters);
            return;
        }

        const idx = ('0' + (meterId + 1)).slice(-2);

        const topic = config.name + '/status/' + names[meterId];
        const payload = JSON.stringify({val: parseFloat((data[idx + '_power'] * 1000).toFixed(1))});

        log.debug(topic, payload);
        mqtt.publish(topic, payload, {retain: true});
        callback();
    });
}

process.on('SIGINT', () => {
    log.info('got SIGINT. exiting.');
    process.exit(0);
});
process.on('SIGTERM', () => {
    log.info('got SIGTERM. exiting.');
    process.exit(0);
});
<|endoftext|>


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

// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TChannel = require('tchannel');
var TChannelAsThrift = require('tchannel/as/thrift');
var TChannelAsJSON = require('tchannel/as/json');
var minimist = require('minimist');
var myLocalIp = require('my-local-ip');
var DebugLogtron = require('debug-logtron');

var console = require('console');
var process = require('process');
var fs = require('fs');
var path = require('path');
var url = require('url');
var assert = require('assert');

var Logger = require('./log');
var TCurlAsHttp = require('./as-http');

main.exec = execMain;

module.exports = main;

if (require.main === module) {
    main(minimist(process.argv.slice(2), {
        boolean: ['raw']
    }));
}

function execMain(str, cb) {
    main(minimist(str, {
        boolean: ['raw']
    }), cb);
}

function help() {
    console.log('tcurl -p host:port <service> <endpoint> [options]');
    console.log('  ');
    console.log('  Options: ');
    // TODO @file; @- stdin.
    console.log('    -2 [data] send an arg2 blob');
    console.log('    -3 [data] send an arg3 blob');
    console.log('    --depth=n configure inspect printing depth');
    console.log('    -j print JSON');
    console.log('    -J [indent] print JSON with indentation');
    console.log('    -t [dir] directory containing Thrift files');
    console.log('    --http method');
    console.log('    --raw encode arg2 & arg3 raw');
    return;
}

function parseArgs(argv) {
    var body = argv['3'] || argv.arg3 || '';
    var head = argv['2'] || argv.arg2 || '';

    var uri = argv.p || argv.peer;
    var thrift = argv.t || argv.thrift;
    var http = argv.http;
    var json = argv.j || argv.J;
    var service = argv._[0];
    var endpoint = argv._[1];
    var parsedUri = url.parse('tchannel://' + uri);

    if (parsedUri.hostname === 'localhost') {
        parsedUri.hostname = myLocalIp();
    }

    assert(parsedUri.hostname, 'host required');
    assert(parsedUri.port, 'port required');
    assert(endpoint, 'endpoint required');
    assert(service, 'service required');

    return {
        head: head,
        body: body,
        service: service,
        endpoint: endpoint,
        hostname: parsedUri.hostname,
        port: parsedUri.port,
        thrift: thrift,
        http: http,
        json: json,
        raw: argv.raw,
        depth: argv.depth
    };
}

function main(argv, onResponse) {
    /*eslint no-console: 0 */
    if (argv.h || argv.help || argv._.length === 0) {
        return help();
    }

    var opts = parseArgs(argv);
    opts.onResponse = onResponse;
    tcurl(opts);
}

function tcurl(opts) {
    var logger = Logger(opts);
    var spec;
    if (opts.thrift) {
        var specs = {};
        var files = fs.readdirSync(opts.thrift);
        files.forEach(function eachFile(file) {
            var match = /([^\/]+)\.thrift$/.exec(file);
            if (match) {
                var serviceName = match[1];
                var fileName = match[0];
                specs[serviceName] =
                    fs.readFileSync(path.join(opts.thrift, fileName), 'utf8');
            }
        });

        spec = specs[opts.service];
        if (!spec) {
            throw new Error('Spec for service unavailable: ' + opts.service);
        }
    }

    var client = TChannel({
        logger: DebugLogtron('tcurl')
    });
    var subChan = client.makeSubChannel({
        serviceName: opts.service,
        requestDefaults: {
            headers: {
                cn: 'tcurl'
            }
        }
    });

    client.on('listening', onListen);
    client.listen(0, '127.0.0.1');

    function onListen() {
        client.removeListener('listening', onListen);

        client.waitForIdentified({
            host: opts.hostname + ':' + opts.port
        }, onIdentified);
    }

    function onIdentified(err) {
        if (err) {
            return onResponse(err);
        }

        var request = subChan.request({
            host: opts.hostname + ':' + opts.port,
            timeout: opts.timeout || 5000,
            hasNoParent: true,
            serviceName: opts.service
        });
        var sender;
        if (opts.thrift) {
            if (opts.body) {
                opts.body = JSON.parse(opts.body);
            }

            sender = new TChannelAsThrift({source: spec});
            sender.send(request, opts.endpoint, opts.head,
                opts.body, onResponse);
        } else if (opts.raw) {
            request.headers.as = 'raw';
            request.send(opts.endpoint, opts.head, opts.body,
                onResponse);
        } else if (opts.http) {
            var ashttp = TCurlAsHttp({
                remoteHostPort: opts.hostname + ':' + opts.port,
                serviceName: opts.service,
                method: opts.http,
                path: opts.endpoint,
                headers: JSON.parse(opts.head),
                body: JSON.parse(opts.body),
                onResponse: onResponse,
                logger: logger
            });
            ashttp.send();
        } else {
            sender = new TChannelAsJSON();

            if (opts.body) {
                opts.body = JSON.parse(opts.body);
            }
            if (opts.head) {
                opts.head = JSON.parse(opts.head);
            }
            sender.send(request, opts.endpoint, opts.head,
                opts.body, onResponse);
        }
    }

    function onResponse(err, resp, arg2, arg3) {
        if (arg2 !== undefined && resp) {
            resp.head = arg2;
        }
        if (arg3 !== undefined && resp) {
            resp.body = arg3;
        }

        if (opts.onResponse) {
            opts.onResponse(err, resp, arg2, arg3);
            client.quit();
            return;
        }

        if (err) {
            logger.log('error', err);
            logger.log('error', err.message);
            /*eslint no-process-exit: 0*/
            process.exit(1);
        }

        if (!resp.ok) {
            logger.log('error', 'Got call response not ok');
            logger.log('error', resp.body);
            process.exit(1);
        } else {
            logger.display('log', 'Got call response ok');
        }

        logger.display('log', resp.body);
        client.quit();
    }
}
<commit_msg>change default timeout to 100ms<commit_after>#!/usr/bin/env node

// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TChannel = require('tchannel');
var TChannelAsThrift = require('tchannel/as/thrift');
var TChannelAsJSON = require('tchannel/as/json');
var minimist = require('minimist');
var myLocalIp = require('my-local-ip');
var DebugLogtron = require('debug-logtron');

var console = require('console');
var process = require('process');
var fs = require('fs');
var path = require('path');
var url = require('url');
var assert = require('assert');

var Logger = require('./log');
var TCurlAsHttp = require('./as-http');

main.exec = execMain;

module.exports = main;

if (require.main === module) {
    main(minimist(process.argv.slice(2), {
        boolean: ['raw']
    }));
}

function execMain(str, cb) {
    main(minimist(str, {
        boolean: ['raw']
    }), cb);
}

function help() {
    console.log('tcurl -p host:port <service> <endpoint> [options]');
    console.log('  ');
    console.log('  Options: ');
    // TODO @file; @- stdin.
    console.log('    -2 [data] send an arg2 blob');
    console.log('    -3 [data] send an arg3 blob');
    console.log('    --depth=n configure inspect printing depth');
    console.log('    -j print JSON');
    console.log('    -J [indent] print JSON with indentation');
    console.log('    -t [dir] directory containing Thrift files');
    console.log('    --http method');
    console.log('    --raw encode arg2 & arg3 raw');
    return;
}

function parseArgs(argv) {
    var body = argv['3'] || argv.arg3 || '';
    var head = argv['2'] || argv.arg2 || '';

    var uri = argv.p || argv.peer;
    var thrift = argv.t || argv.thrift;
    var http = argv.http;
    var json = argv.j || argv.J;
    var service = argv._[0];
    var endpoint = argv._[1];
    var parsedUri = url.parse('tchannel://' + uri);

    if (parsedUri.hostname === 'localhost') {
        parsedUri.hostname = myLocalIp();
    }

    assert(parsedUri.hostname, 'host required');
    assert(parsedUri.port, 'port required');
    assert(endpoint, 'endpoint required');
    assert(service, 'service required');

    return {
        head: head,
        body: body,
        service: service,
        endpoint: endpoint,
        hostname: parsedUri.hostname,
        port: parsedUri.port,
        thrift: thrift,
        http: http,
        json: json,
        raw: argv.raw,
        depth: argv.depth
    };
}

function main(argv, onResponse) {
    /*eslint no-console: 0 */
    if (argv.h || argv.help || argv._.length === 0) {
        return help();
    }

    var opts = parseArgs(argv);
    opts.onResponse = onResponse;
    tcurl(opts);
}

function tcurl(opts) {
    var logger = Logger(opts);
    var spec;
    if (opts.thrift) {
        var specs = {};
        var files = fs.readdirSync(opts.thrift);
        files.forEach(function eachFile(file) {
            var match = /([^\/]+)\.thrift$/.exec(file);
            if (match) {
                var serviceName = match[1];
                var fileName = match[0];
                specs[serviceName] =
                    fs.readFileSync(path.join(opts.thrift, fileName), 'utf8');
            }
        });

        spec = specs[opts.service];
        if (!spec) {
            throw new Error('Spec for service unavailable: ' + opts.service);
        }
    }

    var client = TChannel({
        logger: DebugLogtron('tcurl')
    });
    var subChan = client.makeSubChannel({
        serviceName: opts.service,
        requestDefaults: {
            headers: {
                cn: 'tcurl'
            }
        }
    });

    client.on('listening', onListen);
    client.listen(0, '127.0.0.1');

    function onListen() {
        client.removeListener('listening', onListen);

        client.waitForIdentified({
            host: opts.hostname + ':' + opts.port
        }, onIdentified);
    }

    function onIdentified(err) {
        if (err) {
            return onResponse(err);
        }

        var request = subChan.request({
            host: opts.hostname + ':' + opts.port,
            timeout: opts.timeout || 100,
            hasNoParent: true,
            serviceName: opts.service
        });
        var sender;
        if (opts.thrift) {
            if (opts.body) {
                opts.body = JSON.parse(opts.body);
            }

            sender = new TChannelAsThrift({source: spec});
            sender.send(request, opts.endpoint, opts.head,
                opts.body, onResponse);
        } else if (opts.raw) {
            request.headers.as = 'raw';
            request.send(opts.endpoint, opts.head, opts.body,
                onResponse);
        } else if (opts.http) {
            var ashttp = TCurlAsHttp({
                remoteHostPort: opts.hostname + ':' + opts.port,
                serviceName: opts.service,
                method: opts.http,
                path: opts.endpoint,
                headers: JSON.parse(opts.head),
                body: JSON.parse(opts.body),
                onResponse: onResponse,
                logger: logger
            });
            ashttp.send();
        } else {
            sender = new TChannelAsJSON();

            if (opts.body) {
                opts.body = JSON.parse(opts.body);
            }
            if (opts.head) {
                opts.head = JSON.parse(opts.head);
            }
            sender.send(request, opts.endpoint, opts.head,
                opts.body, onResponse);
        }
    }

    function onResponse(err, resp, arg2, arg3) {
        if (arg2 !== undefined && resp) {
            resp.head = arg2;
        }
        if (arg3 !== undefined && resp) {
            resp.body = arg3;
        }

        if (opts.onResponse) {
            opts.onResponse(err, resp, arg2, arg3);
            client.quit();
            return;
        }

        if (err) {
            logger.log('error', err);
            logger.log('error', err.message);
            /*eslint no-process-exit: 0*/
            process.exit(1);
        }

        if (!resp.ok) {
            logger.log('error', 'Got call response not ok');
            logger.log('error', resp.body);
            process.exit(1);
        } else {
            logger.display('log', 'Got call response ok');
        }

        logger.display('log', resp.body);
        client.quit();
    }
}
<|endoftext|>


<commit_before>'use strict';

var
	platform = require('enyo/platform'),
	dispatcher = require('enyo/dispatcher'),
	gesture = require('enyo/gesture');

exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';

// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
	events: [{name: 'hold', time: 400}],
	endHold: 'onLeave'
});

/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
	// Table of default keyCode mappings for webOS device
	dispatcher.registerKeyMap({
		415 : 'play',
		413 : 'stop',
		19  : 'pause',
		412 : 'rewind',
		417 : 'fastforward',
		461 : 'back'
	});
}

// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts');<commit_msg>Update version string to 2.6.0-pre.14.1<commit_after>'use strict';

var
	platform = require('enyo/platform'),
	dispatcher = require('enyo/dispatcher'),
	gesture = require('enyo/gesture');

exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';

// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
	events: [{name: 'hold', time: 400}],
	endHold: 'onLeave'
});

/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
	// Table of default keyCode mappings for webOS device
	dispatcher.registerKeyMap({
		415 : 'play',
		413 : 'stop',
		19  : 'pause',
		412 : 'rewind',
		417 : 'fastforward',
		461 : 'back'
	});
}

// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts');
<|endoftext|>


<commit_before>const app = require('express')(),
  server = require('http').Server(app);

// Static files
app.use(express.static('build'));

app.get('/', (req, res) => {
  res.send('hello world');
});

app.get('/status.json', (req, res) => {
  res.json({ status: 'ok' });
});

app.get('*', function(req, res) {
  res.sendfile(__dirname + '/build/index.html');
});

// Create the server
app.listen(3001);
<commit_msg>Fix server requires<commit_after>const express = require('express'),
 app = express();

// Static files
app.use(express.static('build'));

app.get('/', (req, res) => {
  res.send('hello world');
});

app.get('/status.json', (req, res) => {
  res.json({ status: 'ok' });
});

app.get('*', function(req, res) {
  res.sendfile(__dirname + '/build/index.html');
});

// Create the server
app.listen(3001);
<|endoftext|>


<commit_before>module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:import/recommended',
  ],

  env: {
    browser: true,
    es6: true,
    node: true,
  },

  plugins: [
    'import',
  ],

  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
    ecmaVersion: 2017,
    sourceType: 'module',
  },

  rules: {
    'array-bracket-newline': 0, // TODO: when it supports single item line-breaked array (like `plugins` above): [2, { multiline: true }],
    'array-bracket-spacing': [1, 'never'],
    'array-callback-return': 2,
    'array-element-newline': 0, // TODO: when it supports single item line-breaked array (like `plugins` above): [2, { multiline: true }],
    'arrow-parens': [2, 'as-needed', { requireForBlockBody: true }],
    'block-scoped-var': 0,
    'brace-style': [2, '1tbs', { allowSingleLine: false }],
    'camelcase': [2, { properties: 'never' }],
    'comma-dangle': [2, 'always-multiline'],
    'comma-spacing': [2, { before: false, after: true }],
    'comma-style': [2, 'last'],
    'complexity': [1, 10],
    'computed-property-spacing': [2, 'never'],
    'consistent-return': 0,
    'curly': 2,
    'dot-notation': 2,
    'eol-last': [2, 'unix'],
    'eqeqeq': 2,
    'for-direction': 2,
    'getter-return': 2,
    'func-call-spacing': 2,
    'guard-for-in': 2,
    'indent': [2, 2, { SwitchCase: 1 }],
    'jsx-quotes': [2, 'prefer-single'],
    'import/default': 0, // TODO: enable once module.exports is supported
    'import/extensions': 2,
    'import/first': 2,
    'import/newline-after-import': 2,
    'import/no-absolute-path': 2,
    'import/no-anonymous-default-export': 0, // TODO: we are discussing this rule's options
    'import/no-deprecated': 1, // NOTE: this rule is still in WIP stage
    'import/no-duplicates': 2,
    'import/no-dynamic-require': 2,
    'import/no-extraneous-dependencies': 2,
    'import/no-internal-modules': 0, // NOTE: Brigade uses a mono-repo + Lerna which curently does not play nice with this rule
    'import/no-mutable-exports': 2,
    'import/no-named-as-default-member': 2,
    'import/no-named-as-default': 2,
    'import/no-named-default': 2,
    'import/no-namespace': 2,
    'import/no-unassigned-import': 1, // NOTE: sometimes we do global polyfills - we'd like to make this a 2 eventually...
    'import/no-webpack-loader-syntax': 2,
    'import/order': [
      2,
      {
        groups: [
          'builtin',
          'external',
          'internal',
          ['index', 'sibling', 'parent'],
        ],
      },
    ],
    'import/prefer-default-export': 2,
    'import/unambiguous': 0, // NOTE: needed until we fully adopt import/export over modules.export
    'object-curly-spacing': [1, 'always'],
    'key-spacing': 0,
    'keyword-spacing': 2,
    'max-len': [2, { code: 100, ignoreComments: true, ignoreUrls: true }],
    'max-nested-callbacks': 0,
    'max-params': [1, 4],
    'new-cap': [2, { newIsCap: true, capIsNew: false }],
    'new-parens': 2,
    'no-alert': 2,
    'no-array-constructor': 2,
    'no-await-in-loop': 2,
    'no-bitwise': 2,
    'no-caller': 2,
    'no-catch-shadow': 0, // NOTE: Off because we don't support IE8 and older
    'no-compare-neg-zero': 2,
    'no-cond-assign': 2,
    'no-confusing-arrow': [2,  { allowParens: true }],
    'no-constant-condition': 2,
    'no-control-regex': 2,
    'no-debugger': 2,
    'no-dupe-args': 2,
    'no-dupe-keys': 2,
    'no-duplicate-imports': 2,
    'no-eq-null': 2,
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-floating-decimal': 2,
    'no-func-assign': 2,
    'no-implied-eval': 2,
    'no-iterator': 2,
    'no-label-var': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-lonely-if': 2,
    'no-loop-func': 0,
    'no-multi-spaces': 0,
    'no-multi-str': 2,
    'no-multiple-empty-lines': 2,
    'no-nested-ternary': 2,
    'no-new': 2,
    'no-new-func': 2,
    'no-new-object': 2,
    'no-new-wrappers': 2,
    'no-octal-escape': 2,
    'no-process-exit': 2,
    'no-proto': 2,
    'no-restricted-globals': [2, 'event'],
    'no-return-assign': 0,
    'no-return-await': 2,
    'no-script-url': 2,
    'no-self-compare': 2,
    'no-sequences': 2,
    'no-shadow': 2,
    'no-shadow-restricted-names': 2,
    'no-throw-literal': 2,
    'no-trailing-spaces': 2,
    'no-undef-init': 2,
    'no-underscore-dangle': 0,
    'no-unsafe-negation': 2,
    'no-unused-expressions': 2,
    'no-use-before-define': 2,
    'no-var': 2,
    'no-void': 2,
    'no-with': 2,
    'object-shorthand': [2, 'always'],
    'operator-assignment': [2, 'always'],
    'operator-linebreak': [2, 'after'],
    'padded-blocks': [2, 'never'],
    'padding-line-between-statements': 0,
    'prefer-const': 2,
    'quotes': [2, 'single', 'avoid-escape'],
    'radix': 2,
    'semi': [2, 'always'],
    'semi-spacing': [2, { before: false, after: true }],
    'semi-style': 2,
    'space-before-blocks': [2, 'always'],
    'space-before-function-paren': [
      2,
      {
        anonymous: 'never',
        named: 'never',
        asyncArrow: 'always',
      },
    ],
    'space-in-parens': [2, 'never'],
    'space-infix-ops': 2,
    'space-unary-ops': 2,
    'spaced-comment': [2, 'always'],
    'strict': [2, 'never'],
    'switch-colon-spacing': 2,
    'valid-jsdoc': [
      2,
      {
        prefer: { returns: 'return' },
        requireParamDescription: false,
        requireReturn: false,
      },
    ],
    'wrap-iife': [2, 'outside'],
    'yoda': 2,
  },
};
<commit_msg>Add rule: no-duplicate-case<commit_after>module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:import/recommended',
  ],

  env: {
    browser: true,
    es6: true,
    node: true,
  },

  plugins: [
    'import',
  ],

  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
    },
    ecmaVersion: 2017,
    sourceType: 'module',
  },

  rules: {
    'array-bracket-newline': 0, // TODO: when it supports single item line-breaked array (like `plugins` above): [2, { multiline: true }],
    'array-bracket-spacing': [1, 'never'],
    'array-callback-return': 2,
    'array-element-newline': 0, // TODO: when it supports single item line-breaked array (like `plugins` above): [2, { multiline: true }],
    'arrow-parens': [2, 'as-needed', { requireForBlockBody: true }],
    'block-scoped-var': 0,
    'brace-style': [2, '1tbs', { allowSingleLine: false }],
    'camelcase': [2, { properties: 'never' }],
    'comma-dangle': [2, 'always-multiline'],
    'comma-spacing': [2, { before: false, after: true }],
    'comma-style': [2, 'last'],
    'complexity': [1, 10],
    'computed-property-spacing': [2, 'never'],
    'consistent-return': 0,
    'curly': 2,
    'dot-notation': 2,
    'eol-last': [2, 'unix'],
    'eqeqeq': 2,
    'for-direction': 2,
    'getter-return': 2,
    'func-call-spacing': 2,
    'guard-for-in': 2,
    'indent': [2, 2, { SwitchCase: 1 }],
    'jsx-quotes': [2, 'prefer-single'],
    'import/default': 0, // TODO: enable once module.exports is supported
    'import/extensions': 2,
    'import/first': 2,
    'import/newline-after-import': 2,
    'import/no-absolute-path': 2,
    'import/no-anonymous-default-export': 0, // TODO: we are discussing this rule's options
    'import/no-deprecated': 1, // NOTE: this rule is still in WIP stage
    'import/no-duplicates': 2,
    'import/no-dynamic-require': 2,
    'import/no-extraneous-dependencies': 2,
    'import/no-internal-modules': 0, // NOTE: Brigade uses a mono-repo + Lerna which curently does not play nice with this rule
    'import/no-mutable-exports': 2,
    'import/no-named-as-default-member': 2,
    'import/no-named-as-default': 2,
    'import/no-named-default': 2,
    'import/no-namespace': 2,
    'import/no-unassigned-import': 1, // NOTE: sometimes we do global polyfills - we'd like to make this a 2 eventually...
    'import/no-webpack-loader-syntax': 2,
    'import/order': [
      2,
      {
        groups: [
          'builtin',
          'external',
          'internal',
          ['index', 'sibling', 'parent'],
        ],
      },
    ],
    'import/prefer-default-export': 2,
    'import/unambiguous': 0, // NOTE: needed until we fully adopt import/export over modules.export
    'object-curly-spacing': [1, 'always'],
    'key-spacing': 0,
    'keyword-spacing': 2,
    'max-len': [2, { code: 100, ignoreComments: true, ignoreUrls: true }],
    'max-nested-callbacks': 0,
    'max-params': [1, 4],
    'new-cap': [2, { newIsCap: true, capIsNew: false }],
    'new-parens': 2,
    'no-alert': 2,
    'no-array-constructor': 2,
    'no-await-in-loop': 2,
    'no-bitwise': 2,
    'no-caller': 2,
    'no-catch-shadow': 0, // NOTE: Off because we don't support IE8 and older
    'no-compare-neg-zero': 2,
    'no-cond-assign': 2,
    'no-confusing-arrow': [2,  { allowParens: true }],
    'no-constant-condition': 2,
    'no-control-regex': 2,
    'no-debugger': 2,
    'no-dupe-args': 2,
    'no-dupe-keys': 2,
    'no-duplicate-case': 2,
    'no-duplicate-imports': 2,
    'no-eq-null': 2,
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-floating-decimal': 2,
    'no-func-assign': 2,
    'no-implied-eval': 2,
    'no-iterator': 2,
    'no-label-var': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-lonely-if': 2,
    'no-loop-func': 0,
    'no-multi-spaces': 0,
    'no-multi-str': 2,
    'no-multiple-empty-lines': 2,
    'no-nested-ternary': 2,
    'no-new': 2,
    'no-new-func': 2,
    'no-new-object': 2,
    'no-new-wrappers': 2,
    'no-octal-escape': 2,
    'no-process-exit': 2,
    'no-proto': 2,
    'no-restricted-globals': [2, 'event'],
    'no-return-assign': 0,
    'no-return-await': 2,
    'no-script-url': 2,
    'no-self-compare': 2,
    'no-sequences': 2,
    'no-shadow': 2,
    'no-shadow-restricted-names': 2,
    'no-throw-literal': 2,
    'no-trailing-spaces': 2,
    'no-undef-init': 2,
    'no-underscore-dangle': 0,
    'no-unsafe-negation': 2,
    'no-unused-expressions': 2,
    'no-use-before-define': 2,
    'no-var': 2,
    'no-void': 2,
    'no-with': 2,
    'object-shorthand': [2, 'always'],
    'operator-assignment': [2, 'always'],
    'operator-linebreak': [2, 'after'],
    'padded-blocks': [2, 'never'],
    'padding-line-between-statements': 0,
    'prefer-const': 2,
    'quotes': [2, 'single', 'avoid-escape'],
    'radix': 2,
    'semi': [2, 'always'],
    'semi-spacing': [2, { before: false, after: true }],
    'semi-style': 2,
    'space-before-blocks': [2, 'always'],
    'space-before-function-paren': [
      2,
      {
        anonymous: 'never',
        named: 'never',
        asyncArrow: 'always',
      },
    ],
    'space-in-parens': [2, 'never'],
    'space-infix-ops': 2,
    'space-unary-ops': 2,
    'spaced-comment': [2, 'always'],
    'strict': [2, 'never'],
    'switch-colon-spacing': 2,
    'valid-jsdoc': [
      2,
      {
        prefer: { returns: 'return' },
        requireParamDescription: false,
        requireReturn: false,
      },
    ],
    'wrap-iife': [2, 'outside'],
    'yoda': 2,
  },
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/**
 * Print in console all the methods detected for the passed route
 */
var getRouteMethods = function (route, options) {
  options = options || {};

  for (var method in route.methods) {
    if (!options.withAll && method === '_all') continue;

    console.log(options.prefix + route.path + ' - ' + method.toUpperCase());
  }
};

/**
 * Return an array if strings with all the detected endpoints
 */
var getEndpoints = function (routerStack, path, endpoints) {
  var regExp = /^\/\^\\\/(?:(\w*)|(\(\?:\(\[\^\\\/\]\+\?\)\)))\\\/.*/;

  endpoints = endpoints || [];
  path = path || '';

  routerStack.forEach(function (val) {
    var newPath = regExp.exec(val.regexp);

  	if (val.route) {
      endpoints.push(path + val.route.path);
      // getRouteMethods(val.route, {prefix: path});

  	} else if (val.name === 'router' || val.name === 'bound dispatch') {
      if (newPath) {
        getEndpoints(val.handle.stack, path + '/' + newPath[1], endpoints);

      } else {
        getEndpoints(val.handle.stack, path, endpoints);
      }
    }
  });

  return endpoints;
};

/**
 * Puts middleware to set 501 error for not used methods
 */
var implHandler = function (router) {
  var endpoints = getEndpoints(router.stack);

  endpoints.map(function (val) {
    router.all(val, function (req, res, next) {
      var err = new Error('Not implemented');

      err.status = 501;
      next(err);
    });
  });
};

module.exports = implHandler;
<commit_msg>Detects if the passed arg is a router or an app<commit_after>var express = require('express');
var router = express.Router();

/**
 * Print in console all the methods detected for the passed route
 */
var getRouteMethods = function (route, options) {
  options = options || {};

  for (var method in route.methods) {
    if (!options.withAll && method === '_all') continue;

    console.log(options.prefix + route.path + ' - ' + method.toUpperCase());
  }
};

/**
 * Return an array if strings with all the detected endpoints
 */
var getEndpoints = function (routerStack, path, endpoints) {
  var regExp = /^\/\^\\\/(?:(\w*)|(\(\?:\(\[\^\\\/\]\+\?\)\)))\\\/.*/;

  endpoints = endpoints || [];
  path = path || '';

  routerStack.forEach(function (val) {
    var newPath = regExp.exec(val.regexp);

  	if (val.route) {
      endpoints.push(path + val.route.path);
      // getRouteMethods(val.route, {prefix: path});

  	} else if (val.name === 'router' || val.name === 'bound dispatch') {
      if (newPath) {
        getEndpoints(val.handle.stack, path + '/' + newPath[1], endpoints);

      } else {
        getEndpoints(val.handle.stack, path, endpoints);
      }
    }
  });

  return endpoints;
};

/**
 * Puts middleware to set 501 error for not used methods
 */
var implHandler = function (router) {
  var endpoints = [];

  router = router || {};

  if (router.tack) {
    endpoints = getEndpoints(router.stack);
  } else if (router._router) {
    endpoints = getEndpoints(router._router.stack);
  }

  endpoints.map(function (val) {
    router.all(val, function (req, res, next) {
      var err = new Error('Not implemented');

      err.status = 501;
      next(err);
    });
  });
};

module.exports = implHandler;
<|endoftext|>


<commit_before>var express = require('express'),
    mongoose = require('mongoose');
var port = process.env.PORT || 3030;
var env = process.env.NODE_ENV || 'development';
var app = express();

var config = require('./server/config/config')
require('./server/config/express')(app,config);
mongoose.connect('mongodb://localhost/telerikdb');

var db = mongoose.connection;

db.once('once',function(err){

    if(err){
        console.log('Database error:'+err);
        return;
    }
    console.log('database is up and running!')
});

db.on('error',function(err){
    console.log(err);
});

app.get('/partials/:folder/:partialName',function(req,res){

    res.render('../../public/app/'+req.params.folder+'/'+req.params.partialName)
});

app.get('*',function(req,res){

    res.render('index');
});

app.listen(port);
console.log('server running on port'+port);<commit_msg>Last Working state<commit_after>var express = require('express'),
    stylus = require('stylus'),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose');
var port = process.env.PORT || 3030;
var env = process.env.NODE_ENV || 'development';
var app = express();

var config = require('./server/config/config')
require('./server/config/express')(app,config);
mongoose.connect('mongodb://localhost/telerikdb');

var db = mongoose.connection;

db.once('once',function(err){

    if(err){
        console.log('Database error:'+err);
        return;
    }
    console.log('database is up and running!')
});

db.on('error',function(err){
    console.log(err);
});
app.set('view engine','jade');
app.set('views',__dirname+'/server/views');
app.use(stylus.middleware(
    {
        src:__dirname+'/public',
        compile:function(str,path){
            return stylus(str).set('filename',path);
        }
    }
));

app.use(express.static(__dirname+'/public'));

app.get('/partials/:folder/:partialName',function(req,res){

    res.render('../../public/app/'+req.params.folder+'/'+req.params.partialName)
});

app.get('*',function(req,res){

    res.render('index');
});

app.listen(port);
console.log('server running on port'+port);<|endoftext|>


<commit_before>var ejs = require("ejs");
var fs = require("fs");
var path = require("path");

var template = ejs.compile(fs.readFileSync(path.join(__dirname,"template.ejs"),"utf-8"));

module.exports = function (options) {
    return function (options) {
        var snippet = template(options).replace("\n","").replace(/\s+/g," ");
        return function (req,res,next) {
            req.locals.piwik = function () {
                return snippet;
            }
        };
    }(options);
};
<commit_msg>Fixed templating engine name<commit_after>var ejs = require("ejs");
var fs = require("fs");
var path = require("path");

var template = ejs.compile(fs.readFileSync(path.join(__dirname,"template.ejs"),"utf-8"));

module.exports = function (options) {
    return function (options) {
        var snippet = template(options).replace("\n","").replace(/\s+/g," ");
        return function (req,res,next) {
            res.locals.piwik = function () {
                return snippet;
            }
            next()
        };
    }(options);
};
<|endoftext|>


<commit_before>const fs = require('graceful-fs');
const request = require('request');
const path = require('path');

const DEFAULT_OPTIONS = {
  apiKey: null,
  appVersion: null,
  codeBundleId: null,
  minifiedUrl: null,
  sourceMap: null,
  minifiedFile: null,
  overwrite: false,
  sources: {},
  endpoint: 'https://upload.bugsnag.com',
  uploadSources: false,
  uploadNodeModules: false,
  projectRoot: '.',
  stripProjectRoot: true,
  addWildcardPrefix: false,
};

/**
 * Combines the default options with the user provided ones.
 *
 * @param {object} options The user provided options
 * @returns {object} The combined options
 */
function applyDefaults(options) {
  return Object.assign({}, DEFAULT_OPTIONS, options);
}

/**
 * Checks that the any required options are present and are not malformed. Some options also
 * depend on each other in order to function correctly. Throws an error when there's a voilation.
 *
 * @param {object} options The options
 * @returns {object}
 */
function validateOptions(options) {
  if (typeof options.apiKey !== 'string') {
    throw new Error('You must provide a valid API key to upload sourcemaps to Bugsnag.');
  }
  if (options.addWildcardPrefix && !options.stripProjectRoot) {
    options.stripProjectRoot = true;
  }
  if (options.uploadSources && !options.projectRoot) {
    throw new Error('You must provide a project root when uploading sources. ' +
      'The project root is used to generate relative paths to the sources.');
  }
  if (options.stripProjectRoot && !options.projectRoot) {
    throw new Error('You must provide a project root when stripping the root ' +
      'path from the source map.');
  }
  if (options.projectRoot && !path.isAbsolute(options.projectRoot)) {
    options.projectRoot = path.resolve(options.projectRoot);
  }
  return options;
}

/**
 * Strips the project root from the file path.
 *
 * @param {string} projectRoot The project root path
 * @param {string} filePath The file path
 * @returns {string}
 */
function stripProjectRoot(projectRoot, filePath) {
  if (typeof filePath === 'string') {
    // Check whether the path is an posix absolute file, otherwise check whether it's a
    // win32 valid absolute file. The order is important here because win32 treats posix
    // absolute paths as absolute, but posix doesn't do the same for win32.
    const p = path.posix.isAbsolute(filePath) ? path.posix
            : path.win32.isAbsolute(filePath) ? path.win32
            : null;
    if (p) {
      const relative = p.relative(projectRoot, filePath);
      if (relative.indexOf('.') !== 0) {
        return relative;
      }
    }
  }
  return filePath;
}

/**
 * Reads a file and parses the content a JSON.
 *
 * If the file could not be read (because it doesn't exist) or it is not valid JSON, the
 * promise is rejected - both cases with the Error object.
 *
 * @param {string} path The path to the file
 * @returns {Promise<object>} The JSON contents of the file
 */
function readFileJSON(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, data) => {
      if (err) {
        reject(err);
        return;
      }
      try {
        const json = JSON.parse(String(data));
        resolve(json);
      } catch (err) {
        reject(err);
      }
    });
  });
}

/**
 * Checks whether a file exists (async Promise version of fs.existsStat).
 *
 * @param {string} path The file path
 * @returns {Promise<boolean>}
 */
function doesFileExist(path) {
  return new Promise(resolve => {
    fs.stat(path, (err, stat) => {
      // The file exists if there were no errors, and it's a file
      resolve(!err && stat.isFile());
    });
  });
}

/**
 * Replaces (maps over) the source paths from the source map.
 *
 * @param {object} sourceMap The source map contents
 * @param {function} mapCallback Map the values of the source paths
 */
function mapSources(sourceMap, mapCallback) {
  let chain = Promise.resolve();
  function pushChain(path, index, arr) {
    chain = chain
      .then(() => mapCallback(path))
      .then(replacement => {
        arr[index] = replacement || path;
      });
  }
  if (sourceMap.sources) {
    sourceMap.sources.forEach(pushChain);
  }
  if (sourceMap.sections) {
    sourceMap.sections.forEach(section => {
      if (section.map && section.map.sources) {
        section.map.sources.forEach(pushChain);
      }
    });
  }
  return chain.then(() => sourceMap);
}

/**
 * Extracts the source file paths from the specified source map file, and adds them to
 * the "sources" option, so they are uploaded too.
 *
 * Note: The "projectRoot" option is used to create relative paths to the sources.
 *
 * @param {object} options The options
 * @returns {Promise<object>}
 */
function transformSourcesMap(options) {
  return (
    readFileJSON(options.sourceMap)
      .then(sourceMap => (
        mapSources(sourceMap, path => {
          const relativePath = stripProjectRoot(options.projectRoot, path);
          return doesFileExist(path).then(exists => {
            if (exists && options.uploadSources) {
              if (path.indexOf("node_modules") != -1) {
                if (options.uploadNodeModules) {
                  options.sources[relativePath] = path;
                }
              } else {
                options.sources[relativePath] = path;
              }
            }
            return relativePath;
          });
        })
      ))
      .then(sourceMap => {
        // Replace the sourceMap option with a buffer of the modified sourcemap.
        const tempMap = path.join(options.tempDir, path.basename(options.sourceMap));
        fs.writeFileSync(tempMap, JSON.stringify(sourceMap)); // FIXME find out why passing a Buffer instead of a fs.ReadStream throws "maxFieldsSize 2097152 exceeded"
        options.sourceMap = tempMap;
        return options;
      })
      .catch(err => {
        throw new Error(`Source map file could not be read (doesn't exist or isn't valid JSON).`);
      })
  );
}

/**
 * Does any last-minute transformations to the options before preparing the request.
 *
 * 1) Removes the "appVersion" option if the "codeBundleId" is set.
 * 2) Extracts the source paths from the source map and adds them to the "sources" option.
 *
 * @param {object} options The options
 * @returns {Promise<object>|object}
 */
function transformOptions(options) {
  if (options.codeBundleId && options.appVersion) {
    delete options.appVersion;
  }
  if (options.addWildcardPrefix && options.minifiedUrl) {
    if (options.minifiedUrl.indexOf('://') == -1 && options.minifiedUrl[0] != '*')
      options.minifiedUrl = '*/' + options.minifiedUrl;
  }
  if (options.stripProjectRoot) {
    options.tempDir = fs.mkdtempSync('bugsnag-sourcemaps');
    return transformSourcesMap(options);
  }
  return options;
}

/**
 * Returns a fs.ReadStream or a Buffer, depending on whether the "path" argument is a
 * valid file path or whether it's a Buffer object (used for sourceMap when uploadSources
 * is set to `true`, because the sourcemap is modified).
 *
 * @param {string|Buffer} path The path of the file, or the file Buffer
 * @returns {fs.ReadStream|Buffer}
 */
function createReadStream(path) {
  if (typeof path === 'string') {
    return fs.createReadStream(path);
  }
  else if (Buffer.isBuffer(path)) {
    return path;
  }
  else {
    throw new Error(`Unknown read stream path of type "${typeof path}"`);
  }
}

/**
 * Constructs the request's form data.
 *
 * Mainly, file read streams are created for the source map, minified file and the sources.
 * Any unknown options are simply added to the form data, to allow for any future options.
 *
 * Some options are omitted from the form data, as they are only used as configuration.
 * E.g. "endpoint", "uploadSources", and "projectRoot".
 *
 * Note: Form data fields need to be either strings or streams. Booleans are stringified.
 *
 * @param {object} options The options
 * @returns {{options: object, formData: object}}
 */
function prepareRequest(options) {
  const formData = {};
  Object.keys(options).forEach(function(name) {
    const value = options[name];
    // Skip option if values are null/undefined
    if (value === null || typeof value === 'undefined') {
      return;
    }
    switch(name) {
      // Single file/buffer stream fields
      case 'sourceMap':
      case 'minifiedFile': {
        formData[name] = createReadStream(value);
        break;
      }
      // All additional file streams field
      case 'sources': {
        Object.keys(value).forEach(function (sourceUrl) {
          const sourcePath = value[sourceUrl];
          const key = options.addWildcardPrefix ? '*/' + sourceUrl : sourceUrl;
          formData[key] = createReadStream(sourcePath);
        });
        break;
      }
      // Ignored settings (omit from formData)
      case 'endpoint':
      case 'uploadSources':
      case 'uploadNodeModules':
      case 'projectRoot':
      case 'stripProjectRoot':
      case 'addWildcardPrefix':
      case 'tempDir': {
        break;
      }
      // Basic fields (strings/booleans) & future fields
      default: {
        formData[name] = String(value);
        break;
      }
    }
  });
  return {
    options,
    formData,
  };
}

/**
 * Posts the form data to the endpoint.
 *
 * If the endpoint returns a status code other than 200, the promise is rejected.
 *
 * @param {{options: object, formData: object}}
 * @returns {Promise<string>}
 */
function sendRequest({ options, formData }) {
  return new Promise((resolve, reject) => {
    request.post({
      url: options.endpoint,
      formData,
    }, function (err, res, body) {
      if (err || res.statusCode !== 200) {
        reject(err || new Error(`${res.statusMessage} (${res.statusCode}) - ${body}`));
      } else {
        resolve(options);
      }
    });
  });
}

/**
 * Removes temporary files generated by the upload process.
 *
 * @param {object} options The options
 * @returns {Promise<object>}
 */
function cleanupTempFiles(options) {
  return new Promise((resolve, reject) => {
    if (options.tempDir && path.dirname(options.sourceMap) === options.tempDir) {
      fs.unlinkSync(options.sourceMap);
      fs.rmdir(options.tempDir, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        };
      });
    } else {
      resolve();
    }
  });
}

/**
 * Upload source map to Bugsnag.
 *
 * @param {object} options The options
 * @param {function} [callback] The node-style callback (optional)
 * @returns {Promise<string>}
 */
function upload(options, callback) {
  const promise = (
    Promise.resolve(options)
      .then(applyDefaults)
      .then(validateOptions)
      .then(transformOptions)
      .then(opts => options = opts)
      .then(prepareRequest)
      .then(sendRequest)
      .catch(err => {
        return cleanupTempFiles(options)
          .then(() => Promise.reject(err));
      })
      .then(cleanupTempFiles)
  );
  if (callback) {
    promise
      .then(message => callback(null, message))
      .catch(err => callback(err, null));
  }
  return promise;
}

exports.upload = upload;

if (process.env.NODE_ENV === 'test') {
  Object.assign(exports, {
    applyDefaults,
    validateOptions,
    stripProjectRoot,
    readFileJSON,
    doesFileExist,
    mapSources,
    transformSourcesMap,
    transformOptions,
    createReadStream,
    prepareRequest,
    sendRequest,
    cleanupTempFiles,
    upload,
  });
}
<commit_msg>Improve wildcard support<commit_after>const fs = require('graceful-fs');
const request = require('request');
const path = require('path');

const DEFAULT_OPTIONS = {
  apiKey: null,
  appVersion: null,
  codeBundleId: null,
  minifiedUrl: null,
  sourceMap: null,
  minifiedFile: null,
  overwrite: false,
  sources: {},
  endpoint: 'https://upload.bugsnag.com',
  uploadSources: false,
  uploadNodeModules: false,
  projectRoot: '.',
  stripProjectRoot: true,
  addWildcardPrefix: false,
};

/**
 * Combines the default options with the user provided ones.
 *
 * @param {object} options The user provided options
 * @returns {object} The combined options
 */
function applyDefaults(options) {
  return Object.assign({}, DEFAULT_OPTIONS, options);
}

/**
 * Checks that the any required options are present and are not malformed. Some options also
 * depend on each other in order to function correctly. Throws an error when there's a voilation.
 *
 * @param {object} options The options
 * @returns {object}
 */
function validateOptions(options) {
  if (typeof options.apiKey !== 'string') {
    throw new Error('You must provide a valid API key to upload sourcemaps to Bugsnag.');
  }
  if (options.addWildcardPrefix && !options.stripProjectRoot) {
    options.stripProjectRoot = true;
  }
  if (options.uploadSources && !options.projectRoot) {
    throw new Error('You must provide a project root when uploading sources. ' +
      'The project root is used to generate relative paths to the sources.');
  }
  if (options.stripProjectRoot && !options.projectRoot) {
    throw new Error('You must provide a project root when stripping the root ' +
      'path from the source map.');
  }
  if (options.projectRoot && !path.isAbsolute(options.projectRoot)) {
    options.projectRoot = path.resolve(options.projectRoot);
  }
  return options;
}

/**
 * Strips the project root from the file path.
 *
 * @param {string} projectRoot The project root path
 * @param {string} filePath The file path
 * @returns {string}
 */
function stripProjectRoot(projectRoot, filePath) {
  if (typeof filePath === 'string') {
    // Check whether the path is an posix absolute file, otherwise check whether it's a
    // win32 valid absolute file. The order is important here because win32 treats posix
    // absolute paths as absolute, but posix doesn't do the same for win32.
    const p = path.posix.isAbsolute(filePath) ? path.posix
            : path.win32.isAbsolute(filePath) ? path.win32
            : null;
    if (p) {
      const relative = p.relative(projectRoot, filePath);
      if (relative.indexOf('.') !== 0) {
        return relative;
      }
    }
  }
  return filePath;
}

/**
 * Reads a file and parses the content a JSON.
 *
 * If the file could not be read (because it doesn't exist) or it is not valid JSON, the
 * promise is rejected - both cases with the Error object.
 *
 * @param {string} path The path to the file
 * @returns {Promise<object>} The JSON contents of the file
 */
function readFileJSON(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, data) => {
      if (err) {
        reject(err);
        return;
      }
      try {
        const json = JSON.parse(String(data));
        resolve(json);
      } catch (err) {
        reject(err);
      }
    });
  });
}

/**
 * Checks whether a file exists (async Promise version of fs.existsStat).
 *
 * @param {string} path The file path
 * @returns {Promise<boolean>}
 */
function doesFileExist(path) {
  return new Promise(resolve => {
    fs.stat(path, (err, stat) => {
      // The file exists if there were no errors, and it's a file
      resolve(!err && stat.isFile());
    });
  });
}

/**
 * Replaces (maps over) the source paths from the source map.
 *
 * @param {object} sourceMap The source map contents
 * @param {function} mapCallback Map the values of the source paths
 */
function mapSources(sourceMap, mapCallback) {
  let chain = Promise.resolve();
  function pushChain(path, index, arr) {
    chain = chain
      .then(() => mapCallback(path))
      .then(replacement => {
        arr[index] = replacement || path;
      });
  }
  if (sourceMap.sources) {
    sourceMap.sources.forEach(pushChain);
  }
  if (sourceMap.sections) {
    sourceMap.sections.forEach(section => {
      if (section.map && section.map.sources) {
        section.map.sources.forEach(pushChain);
      }
    });
  }
  return chain.then(() => sourceMap);
}

/**
 * Extracts the source file paths from the specified source map file, and adds them to
 * the "sources" option, so they are uploaded too.
 *
 * Note: The "projectRoot" option is used to create relative paths to the sources.
 *
 * @param {object} options The options
 * @returns {Promise<object>}
 */
function transformSourcesMap(options) {
  return (
    readFileJSON(options.sourceMap)
      .then(sourceMap => (
        mapSources(sourceMap, path => {
          const relativePath = stripProjectRoot(options.projectRoot, path);
          return doesFileExist(path).then(exists => {
            if (exists && options.uploadSources) {
              if (path.indexOf("node_modules") != -1) {
                if (options.uploadNodeModules) {
                  options.sources[relativePath] = path;
                }
              } else {
                options.sources[relativePath] = path;
              }
            }
            return relativePath;
          });
        })
      ))
      .then(sourceMap => {
        // Replace the sourceMap option with a buffer of the modified sourcemap.
        const tempMap = path.join(options.tempDir, path.basename(options.sourceMap));
        fs.writeFileSync(tempMap, JSON.stringify(sourceMap)); // FIXME find out why passing a Buffer instead of a fs.ReadStream throws "maxFieldsSize 2097152 exceeded"
        options.sourceMap = tempMap;
        return options;
      })
      .catch(err => {
        throw new Error(`Source map file could not be read (doesn't exist or isn't valid JSON).`);
      })
  );
}

/**
 * Does any last-minute transformations to the options before preparing the request.
 *
 * 1) Removes the "appVersion" option if the "codeBundleId" is set.
 * 2) Extracts the source paths from the source map and adds them to the "sources" option.
 *
 * @param {object} options The options
 * @returns {Promise<object>|object}
 */
function transformOptions(options) {
  if (options.codeBundleId && options.appVersion) {
    delete options.appVersion;
  }
  if (options.addWildcardPrefix && options.minifiedUrl) {
    if (options.minifiedUrl.indexOf('://') == -1 && options.minifiedUrl[0] != '*')
      options.minifiedUrl = '*' + options.minifiedUrl;
  }
  if (options.stripProjectRoot) {
    options.tempDir = fs.mkdtempSync('bugsnag-sourcemaps');
    return transformSourcesMap(options);
  }
  return options;
}

/**
 * Returns a fs.ReadStream or a Buffer, depending on whether the "path" argument is a
 * valid file path or whether it's a Buffer object (used for sourceMap when uploadSources
 * is set to `true`, because the sourcemap is modified).
 *
 * @param {string|Buffer} path The path of the file, or the file Buffer
 * @returns {fs.ReadStream|Buffer}
 */
function createReadStream(path) {
  if (typeof path === 'string') {
    return fs.createReadStream(path);
  }
  else if (Buffer.isBuffer(path)) {
    return path;
  }
  else {
    throw new Error(`Unknown read stream path of type "${typeof path}"`);
  }
}

/**
 * Constructs the request's form data.
 *
 * Mainly, file read streams are created for the source map, minified file and the sources.
 * Any unknown options are simply added to the form data, to allow for any future options.
 *
 * Some options are omitted from the form data, as they are only used as configuration.
 * E.g. "endpoint", "uploadSources", and "projectRoot".
 *
 * Note: Form data fields need to be either strings or streams. Booleans are stringified.
 *
 * @param {object} options The options
 * @returns {{options: object, formData: object}}
 */
function prepareRequest(options) {
  const formData = {};
  Object.keys(options).forEach(function(name) {
    const value = options[name];
    // Skip option if values are null/undefined
    if (value === null || typeof value === 'undefined') {
      return;
    }
    switch(name) {
      // Single file/buffer stream fields
      case 'sourceMap':
      case 'minifiedFile': {
        formData[name] = createReadStream(value);
        break;
      }
      // All additional file streams field
      case 'sources': {
        Object.keys(value).forEach(function (sourceUrl) {
          const sourcePath = value[sourceUrl];
          const key = options.addWildcardPrefix ? '*' + sourceUrl : sourceUrl;
          formData[key] = createReadStream(sourcePath);
        });
        break;
      }
      // Ignored settings (omit from formData)
      case 'endpoint':
      case 'uploadSources':
      case 'uploadNodeModules':
      case 'projectRoot':
      case 'stripProjectRoot':
      case 'addWildcardPrefix':
      case 'tempDir': {
        break;
      }
      // Basic fields (strings/booleans) & future fields
      default: {
        formData[name] = String(value);
        break;
      }
    }
  });
  return {
    options,
    formData,
  };
}

/**
 * Posts the form data to the endpoint.
 *
 * If the endpoint returns a status code other than 200, the promise is rejected.
 *
 * @param {{options: object, formData: object}}
 * @returns {Promise<string>}
 */
function sendRequest({ options, formData }) {
  return new Promise((resolve, reject) => {
    request.post({
      url: options.endpoint,
      formData,
    }, function (err, res, body) {
      if (err || res.statusCode !== 200) {
        reject(err || new Error(`${res.statusMessage} (${res.statusCode}) - ${body}`));
      } else {
        resolve(options);
      }
    });
  });
}

/**
 * Removes temporary files generated by the upload process.
 *
 * @param {object} options The options
 * @returns {Promise<object>}
 */
function cleanupTempFiles(options) {
  return new Promise((resolve, reject) => {
    if (options.tempDir && path.dirname(options.sourceMap) === options.tempDir) {
      fs.unlinkSync(options.sourceMap);
      fs.rmdir(options.tempDir, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        };
      });
    } else {
      resolve();
    }
  });
}

/**
 * Upload source map to Bugsnag.
 *
 * @param {object} options The options
 * @param {function} [callback] The node-style callback (optional)
 * @returns {Promise<string>}
 */
function upload(options, callback) {
  const promise = (
    Promise.resolve(options)
      .then(applyDefaults)
      .then(validateOptions)
      .then(transformOptions)
      .then(opts => options = opts)
      .then(prepareRequest)
      .then(sendRequest)
      .catch(err => {
        return cleanupTempFiles(options)
          .then(() => Promise.reject(err));
      })
      .then(cleanupTempFiles)
  );
  if (callback) {
    promise
      .then(message => callback(null, message))
      .catch(err => callback(err, null));
  }
  return promise;
}

exports.upload = upload;

if (process.env.NODE_ENV === 'test') {
  Object.assign(exports, {
    applyDefaults,
    validateOptions,
    stripProjectRoot,
    readFileJSON,
    doesFileExist,
    mapSources,
    transformSourcesMap,
    transformOptions,
    createReadStream,
    prepareRequest,
    sendRequest,
    cleanupTempFiles,
    upload,
  });
}
<|endoftext|>


<commit_before>
import express from 'express';
import path from 'path';
import webRoutes from './routes/web';
import apiRoutes from './routes/api';

let app = express();

app.set('view engine', 'jade')
app.set('views', path.join(__dirname, 'views'))

app.use('/', express.static(__dirname + '/public'))
app.use(webRoutes)
app.use(apiRoutes)

app.listen('3000');
<commit_msg>changed port to 3001<commit_after>
import express from 'express';
import path from 'path';
import webRoutes from './routes/web';
import apiRoutes from './routes/api';

let app = express();

app.set('view engine', 'jade')
app.set('views', path.join(__dirname, 'views'))

app.use('/', express.static(__dirname + '/public'))
app.use(webRoutes)
app.use(apiRoutes)

app.listen('3001');
<|endoftext|>


<commit_before>let options;

const toggleResultHighlighting = (link) => {
  link.classList.toggle('highlighted-search-result')
};

const loadOptions = () => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get(
        {
          wrapNavigation: false,
          autoSelectFirst: true,
          nextKey: 'down, j',
          previousKey: 'up, k',
          navigatePreviousResultPage: 'left, h',
          navigateNextResultPage: 'right, l',
          navigateKey: 'return, space',
          navigateNewTabKey: 'ctrl+return, command+return, ctrl+space',
          navigateSearchTab: 'a, s',
          navigateImagesTab: 'i',
          navigateVideosTab: 'v',
          navigateMapsTab: 'm',
          navigateNewsTab: 'n',
          focusSearchInput: '/, escape'
        },
        (items) => {
          options = items;
          if (chrome.runtime.lastError) {
            reject();
          } else {
            resolve();
          }
        });
  });
};

const getNextIndex = (currentIndex, numResults, shouldWrap) => {
  if (currentIndex < numResults - 1) {
    return currentIndex + 1;
  }
  if (!shouldWrap) {
    return currentIndex;
  }
  return 0;
};

const getPreviousIndex = (currentIndex, numResults, shouldWrap) => {
  if (currentIndex > 0) {
    return currentIndex - 1;
  }
  if (!shouldWrap) {
    return currentIndex;
  }
  return numResults - 1;
};

const initResultsNavigation = (results) => {
  let isFirstNavigation = true;
  let resultIndex = 0;
  const updateHighlightedResult = (newResultIndex) => {
    if (results.length > 0) {
      results[resultIndex].classList.remove('highlighted-search-result')
      resultIndex = newResultIndex;
      results[resultIndex].classList.add('highlighted-search-result')
      results[resultIndex].focus();
    }
  };
  if (options.autoSelectFirst) {
    // Highlight the first result when the page is loaded.
    updateHighlightedResult(0);
  }
  key(options.nextKey, (event) => {
    let nextIndex =
        getNextIndex(resultIndex, results.length, options.wrapNavigation);
    if (!options.autoSelectFirst && isFirstNavigation) {
      nextIndex = 0;
      isFirstNavigation = false;
    }
    updateHighlightedResult(nextIndex);
    handleEvent(event);
  });
  key(options.previousKey, (event) => {
    let previousIndex =
        getPreviousIndex(resultIndex, results.length, options.wrapNavigation);
    if (!options.autoSelectFirst && isFirstNavigation) {
      previousIndex = 0;
      isFirstNavigation = false;
    }
    updateHighlightedResult(previousIndex);
    handleEvent(event);
  });
  key(options.navigateKey, (event) => {
    let link = results[resultIndex];
    link.click();
    handleEvent(event);
  });
  key(options.navigateNewTabKey, (event) => {
    let link = results[resultIndex];
    window.open(link.href);
    handleEvent(event);
  });
};

const initCommonGoogleSearchNavigation = () => {
  let searchInput = document.getElementById('lst-ib');
  key(options.focusSearchInput, (event) => {
    searchInput.focus();
    searchInput.select();
    handleEvent(event);
  });
  let all = getElementByXpath(
      '//a[contains(@class, \'q qs\') and not (contains(@href, \'&tbm=\')) and not (contains(@href, \'maps.google.\'))]');
  key(options.navigateSearchTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(all, event);
  });
  let images = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'&tbm=isch\'))]');
  key(options.navigateImagesTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(images, event);
  });
  let videos = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'&tbm=vid\'))]');
  key(options.navigateVideosTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(videos, event);
  });
  let maps = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'maps.google.\'))]');
  key(options.navigateMapsTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(maps, event);
  });
  let news = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'&tbm=nws\'))]');
  key(options.navigateNewsTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(news, event);
  });
  let previousResultPage = document.querySelector('#pnprev');
  key(options.navigatePreviousResultPage, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(previousResultPage, event);
  });
  let nextResultPage = document.querySelector('#pnnext');
  key(options.navigateNextResultPage, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(nextResultPage, event);
  });
};

const updateUrlWithNodeHrefAndHandleEvent = (node, event) => {
  if (node !== null) {
    location.href = node.href;
  }
  handleEvent(event);
};

const handleEvent = (event) => {
  if (event !== null) {
    event.stopPropagation();
    event.preventDefault();
  }
};

const getQueryStringParams = () => {
  const encodedQueryString = window.location.search.slice(1);
  const encodedParams = encodedQueryString.split('&');
  let params = {};
  for (const encodedParam of encodedParams) {
    let [key, encodedValue] = encodedParam.split('=');
    if (!encodedValue) {
      encodedValue = '';
    }
    // + (plus sign) is not decoded by decodeURIComponent so we need to decode
    // it manually.
    encodedValue = encodedValue.replace(/\+/g, ' ');
    params[key] = decodeURIComponent(encodedValue);
  }
  return params;
};

const getGoogleSearchLinks = function() {
  let results = Array.prototype.slice.call(document.querySelectorAll('h3.r a'));
  let prevPage = document.querySelector('#pnprev');
  if (prevPage !== null) {
    results.push(prevPage);
  }
  let nextPage = document.querySelector('#pnnext');
  if (nextPage !== null) {
    results.push(nextPage);
  }
  return results;
};

const initGoogleSearch = function() {
  const params = getQueryStringParams();
  // Don't initialize results navigation on image search, since it doesn't work
  // there.
  if (params['tbm'] !== 'isch') {
    // This file is loaded only after the DOM is ready, so no need to wait for
    // DOMContentLoaded.
    loadOptions().then(() => {
      initResultsNavigation(getGoogleSearchLinks());
    });
  }
  loadOptions().then(() => {
    initCommonGoogleSearchNavigation();
  });
};

const initPageIfNeeded = () => {
  if (/^(www|encrypted)\.google\./.test(window.location.hostname)) {
    initGoogleSearch();
  }
};

function getElementByXpath(path) {
  return document
      .evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
      .singleNodeValue;
};

initPageIfNeeded();

<commit_msg>Restore the focused item when using back<commit_after>let options;
let lastNavigation;

const toggleResultHighlighting = (link) => {
  link.classList.toggle('highlighted-search-result')
};

const loadOptions = () => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get(
        {
          wrapNavigation: false,
          autoSelectFirst: true,
          nextKey: 'down, j',
          previousKey: 'up, k',
          navigatePreviousResultPage: 'left, h',
          navigateNextResultPage: 'right, l',
          navigateKey: 'return, space',
          navigateNewTabKey: 'ctrl+return, command+return, ctrl+space',
          navigateSearchTab: 'a, s',
          navigateImagesTab: 'i',
          navigateVideosTab: 'v',
          navigateMapsTab: 'm',
          navigateNewsTab: 'n',
          focusSearchInput: '/, escape'
        },
        (items) => {
          options = items;
          if (chrome.runtime.lastError) {
            reject();
          } else {
            resolve();
          }
        });
  });
};

const loadLastNavigation = () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(
    {
      lastQueryUrl: false,
      lastFocusedIndex: 0
    },
    (items) =>{
      lastNavigation = items;
      if (chrome.runtime.lastError) {
        reject();
      } else {
        resolve();
      }
    });
  });
}

const getNextIndex = (currentIndex, numResults, shouldWrap) => {
  if (currentIndex < numResults - 1) {
    return currentIndex + 1;
  }
  if (!shouldWrap) {
    return currentIndex;
  }
  return 0;
};

const getPreviousIndex = (currentIndex, numResults, shouldWrap) => {
  if (currentIndex > 0) {
    return currentIndex - 1;
  }
  if (!shouldWrap) {
    return currentIndex;
  }
  return numResults - 1;
};

const initResultsNavigation = (results) => {
  let isFirstNavigation = true;
  let resultIndex = 0;
  const updateHighlightedResult = (newResultIndex) => {
    if (results.length > 0) {
      results[resultIndex].classList.remove('highlighted-search-result')
      resultIndex = newResultIndex;
      results[resultIndex].classList.add('highlighted-search-result')
      results[resultIndex].focus();
    }
  };
  if (options.autoSelectFirst) {
    // Highlight the first result when the page is loaded.
    updateHighlightedResult(0);
  }
  loadLastNavigation().then(() => {
    if (location.href === lastNavigation.lastQueryUrl) {
      isFirstNavigation = false;
      updateHighlightedResult(lastNavigation.lastFocusedIndex);
    }
  });
  key(options.nextKey, (event) => {
    let nextIndex =
        getNextIndex(resultIndex, results.length, options.wrapNavigation);
    if (!options.autoSelectFirst && isFirstNavigation) {
      nextIndex = 0;
      isFirstNavigation = false;
    }
    updateHighlightedResult(nextIndex);
    handleEvent(event);
  });
  key(options.previousKey, (event) => {
    let previousIndex =
        getPreviousIndex(resultIndex, results.length, options.wrapNavigation);
    if (!options.autoSelectFirst && isFirstNavigation) {
      previousIndex = 0;
      isFirstNavigation = false;
    }
    updateHighlightedResult(previousIndex);
    handleEvent(event);
  });
  key(options.navigateKey, (event) => {
    let link = results[resultIndex];
    saveLastNavigation();
    handleEvent(event);
  });
  key(options.navigateNewTabKey, (event) => {
    let link = results[resultIndex];
    window.open(link.href);
    handleEvent(event);
  });
};

const initCommonGoogleSearchNavigation = () => {
  let searchInput = document.getElementById('lst-ib');
  key(options.focusSearchInput, (event) => {
    searchInput.focus();
    searchInput.select();
    handleEvent(event);
  });
  let all = getElementByXpath(
      '//a[contains(@class, \'q qs\') and not (contains(@href, \'&tbm=\')) and not (contains(@href, \'maps.google.\'))]');
  key(options.navigateSearchTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(all, event);
  });
  let images = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'&tbm=isch\'))]');
  key(options.navigateImagesTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(images, event);
  });
  let videos = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'&tbm=vid\'))]');
  key(options.navigateVideosTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(videos, event);
  });
  let maps = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'maps.google.\'))]');
  key(options.navigateMapsTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(maps, event);
  });
  let news = getElementByXpath(
      '//a[contains(@class, \'q qs\') and (contains(@href, \'&tbm=nws\'))]');
  key(options.navigateNewsTab, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(news, event);
  });
  let previousResultPage = document.querySelector('#pnprev');
  key(options.navigatePreviousResultPage, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(previousResultPage, event);
  });
  let nextResultPage = document.querySelector('#pnnext');
  key(options.navigateNextResultPage, (event) => {
    updateUrlWithNodeHrefAndHandleEvent(nextResultPage, event);
  });
};

const updateUrlWithNodeHrefAndHandleEvent = (node, event) => {
  if (node !== null) {
    location.href = node.href;
  }
  handleEvent(event);
};

const handleEvent = (event) => {
  if (event !== null) {
    event.stopPropagation();
    event.preventDefault();
  }
};

const getQueryStringParams = () => {
  const encodedQueryString = window.location.search.slice(1);
  const encodedParams = encodedQueryString.split('&');
  let params = {};
  for (const encodedParam of encodedParams) {
    let [key, encodedValue] = encodedParam.split('=');
    if (!encodedValue) {
      encodedValue = '';
    }
    // + (plus sign) is not decoded by decodeURIComponent so we need to decode
    // it manually.
    encodedValue = encodedValue.replace(/\+/g, ' ');
    params[key] = decodeURIComponent(encodedValue);
  }
  return params;
};

const getGoogleSearchLinks = function() {
  let results = Array.prototype.slice.call(document.querySelectorAll('h3.r a'));
  let prevPage = document.querySelector('#pnprev');
  if (prevPage !== null) {
    results.push(prevPage);
  }
  let nextPage = document.querySelector('#pnnext');
  if (nextPage !== null) {
    results.push(nextPage);
  }
  return results;
};

const initGoogleSearch = function() {
  const params = getQueryStringParams();
  // Don't initialize results navigation on image search, since it doesn't work
  // there.
  if (params['tbm'] !== 'isch') {
    // This file is loaded only after the DOM is ready, so no need to wait for
    // DOMContentLoaded.
    loadOptions().then(() => {
      initResultsNavigation(getGoogleSearchLinks());
    });
  }
  loadOptions().then(() => {
    initCommonGoogleSearchNavigation();
  });
};

const initPageIfNeeded = () => {
  if (/^(www|encrypted)\.google\./.test(window.location.hostname)) {
    initGoogleSearch();
  }
};

function getElementByXpath(path) {
  return document
      .evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
      .singleNodeValue;
};

const saveLastNavigation = () => {
  chrome.storage.local.set(
      {
        lastQueryUrl: location.href,
        lastFocusedIndex: resultIndex
      }, null);
    link.click();
}

initPageIfNeeded();

<|endoftext|>


<commit_before>'use strict';
var unirest = require('unirest'),
    config = require('../../config/'),
    fs = require('fs-extra'),
    moConfigFile = require('./mo_app_config_file');

exports.putPackageData = function(name, version, options) {
  if(options == undefined) options = {}

  return moConfigFile.read(options).then((authData) => {
      return new Promise(function(resolve, reject) {
      unirest.put(config.moServer + "/api/packages/" + name + "/" + version)
        .header('Accept', 'application/json')
        .field('s', 'f')
        .attach({'package': '' + name + "-" + version + ".zip"})
        .end(function(response) {
          if(response.body && response.body.error) {
            return reject(response.body.error)
          }

          if(response.status !== 200) {
            return reject(response.body)
          }

          fs.remove('' + name + "-" + version + ".zip", function(err) {
            return resolve(response.body)
          })
        })

      })
    })
}

exports.postPackageData = function(json, options) {
  if(options == undefined) options = {}

  return moConfigFile.read(options).then((authData) => {
    return new Promise(function(resolve, reject) {
      unirest.post(config.moServer + '/api/packages')
        .header('Accept', 'application/json')
        .type('json')
        .send({"data": json})
        .end(function (response) {
          if(response.body && response.body.error) {
            return reject(response.body.error)
          }

          if(response.status !== 200) {
            return reject(response.body)
          }

          return resolve(response.body)
        });
    })
  })
}

exports.deletePackage = function(json, options) {
  if(options == undefined) options = {}

  return moConfigFile.read(options).then((authData) => {
    return new Promise(function(resolve, reject) {
      unirest.delete(config.moServer + '/api/packages/' + json.name)
        .header('Accept', 'application/json')
        .type('json')
        .end(function (response) {
          if(response.error) {
            return reject(response.error.message)
          }

          if(response.status !== 200) {
            return reject(response.body.error)
          }

          return resolve(response.body)
        });
    })
  })
}

exports.authenticate = function(json) {
  return new Promise(function(resolve, reject) {
    unirest.post(config.moServer + '/api/authenticate')
      .header('Accept', 'application/json')
      .type('json')
      .send({"username": json.username, "api_key": json.api_key})
      .end(function (response) {
        if(response.body && response.body.error) {
          return reject(response.body.error)
        }

        if(response.status !== 200) {
          return reject(response.body)
        }

        return resolve(response.body)
      });
  })
}
<commit_msg>fix(cli): adds access token in requirests<commit_after>'use strict';
var unirest = require('unirest'),
    config = require('../../config/'),
    fs = require('fs-extra'),
    moConfigFile = require('./mo_app_config_file');

exports.putPackageData = function(name, version, options) {
  if(options == undefined) options = {}

  return moConfigFile.read(options).then((authData) => {
      return new Promise(function(resolve, reject) {
      unirest.put(config.moServer + "/api/packages/" + name + "/" + version)
        .header('Accept', 'application/json')
        .field('s', 'f')
        .attach({'package': '' + name + "-" + version + ".zip"})
        .send({'token': authData.token})
        .end(function(response) {
          if(response.body && response.body.error) {
            return reject(response.body.error)
          }

          if(response.status !== 200) {
            return reject(response.body)
          }

          fs.remove('' + name + "-" + version + ".zip", function(err) {
            return resolve(response.body)
          })
        })

      })
    })
}

exports.postPackageData = function(json, options) {
  if(options == undefined) options = {}

  return moConfigFile.read(options).then((authData) => {
    return new Promise(function(resolve, reject) {
      unirest.post(config.moServer + '/api/packages')
        .header('Accept', 'application/json')
        .type('json')
        .send({"data": json, token: authData.token})
        .end(function (response) {
          if(response.body && response.body.error) {
            return reject(response.body.error)
          }

          if(response.status !== 200) {
            return reject(response.body)
          }

          return resolve(response.body)
        });
    })
  })
}

exports.deletePackage = function(json, options) {
  if(options == undefined) options = {}

  return moConfigFile.read(options).then((authData) => {
    return new Promise(function(resolve, reject) {
      unirest.delete(config.moServer + '/api/packages/' + json.name)
        .header('Accept', 'application/json')
        .type('json')
        .send({'token': authData.token})
        .end(function (response) {
          if(response.error) {
            return reject(response.error.message)
          }

          if(response.status !== 200) {
            return reject(response.body.error)
          }

          return resolve(response.body)
        });
    })
  })
}

exports.authenticate = function(json) {
  return new Promise(function(resolve, reject) {
    unirest.post(config.moServer + '/api/authenticate')
      .header('Accept', 'application/json')
      .type('json')
      .send({"username": json.username, "api_key": json.api_key})
      .end(function (response) {
        if(response.body && response.body.error) {
          return reject(response.body.error)
        }

        if(response.status !== 200) {
          return reject(response.body)
        }

        return resolve(response.body)
      });
  })
}
<|endoftext|>


<commit_before>var osa = require('osa2')

function play(uri) {
    if (uri)
        return playTrack(uri)
    return osa(() => Application('Spotify').play())()
}

function playTrack(uri) {
    return osa((uri) => Application('Spotify').playTrack(uri))(uri)
}

function pause() {
    return osa(() => Application('Spotify').pause())()
}

function toggle() {
    return osa(() => Application('Spotify').playpause())()
}

function next() {
    return osa(() => Application('Spotify').nextTrack())()
}

function prev() {
    return osa(() => Application('Spotify').previousTrack())()
}

function getCurrentTrack() {
    return osa(() => {
        var track = Application('Spotify').currentTrack
        return {
            id: track.id(),
            name: track.name(),
            album: track.album(),
            artist: track.artist(),
            duration: track.duration(),
            artwork: track.artworkUrl(),
            popularity: track.popularity()
        }
    })()
}

function getPlayerState() {
    return osa(() => {
        var s = Application('Spotify')
        return {
            state: s.playerState(),
            volume: s.soundVolume(),
            position: s.playerPosition(),
            repeating: s.repeating(),
            shuffling: s.shuffling(),
        }
    })()
}

module.exports = {
    play, pause, toggle, next, prev,
    getCurrentTrack, getPlayerState
}
<commit_msg>Add track number and album artist to info<commit_after>var osa = require('osa2')

function play(uri) {
    if (uri)
        return playTrack(uri)
    return osa(() => Application('Spotify').play())()
}

function playTrack(uri) {
    return osa((uri) => Application('Spotify').playTrack(uri))(uri)
}

function pause() {
    return osa(() => Application('Spotify').pause())()
}

function toggle() {
    return osa(() => Application('Spotify').playpause())()
}

function next() {
    return osa(() => Application('Spotify').nextTrack())()
}

function prev() {
    return osa(() => Application('Spotify').previousTrack())()
}

function getCurrentTrack() {
    return osa(() => {
        var track = Application('Spotify').currentTrack
        return {
            id: track.id(),
            name: track.name(),
            album: track.album(),
            artist: track.artist(),
            number: track.trackNumber(),
            duration: track.duration(),
            artwork: track.artworkUrl(),
            popularity: track.popularity(),
            albumArtist: track.albumArtist(),
        }
    })()
}

function getPlayerState() {
    return osa(() => {
        var s = Application('Spotify')
        return {
            state: s.playerState(),
            volume: s.soundVolume(),
            position: s.playerPosition(),
            repeating: s.repeating(),
            shuffling: s.shuffling(),
        }
    })()
}

module.exports = {
    play, pause, toggle, next, prev,
    getCurrentTrack, getPlayerState
}
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var conf = require('./server/conf');
var logger = conf.logger;
var staticResources = require('./server/staticResources');
var accessControl = require('./server/accessControl');

var app = express();

app.use(express.favicon('public/favicon.ico'));
if (conf.env === 'production') {
  app.use(express.logger());
}
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
  secret: conf.settings.SESSION_SECRET,
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: null,
    secure: conf.env === 'production' // force HTTPS
  }
}));
app.use(require('connect-flash')());

app.use(staticResources.anonymousResources(conf.env, express));

app.use(passport.initialize());
app.use(passport.session());

app.use(app.router);

app.use(function errorHandler(err, req, res, next) {
  if (!err) {
    // this shouldn't happen, since all middleware with arity 4 is error middleware, but better safe than sorry
    next();
  } else {
    console.error(err.stack);
    res.status(500);
    res.format({
      html: function () {
        res.render('error.html', {
          error: err
        });
      },
      json: function () {
        res.send({
          error: 'Server error'
        });
      }
    });
  }
});

app.engine('html', require('ejs').renderFile);
app.set('views', require('./server/views')(conf.env));

// see http://redotheweb.com/2013/02/20/sequelize-the-javascript-orm-in-practice.html
var models = require('./server/models');
app.set('models', models);

passport.serializeUser(function (user, done) {
  done(null, user.id);
});
passport.deserializeUser(function (id, done) {
  models.User
    .find(id)
    .error(done)
    .success(function (user) {
      if (user) {
        done(null, user);
      } else {
        done(new Error('Unknown user ' + id));
      }
    });
});

passport.use(new LocalStrategy(function (username, password, done) {
  models.User
    .find({
      where: {
        name: username
      }
    })
    .error(done)
    .success(function (user) {
      if (!user) {
        return done(null, false, {
          // don't display this to the user, that would be an info leak
          message: 'Unknown username ' + username
        });
      }
      user.comparePassword(password, function (err, result) {
        if (err) {
          return done(err);
        }
        if (result) {
          return done(null, user);
        } else {
          return done(null, false, {
            message: 'Incorrect password'
          });
        }
      });
    });
}));

app.get('/', function (req, res) {
  if (req.user) {
    res.redirect(307, '/kibana');
  } else {
    res.render('login.html');
  }
});

app.post('/login', passport.authenticate('local', {
  successRedirect: '/kibana',
  failureRedirect: '/',
  failureFlash: true
}));

// all routes below this require authenticating
app.all('*', accessControl.denyAnonymousAccess);

app.use('/kibana', staticResources.kibana(conf.env, express));

// this MUST be the last route
app.use(function (req, res) {
  console.trace(req.url + ' not found');
  res.status(404);

  res.format({
    html: function () {
      res.render('404.html', {
        url: req.url
      });
    },
    json: function () {
      res.send({
        error: 'Not found'
      });
    }
  });
});

function forkChildren () {
  var childProcess = require('child_process');

  var syncer = childProcess.fork(__dirname + '/server/es/pgsyncer');
  logger.info('Spawned pgsyncer child pid %d', syncer.pid); // so user knows what to kill, if need be

  syncer.on('error', function (err) {
    console.error('Error in pgsync child process');
    console.error(err);
  });
  syncer.on('exit', function () {
    console.error('syncer child process exited');
  });

  if (conf.env === 'production') {
    logger.info('Waiting 10s before starting reindexing');
    setTimeout(function () {
      var reindexer = childProcess.fork(__dirname + '/server/es/reindexer');
      logger.info('Spawned reindexer child pid %d', reindexer.pid);

      reindexer.on('exit', function () {
        logger.info('reindexer exited');

        // install cron job after reindexer is done
        var CronJob = require('cron').CronJob;
        // run every day at 3 AM
        new CronJob('00 00 3 * * *', function () { // TODO test this
          logger.info('Cron job is running reindexer');
          var child = childProcess.fork(__dirname + '/server/es/reindexer');
          logger.info('Spawned reindexer child pid %d', child.pid);
        });
      });
    }, 10000);
  }
}

if (!module.parent) {
  var port = process.env.PORT || 9000;

  app.listen(port, function () {
    // must log to stdout (some 3rd party tools read stdout to know when web server is up)
    console.log('Listening on port ' + port);
  });

  forkChildren();
}
<commit_msg>Don't deserialize sessions from database<commit_after>'use strict';

var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var conf = require('./server/conf');
var logger = conf.logger;
var staticResources = require('./server/staticResources');
var accessControl = require('./server/accessControl');

var app = express();

app.use(express.favicon('public/favicon.ico'));
if (conf.env === 'production') {
  app.use(express.logger());
}
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
  secret: conf.settings.SESSION_SECRET,
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: null,
    secure: conf.env === 'production' // force HTTPS
  }
}));
app.use(require('connect-flash')());

app.use(staticResources.anonymousResources(conf.env, express));

app.use(passport.initialize());
app.use(passport.session());

app.use(app.router);

app.use(function errorHandler(err, req, res, next) {
  if (!err) {
    // this shouldn't happen, since all middleware with arity 4 is error middleware, but better safe than sorry
    next();
  } else {
    console.error(err.stack);
    res.status(500);
    res.format({
      html: function () {
        res.render('error.html', {
          error: err
        });
      },
      json: function () {
        res.send({
          error: 'Server error'
        });
      }
    });
  }
});

app.engine('html', require('ejs').renderFile);
app.set('views', require('./server/views')(conf.env));

// see http://redotheweb.com/2013/02/20/sequelize-the-javascript-orm-in-practice.html
var models = require('./server/models');
app.set('models', models);

passport.serializeUser(function (user, done) {
  // store entire user object in session so we don't have to deserialize it from data store
  // this won't scale to large number of concurrent users, but it will be faster for small deployments
  done(null, user);
});
passport.deserializeUser(function (user, done) {
  done(null, user);
});

passport.use(new LocalStrategy(function (username, password, done) {
  models.User
    .find({
      where: {
        name: username
      }
    })
    .error(done)
    .success(function (user) {
      if (!user) {
        return done(null, false, {
          // don't display this to the user, that would be an info leak
          message: 'Unknown username ' + username
        });
      }
      user.comparePassword(password, function (err, result) {
        if (err) {
          return done(err);
        }
        if (result) {
          return done(null, user);
        } else {
          return done(null, false, {
            message: 'Incorrect password'
          });
        }
      });
    });
}));

app.get('/', function (req, res) {
  if (req.user) {
    res.redirect(307, '/kibana');
  } else {
    res.render('login.html');
  }
});

app.post('/login', passport.authenticate('local', {
  successRedirect: '/kibana',
  failureRedirect: '/',
  failureFlash: true
}));

// all routes below this require authenticating
app.all('*', accessControl.denyAnonymousAccess);

app.use('/kibana', staticResources.kibana(conf.env, express));

// this MUST be the last route
app.use(function (req, res) {
  console.trace(req.url + ' not found');
  res.status(404);

  res.format({
    html: function () {
      res.render('404.html', {
        url: req.url
      });
    },
    json: function () {
      res.send({
        error: 'Not found'
      });
    }
  });
});

function forkChildren () {
  var childProcess = require('child_process');

  var syncer = childProcess.fork(__dirname + '/server/es/pgsyncer');
  logger.info('Spawned pgsyncer child pid %d', syncer.pid); // so user knows what to kill, if need be

  syncer.on('error', function (err) {
    console.error('Error in pgsync child process');
    console.error(err);
  });
  syncer.on('exit', function () {
    console.error('syncer child process exited');
  });

  if (conf.env === 'production') {
    logger.info('Waiting 10s before starting reindexing');
    setTimeout(function () {
      var reindexer = childProcess.fork(__dirname + '/server/es/reindexer');
      logger.info('Spawned reindexer child pid %d', reindexer.pid);

      reindexer.on('exit', function () {
        logger.info('reindexer exited');

        // install cron job after reindexer is done
        var CronJob = require('cron').CronJob;
        // run every day at 3 AM
        new CronJob('00 00 3 * * *', function () { // TODO test this
          logger.info('Cron job is running reindexer');
          var child = childProcess.fork(__dirname + '/server/es/reindexer');
          logger.info('Spawned reindexer child pid %d', child.pid);
        });
      });
    }, 10000);
  }
}

if (!module.parent) {
  var port = process.env.PORT || 9000;

  app.listen(port, function () {
    // must log to stdout (some 3rd party tools read stdout to know when web server is up)
    console.log('Listening on port ' + port);
  });

  forkChildren();
}
<|endoftext|>


<commit_before>export {version} from "./package.json";

export {default as image} from "./src/image";
export {default as rect} from "./src/rect";
<commit_msg>removes version export<commit_after>export {default as image} from "./src/image";
export {default as rect} from "./src/rect";
<|endoftext|>