<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const url = require('url');
const mime = require('mime-types');
const _ = require('lodash');

/**
 * @class Router
 */
class Router {
    /**
     * @constructs
     * @param {Express} app
     * @param {object} options
     * @param {string} options.file
     * @param {string} [options.baseDir=__dirname]
     * @throws Error if parameter app is not defined
     * @throws Error if parameter app is not express() function
     * @throws Error if parameter file is not defined
     */
    constructor() {
        return (app, options) => {
            if (app === undefined) {
                throw new Error(`Could not apply router to undefined application.`);
            } else if (typeof app !== 'function') {
                throw new Error(`Application should to be an express() function.`);
            } else {
                // @member {function} app
                this.app = app;
            }

            if (options.file === undefined) {
                throw new Error(`Route's file have to be specified.`);
            } else {
                // @member {string} file
                this.file = options.file;
            }

            // @member {string} [protocol]
            this.protocol = options.protocol || 'http';

            // @member {string} [host]
            this.host = options.host || '';

            // @member {string} [port]
            this.port = options.port || '';

            // @member {string} [baseDir=__dirname]
            this.baseDir = options.baseDir || __dirname;

            this._start();
        };
    }

    /**
     * @method
     * @private
     */
    _start() {
        this.routeMap = {};
        this._normalizeRoutesMap(this._getRoutesFromFile(this.file));

        for (let name in this.routeMap) {
            this._applyRoute(this.routeMap[name]);
        }

        // URI to output routeMap for developing
        // @todo: hide from production mode
        this.app.get('/_dev/routes/', (req, res) => {
            res.json(this.routeMap);
        });

        this.app.use((req, res) => {
            this.sendNotFaund(req, res);
        });
    }

    /**
     * @method
     * @param {object} routes
     * @param {string} [prefix]
     * @param {object} [defaults]
     * @param {object} [requirements]
     * @returns {Router}
     * @private
     */
    _normalizeRoutesMap(routes, prefix, defaults, requirements) {
        prefix = prefix || '';
        defaults = defaults || {};
        requirements = requirements || {};

        for (let name in routes) {
            let route = routes[name];
            let routeDefaults = _.merge({}, defaults, (route.defaults || {}));
            let routeRequirements = _.merge({}, requirements, (route.requirements || {}));

            if (route.resource !== undefined) {
                this._normalizeRoutesMap(this._getRoutesFromFile(route.resource), (prefix + (route.prefix || '')), routeDefaults, routeRequirements);
            } else {
                Object.assign(this.routeMap[name] = {}, {
                    name: name,
                    path: prefix + route.path,
                    methods: route.methods || ['all'],
                    defaults: routeDefaults,
                    requirements: routeRequirements
                }, route);
            }
        }

        return this;
    }

    /**
     * @method
     * @param {string} file
     * @returns {json}
     * @private
     */
    _getRoutesFromFile(file) {
        return JSON.parse(fs.readFileSync(path.join(this.baseDir, file), 'utf8'));
    }

    /**
     * @method
     * @param {object} route
     * @returns {Router}
     * @private
     */
    _applyRoute(route) {
        let methods = this._getMethods(route);

        methods.forEach((method) => {
            this.app[method](this._getPath(route), (req, res) => {
                if (this._getTemplate(route)) {
                    res.render(this._getTemplate(route), this._getController(route)(req, res, this));
                } else {
                    res.send(this._getController(route)(req, res, this));
                }
            });
        });

        return this;
    }

    /**
     * @const {RegExp}
     */
    get PARAM_PATTERN() {
        return /\{([^}]+)\}/g;
    }

    /**
     * @method
     * @param {object} route
     * @returns {string}
     * @private
     */
    _getPath(route) {
        let result;

        result = route.path.replace(this.PARAM_PATTERN, (match, name) => {
            let pattern = (typeof route.requirements[name] !== 'undefined') ? `(${route.requirements[name]})` : '';

            return `:${name}${pattern}`;
        });

        return result;
    }

    /**
     * @method
     * @param {object} route
     * @returns {array}
     * @private
     */
    _getMethods(route) {
        let result;
        let methods = route.methods || ['all'];

        if (!Array.isArray(methods)) {
            result = [methods];
        } else {
            result = methods;
        }

        result = result.map((method) => {
            return method.toLowerCase();
        });

        return result;
    }

    /**
     * @method
     * @param {object} router
     * @throws Error if controller for route could not be loaded
     * @returns {function}
     * @private
     */
    _getController(route) {
        let result;
        let controller = route.defaults._controller || '';
        let controllerPath = path.join(this.baseDir, controller);

        try {
            result = require(controllerPath);
        } catch (e) {
            throw new Error(`Could not load controller "${controller}" for route "${route.name}".`);
        }

        return result;
    }

    /**
     * @method
     * @param {object} router
     * @returns {string}
     * @private
     */
    _getFormat(route) {
        let result;
        let template = this._getTemplate(route);

        if (route.defaults.hasOwnProperty(_format) && mime.lookup(this.defaults._format)) {
            if (typeof template !== 'undefined') {
                result = route.defaults._format;
            } else {
                throw new Error(`Template for route "${route.name}" is not defined.`)
            }
        } else if (typeof template !== 'undefined') {
            result = 'html';
        } else {
            result = 'json';
        }

        return result;
    }

    /**
     * @method
     * @param {object} router
     * @returns {string}
     * @private
     */
    _getTemplate(route) {
        let result;

        result = route.defaults._template;

        return result;
    }

    /**
     * @method
     * @param {object} req
     * @param {object} res
     * @returns {Router}
     * @public
     */
    sendNotFaund(req, res) {
        res.status(404);
        res.send({
            error: 'Not found'
        });

        return this;
    }

    /**
     * @method
     * @param {object} req
     * @param {object} res
     * @returns {Router}
     * @public
     */
    sendMethodNotAllowed(req, res) {
        res.status(405);
        res.send({
            error: 'Method Not Allowed'
        });

        return this;
    }

    /**
     * @method
     * @param {string} routeName
     * @param {object} [attributes]
     * @param {suffix} [suffix]
     * @throws Error if route is not defined
     * @throws Error if parameter attributes is not an Object
     * @throws Error if parameter suffix is not a String
     * @returns {string}
     * @public
     */
    generate(routeName, attributes, suffix) {
        let result;

        if (!this.routeMap.hasOwnProperty(routeName)) {
            throw new Error(`Route name "${routeName}" is undefined.`);
        }

        attributes = attributes || {};

        if (typeof attributes !== 'object') {
            throw new Error(`Attributes should to be an Object.`);
        }

        let protocol;
        let host;
        let port;

        if (attributes.hasOwnProperty('_protocol') || attributes.hasOwnProperty('_host') || attributes.hasOwnProperty('_port') || attributes.hasOwnProperty('_absolute')) {
            protocol = attributes['_protocol'] || this.protocol;
            host = attributes['_host'] || this.host;
            port = attributes['_port'] || this.port || '';

            attributes = _.omit(attributes, (value, attr) => {
                if ([
                    '_protocol',
                    '_host',
                    '_port',
                    '_absolute'
                ].indexOf(attr) != -1) {
                    return attr;
                }
            });
        }

        suffix = suffix || '';

        if (typeof suffix !== 'string') {
            throw new Error('Suffix should to be a String.');
        }

        let route = this.routeMap[routeName];

        result = url.format({
            protocol: protocol,
            hostname: host,
            port: port,
            pathname: route.path.replace(this.PARAM_PATTERN, (match, name) => {
                let requirements = new RegExp(route.requirements[name] || '.*');

                if (attributes.hasOwnProperty(name)) {
                    if (requirements.test(attributes[name])) {
                        let value = attributes[name];
                        attributes = _.omit(attributes, name);

                        return value;
                    } else {
                        throw new Error(`Parameter "${name}" is not valid. See requirements of route "${routeName}".`);
                    }
                } else if (route.defaults.hasOwnProperty(name)) {
                    if (requirements.test(route.defaults[name])) {
                        return route.defaults[name];
                    } else {
                        throw new Error(`Default parameter "${name}" is not valid. See requirements of route "${routeName}".`);
                    }
                } else {
                    throw new Error(`Parameter "${name}" is not defined for route "${routeName}".`);
                }
            }),
            query: attributes,
            hash: suffix
        });

        return result;
    }
};

module.exports = new Router();
<commit_msg>lowdash ---> Object.assing()<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const url = require('url');
const mime = require('mime-types');
const _ = require('lodash');

/**
 * @class Router
 */
class Router {
    /**
     * @constructs
     * @param {Express} app
     * @param {object} options
     * @param {string} options.file
     * @param {string} [options.baseDir=__dirname]
     * @throws Error if parameter app is not defined
     * @throws Error if parameter app is not express() function
     * @throws Error if parameter file is not defined
     */
    constructor() {
        return (app, options) => {
            if (app === undefined) {
                throw new Error(`Could not apply router to undefined application.`);
            } else if (typeof app !== 'function') {
                throw new Error(`Application should to be an express() function.`);
            } else {
                // @member {function} app
                this.app = app;
            }

            if (options.file === undefined) {
                throw new Error(`Route's file have to be specified.`);
            } else {
                // @member {string} file
                this.file = options.file;
            }

            // @member {string} [protocol]
            this.protocol = options.protocol || 'http';

            // @member {string} [host]
            this.host = options.host || '';

            // @member {string} [port]
            this.port = options.port || '';

            // @member {string} [baseDir=__dirname]
            this.baseDir = options.baseDir || __dirname;

            this._start();
        };
    }

    /**
     * @method
     * @private
     */
    _start() {
        this.routeMap = {};
        this._normalizeRoutesMap(this._getRoutesFromFile(this.file));

        for (let name in this.routeMap) {
            this._applyRoute(this.routeMap[name]);
        }

        // URI to output routeMap for developing
        // @todo: hide from production mode
        this.app.get('/_dev/routes/', (req, res) => {
            res.json(this.routeMap);
        });

        this.app.use((req, res) => {
            this.sendNotFaund(req, res);
        });
    }

    /**
     * @method
     * @param {object} routes
     * @param {string} [prefix]
     * @param {object} [defaults]
     * @param {object} [requirements]
     * @returns {Router}
     * @private
     */
    _normalizeRoutesMap(routes, prefix, defaults, requirements) {
        prefix = prefix || '';
        defaults = defaults || {};
        requirements = requirements || {};

        for (let name in routes) {
            let route = routes[name];
            let routeDefaults = {};
            let routeRequirements = {};

            Object.assign(routeDefaults, defaults, (route.defaults || {}));
            Object.assign(routeRequirements, requirements, (route.requirements || {}));

            if (route.resource !== undefined) {
                this._normalizeRoutesMap(this._getRoutesFromFile(route.resource), (prefix + (route.prefix || '')), routeDefaults, routeRequirements);
            } else {
                Object.assign(this.routeMap[name] = {}, {
                    name: name,
                    path: prefix + route.path,
                    methods: route.methods || ['all'],
                    defaults: routeDefaults,
                    requirements: routeRequirements
                }, route);
            }
        }

        return this;
    }

    /**
     * @method
     * @param {string} file
     * @returns {json}
     * @private
     */
    _getRoutesFromFile(file) {
        return JSON.parse(fs.readFileSync(path.join(this.baseDir, file), 'utf8'));
    }

    /**
     * @method
     * @param {object} route
     * @returns {Router}
     * @private
     */
    _applyRoute(route) {
        let methods = this._getMethods(route);

        methods.forEach((method) => {
            this.app[method](this._getPath(route), (req, res) => {
                if (this._getTemplate(route)) {
                    res.render(this._getTemplate(route), this._getController(route)(req, res, this));
                } else {
                    res.send(this._getController(route)(req, res, this));
                }
            });
        });

        return this;
    }

    /**
     * @const {RegExp}
     */
    get PARAM_PATTERN() {
        return /\{([^}]+)\}/g;
    }

    /**
     * @method
     * @param {object} route
     * @returns {string}
     * @private
     */
    _getPath(route) {
        let result;

        result = route.path.replace(this.PARAM_PATTERN, (match, name) => {
            let pattern = (typeof route.requirements[name] !== 'undefined') ? `(${route.requirements[name]})` : '';

            return `:${name}${pattern}`;
        });

        return result;
    }

    /**
     * @method
     * @param {object} route
     * @returns {array}
     * @private
     */
    _getMethods(route) {
        let result;
        let methods = route.methods || ['all'];

        if (!Array.isArray(methods)) {
            result = [methods];
        } else {
            result = methods;
        }

        result = result.map((method) => {
            return method.toLowerCase();
        });

        return result;
    }

    /**
     * @method
     * @param {object} router
     * @throws Error if controller for route could not be loaded
     * @returns {function}
     * @private
     */
    _getController(route) {
        let result;
        let controller = route.defaults._controller || '';
        let controllerPath = path.join(this.baseDir, controller);

        try {
            result = require(controllerPath);
        } catch (e) {
            throw new Error(`Could not load controller "${controller}" for route "${route.name}".`);
        }

        return result;
    }

    /**
     * @method
     * @param {object} router
     * @returns {string}
     * @private
     */
    _getFormat(route) {
        let result;
        let template = this._getTemplate(route);

        if (route.defaults.hasOwnProperty(_format) && mime.lookup(this.defaults._format)) {
            if (typeof template !== 'undefined') {
                result = route.defaults._format;
            } else {
                throw new Error(`Template for route "${route.name}" is not defined.`)
            }
        } else if (typeof template !== 'undefined') {
            result = 'html';
        } else {
            result = 'json';
        }

        return result;
    }

    /**
     * @method
     * @param {object} router
     * @returns {string}
     * @private
     */
    _getTemplate(route) {
        let result;

        result = route.defaults._template;

        return result;
    }

    /**
     * @method
     * @param {object} req
     * @param {object} res
     * @returns {Router}
     * @public
     */
    sendNotFaund(req, res) {
        res.status(404);
        res.send({
            error: 'Not found'
        });

        return this;
    }

    /**
     * @method
     * @param {object} req
     * @param {object} res
     * @returns {Router}
     * @public
     */
    sendMethodNotAllowed(req, res) {
        res.status(405);
        res.send({
            error: 'Method Not Allowed'
        });

        return this;
    }

    /**
     * @method
     * @param {string} routeName
     * @param {object} [attributes]
     * @param {suffix} [suffix]
     * @throws Error if route is not defined
     * @throws Error if parameter attributes is not an Object
     * @throws Error if parameter suffix is not a String
     * @returns {string}
     * @public
     */
    generate(routeName, attributes, suffix) {
        let result;

        if (!this.routeMap.hasOwnProperty(routeName)) {
            throw new Error(`Route name "${routeName}" is undefined.`);
        }

        attributes = attributes || {};

        if (typeof attributes !== 'object') {
            throw new Error(`Attributes should to be an Object.`);
        }

        let protocol;
        let host;
        let port;

        if (attributes.hasOwnProperty('_protocol') || attributes.hasOwnProperty('_host') || attributes.hasOwnProperty('_port') || attributes.hasOwnProperty('_absolute')) {
            protocol = attributes['_protocol'] || this.protocol;
            host = attributes['_host'] || this.host;
            port = attributes['_port'] || this.port || '';

            attributes = _.omit(attributes, (value, attr) => {
                if ([
                    '_protocol',
                    '_host',
                    '_port',
                    '_absolute'
                ].indexOf(attr) != -1) {
                    return attr;
                }
            });
        }

        suffix = suffix || '';

        if (typeof suffix !== 'string') {
            throw new Error('Suffix should to be a String.');
        }

        let route = this.routeMap[routeName];

        result = url.format({
            protocol: protocol,
            hostname: host,
            port: port,
            pathname: route.path.replace(this.PARAM_PATTERN, (match, name) => {
                let requirements = new RegExp(route.requirements[name] || '.*');

                if (attributes.hasOwnProperty(name)) {
                    if (requirements.test(attributes[name])) {
                        let value = attributes[name];
                        attributes = _.omit(attributes, name);

                        return value;
                    } else {
                        throw new Error(`Parameter "${name}" is not valid. See requirements of route "${routeName}".`);
                    }
                } else if (route.defaults.hasOwnProperty(name)) {
                    if (requirements.test(route.defaults[name])) {
                        return route.defaults[name];
                    } else {
                        throw new Error(`Default parameter "${name}" is not valid. See requirements of route "${routeName}".`);
                    }
                } else {
                    throw new Error(`Parameter "${name}" is not defined for route "${routeName}".`);
                }
            }),
            query: attributes,
            hash: suffix
        });

        return result;
    }
};

module.exports = new Router();
<|endoftext|>


<commit_before>// from http://www.w3.org/TR/css3-color/#svg-color

export default var cssnames = {
  aliceblue = 15792383,
  antiquewhite = 16444375,
  aqua = 65535,
  aquamarine = 8388564,
  azure = 15794175,
  beige = 16119260,
  bisque = 16770244,
  black = 0,
  blanchedalmond = 16772045,
  blue = 255,
  blueviolet = 9055202,
  brown = 10824234,
  burlywood = 14596231,
  cadetblue = 6266528,
  chartreuse = 8388352,
  chocolate = 13789470,
  coral = 16744272,
  cornflowerblue = 6591981,
  cornsilk = 16775388,
  crimson = 14423102,
  cyan = 65535,
  darkblue = 139,
  darkcyan = 35723,
  darkgoldenrod = 12092939,
  darkgray = 11119017,
  darkgreen = 25600,
  darkgrey = 11119017,
  darkkhaki = 12433259,
  darkmagenta = 9109643,
  darkolivegreen = 5597999,
  darkorange = 16747520,
  darkorchid = 10040012,
  darkred = 9109504,
  darksalmon = 15308410,
  darkseagreen = 9419919,
  darkslateblue = 4734347,
  darkslategray = 3100495,
  darkslategrey = 3100495,
  darkturquoise = 52945,
  darkviolet = 9699539,
  deeppink = 16716947,
  deepskyblue = 49151,
  dimgray = 6908265,
  dimgrey = 6908265,
  dodgerblue = 2003199,
  firebrick = 11674146,
  floralwhite = 16775920,
  forestgreen = 2263842,
  fuchsia = 16711935,
  gainsboro = 14474460,
  ghostwhite = 16316671,
  gold = 16766720,
  goldenrod = 14329120,
  gray = 8421504,
  green = 32768,
  greenyellow = 11403055,
  grey = 8421504,
  honeydew = 15794160,
  hotpink = 16738740,
  indianred = 13458524,
  indigo = 4915330,
  ivory = 16777200,
  khaki = 15787660,
  lavender = 15132410,
  lavenderblush = 16773365,
  lawngreen = 8190976,
  lemonchiffon = 16775885,
  lightblue = 11393254,
  lightcoral = 15761536,
  lightcyan = 14745599,
  lightgoldenrodyellow = 16448210,
  lightgray = 13882323,
  lightgreen = 9498256,
  lightgrey = 13882323,
  lightpink = 16758465,
  lightsalmon = 16752762,
  lightseagreen = 2142890,
  lightskyblue = 8900346,
  lightslategray = 7833753,
  lightslategrey = 7833753,
  lightsteelblue = 11584734,
  lightyellow = 16777184,
  lime = 65280,
  limegreen = 3329330,
  linen = 16445670,
  magenta = 16711935,
  maroon = 8388608,
  mediumaquamarine = 6737322,
  mediumblue = 205,
  mediumorchid = 12211667,
  mediumpurple = 9662683,
  mediumseagreen = 3978097,
  mediumslateblue = 8087790,
  mediumspringgreen = 64154,
  mediumturquoise = 4772300,
  mediumvioletred = 13047173,
  midnightblue = 1644912,
  mintcream = 16121850,
  mistyrose = 16770273,
  moccasin = 16770229,
  navajowhite = 16768685,
  navy = 128,
  oldlace = 16643558,
  olive = 8421376,
  olivedrab = 7048739,
  orange = 16753920,
  orangered = 16729344,
  orchid = 14315734,
  palegoldenrod = 15657130,
  palegreen = 10025880,
  paleturquoise = 11529966,
  palevioletred = 14381203,
  papayawhip = 16773077,
  peachpuff = 16767673,
  peru = 13468991,
  pink = 16761035,
  plum = 14524637,
  powderblue = 11591910,
  purple = 8388736,
  red = 16711680,
  rosybrown = 12357519,
  royalblue = 4286945,
  saddlebrown = 9127187,
  salmon = 16416882,
  sandybrown = 16032864,
  seagreen = 3050327,
  seashell = 16774638,
  sienna = 10506797,
  silver = 12632256,
  skyblue = 8900331,
  slateblue = 6970061,
  slategray = 7372944,
  slategrey = 7372944,
  snow = 16775930,
  springgreen = 65407,
  steelblue = 4620980,
  tan = 13808780,
  teal = 32896,
  thistle = 14204888,
  tomato = 16737095,
  transparent = 0,
  turquoise = 4251856,
  violet = 15631086,
  wheat = 16113331,
  white = 16777215,
  whitesmoke = 16119285,
  yellow = 16776960,
  yellowgreen = 1014507
};
<commit_msg>fix: resolve syntax error<commit_after>// from http://www.w3.org/TR/css3-color/#svg-color

var cssnames = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423102,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  transparent: 0,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 1014507
};

export default cssnames;
<|endoftext|>


<commit_before>(function(win, doc, $) {
    'use strict';

    // hide old table
    $('.bc-old').addClass('hidden');
    // show new table
    $('.bc-data').removeClass('hidden');

    // Private var to assign IDs to history for accessibility purposes
    var historyCount = 0;

    // The open button template
    var $historyLink = $('<button title="' + gettext('Open implementation notes') + '" class="bc-history-link only-icon" tabindex="-1">' + gettext('Open') + '</button>');
    // The close button template
    var $historyCloseButton = $('<button class="bc-history-button only-icon">' + gettext('Close') + '</button>');

    var animationProps = {
        duration: 150,
        queue: false,
        easing: 'linear'
    };

    //  Usage: $('.compat-table').mozCompatTable();
    return jQuery.fn.mozCompatTable = function() {

        return $(this).each(function() {

            var $table = $(this);

            // add beta notice & menu
            addBetaNotice($table);

            // Keep track of what may be open within this table
            var $openCell;

            // This limits very quick opening and closing of cells which results in incorrect height counts
            var animating = false;

            var subjectAnimation = $.extend({ complete: function() { animating = false; } }, animationProps);

            // Activate all history cells for keyboard
            $table.find('.bc-has-history').each(function() {
                var historyId = 'bc-history-' + (++historyCount);
                var $td = $(this);
                var $history = $td.find('.bc-history');

                $td.attr({
                    tabIndex: 0,
                    'aria-expanded': false,
                    'aria-controls': historyId
                });

                $history.attr('id', historyId);
                // generate and add button to open history tray
                $historyLink.clone().insertBefore($history);
            });

            // Listen for interaction on "history" cells
            $table.on('click touchend', '.bc-has-history', function(e) {
                var $actualTarget = $(e.target);

                // Don't open/close if the user interaction is within the history section
                if ($actualTarget.parents('.bc-history').length || $actualTarget.hasClass('bc-history')) {
                    e.stopImmediatePropagation();
                    return;
                }

                // prevent touch event from bubbling to a click event as well
                // has no effect if this was a click
                e.preventDefault();

                // Close previous cell, open the next one
                closeAndOpenHistory($(this));
            });

            // Listen for interaction on "close" buttons
            $table.on('click touchend', '.bc-history-button', function(ev) {
                ev.stopImmediatePropagation();
                hideHistory();
            });

            // Listen for keyboard events to open/close history
            $table.on('keypress', '.bc-has-history', function(ev) {
                var $td = $(this);
                var key = ev.which;

                if (key === 13 || key === 32) {
                    closeAndOpenHistory($td);
                    ev.preventDefault();
                } else if (key === 27) {
                    hideHistory();
                    ev.preventDefault();
                }
            });

            /** add beta notice & associated functonality */
            function addBetaNotice($table) {
                var $betaMenuWrapper = $('
', { 'class': 'bc-beta-menu' });
                var $betaMenuTrigger = $('', { text: gettext('New compatibility tables are in beta '), href: '/en-US/docs/New_Compatibility_Tables_Beta' }).append($('', { class: 'icon-caret-down', 'aria-hidden': 'true' }));
                var $betaSubmenu = $('
', { 'class': 'submenu js-submenu' });
                var betaSubmenuItems = [];

                var $betaLink = $('', { text: gettext('More about the beta.'), href: '/docs/New_Compatibility_Tables_Beta' });
                betaSubmenuItems.push($betaLink);

                var $betaSurvey = $('', { text: gettext('Take the survey'), href: 'https://www.surveygizmo.com/s3/2342437/0b5ff6b6b8f6', 'class': 'external external-icon' });
                betaSubmenuItems.push($betaSurvey);

                var $betaError = $('<button />', { text: gettext('Report an error.'), 'class': 'button bc-error' });
                $betaError.on('click', function() {
                    mdn.analytics.trackEvent({
                        category: 'Compat Tables Error',
                        action: location.pathname
                    });
                    mdn.Notifier.growl(gettext('Reported. Thanks!'), { duration: 2000, closable: true }).success();
                });
                betaSubmenuItems.push($betaError);

                var $betaShowOld = $('<button />', { text: gettext('Show old table.'), 'class': 'button bc-old' });
                $betaShowOld.on('click', function() {
                    $('.bc-old').toggle();
                    mdn.analytics.trackEvent({
                        category: 'Compat Tables Show Old',
                        action: location.pathname
                    });
                });
                betaSubmenuItems.push($betaShowOld);

                $(betaSubmenuItems).each(function() {
                    var $newItem = $('
');
                    $newItem.append(this);
                    $newItem.appendTo($betaSubmenu);
                });

                $betaMenuWrapper.append($betaMenuTrigger).append($betaSubmenu);
                $betaMenuWrapper.insertBefore($table);

                $betaMenuWrapper.mozMenu().mozKeyboardNav();
            }

            /** Function which closes any open history items, then opens the target history item
                Acts as the "router" for open and close directives */
            function closeAndOpenHistory($td) {
                if (animating) {
                    return;
                }

                // If no cell is open at the moment, skip the "close" step and just open it
                if (!$openCell) {
                    return _open($td);
                }

                // If click event is from the currently closing cell, set $td to null
                var previousOpenCell = $openCell && $openCell.get(0);
                if ($td.get(0) === previousOpenCell) {
                    $td = null;
                }

                // Close what's open, if anything, and open if $td has a value
                hideHistory($td);
            }

            /** Opens the history for a given item */
            function showHistory() {
                if (animating) {
                    return;
                }

                var $row = $openCell.closest('tr');
                var $history = $openCell.find('.bc-history').outerWidth($table.width());

                // get cell coords
                var cellLeft = $openCell.offset().left;

                // get cell border widths
                var cellBorders = $openCell.css(['border-top-width', 'border-left-width', 'border-bottom-width']);

                // get table coords
                var tableLeft = $table.offset().left;

                // left coord of table minus left coord of cell
                var historyLeft = tableLeft - cellLeft - parseInt(cellBorders['border-left-width'], 10);

                // get cell height
                var cellTop = $openCell.outerHeight();

                var historyTop = cellTop - parseInt(cellBorders['border-bottom-width'], 10) - parseInt(cellBorders['border-top-width'], 10);

                var historyHeight;
                var $subject;
                var displayDetect;

                // Add a close button if one doesn't already exist
                if ($history.find('.bc-history-button').length === 0) {
                    $historyCloseButton.clone().appendTo($history);
                }

                // move history where it will display
                $history.css({ left: historyLeft, top: historyTop });

                // measure height
                $history.css('display', 'block').attr('aria-hidden', false);
                historyHeight = $history.outerHeight();

                // set max-height to 0 and visibility to visible
                $openCell.addClass('active').attr('aria-expanded', true);

                // add measured height to history and to the cell/row it is being displayed beneath (CSS handles transition)
                displayDetect = parseInt($table.find('thead td').first().css('z-index'));

                if (displayDetect === 1 ) {
                    $subject = $row.find('td');
                } else if (displayDetect === 2) {
                    $subject = $openCell;
                } else {
                    $subject = $row.find('th, td');
                }

                animating = true;
                $history.css('height', 0).stop().animate({ height: historyHeight }, animationProps);

                $subject.stop().animate({ borderBottomWidth: historyHeight }, subjectAnimation);
            }

            /**
             * Hides the history dropdown for a given cell
             * @param {Object} $td - Hides the dropdown for this cell
             */
            function hideHistory($td) {
                var $history;

                if (animating) {
                    return;
                }

                // Animate the borders back down
                $openCell.attr('aria-expanded', false).stop().animate({ borderBottomWidth: '' }, animationProps);
                $openCell.closest('tr').find('th, td').stop().animate({ borderBottomWidth: '' }, animationProps);

                $history = $openCell.find('.bc-history');

                var historyAnimationProps = $.extend({
                    complete: function() {
                        $openCell.removeClass('active');
                        $history.css('display', 'none').css('height', 'auto');
                        $openCell = null;

                        if ($td) {
                            _open($td);
                        }
                    }
                }, animationProps);

                $history.attr('aria-hidden', true).stop().animate({ height: '' }, historyAnimationProps);

                // if the focus is inside the .bc-history and we'd lose our keyboard place, move focus to parent
                if ($.contains($openCell.get(0), doc.activeElement)) {
                    $openCell.focus();
                }
            }

            /**
             * Opens a cell and records it
             * @param {Object} $td - The cell to open
             */
            function _open($td) {
                // Set this cell as open
                $openCell = $td;
                // Show!
                showHistory();
            }
        });
    };

})(window, document, jQuery);
<commit_msg>Fixed l10n-aware link to New_Compatibility_Tables_Beta (#4609)<commit_after>(function(win, doc, $) {
    'use strict';

    // hide old table
    $('.bc-old').addClass('hidden');
    // show new table
    $('.bc-data').removeClass('hidden');

    // Private var to assign IDs to history for accessibility purposes
    var historyCount = 0;

    // The open button template
    var $historyLink = $('<button title="' + gettext('Open implementation notes') + '" class="bc-history-link only-icon" tabindex="-1">' + gettext('Open') + '</button>');
    // The close button template
    var $historyCloseButton = $('<button class="bc-history-button only-icon">' + gettext('Close') + '</button>');

    var animationProps = {
        duration: 150,
        queue: false,
        easing: 'linear'
    };

    //  Usage: $('.compat-table').mozCompatTable();
    return jQuery.fn.mozCompatTable = function() {

        return $(this).each(function() {

            var $table = $(this);

            // add beta notice & menu
            addBetaNotice($table);

            // Keep track of what may be open within this table
            var $openCell;

            // This limits very quick opening and closing of cells which results in incorrect height counts
            var animating = false;

            var subjectAnimation = $.extend({ complete: function() { animating = false; } }, animationProps);

            // Activate all history cells for keyboard
            $table.find('.bc-has-history').each(function() {
                var historyId = 'bc-history-' + (++historyCount);
                var $td = $(this);
                var $history = $td.find('.bc-history');

                $td.attr({
                    tabIndex: 0,
                    'aria-expanded': false,
                    'aria-controls': historyId
                });

                $history.attr('id', historyId);
                // generate and add button to open history tray
                $historyLink.clone().insertBefore($history);
            });

            // Listen for interaction on "history" cells
            $table.on('click touchend', '.bc-has-history', function(e) {
                var $actualTarget = $(e.target);

                // Don't open/close if the user interaction is within the history section
                if ($actualTarget.parents('.bc-history').length || $actualTarget.hasClass('bc-history')) {
                    e.stopImmediatePropagation();
                    return;
                }

                // prevent touch event from bubbling to a click event as well
                // has no effect if this was a click
                e.preventDefault();

                // Close previous cell, open the next one
                closeAndOpenHistory($(this));
            });

            // Listen for interaction on "close" buttons
            $table.on('click touchend', '.bc-history-button', function(ev) {
                ev.stopImmediatePropagation();
                hideHistory();
            });

            // Listen for keyboard events to open/close history
            $table.on('keypress', '.bc-has-history', function(ev) {
                var $td = $(this);
                var key = ev.which;

                if (key === 13 || key === 32) {
                    closeAndOpenHistory($td);
                    ev.preventDefault();
                } else if (key === 27) {
                    hideHistory();
                    ev.preventDefault();
                }
            });

            /** add beta notice & associated functonality */
            function addBetaNotice($table) {
                var $betaMenuWrapper = $('
', { 'class': 'bc-beta-menu' });
                var $betaMenuTrigger = $('', { text: gettext('New compatibility tables are in beta '), href: '/docs/New_Compatibility_Tables_Beta' }).append($('', { class: 'icon-caret-down', 'aria-hidden': 'true' }));
                var $betaSubmenu = $('
', { 'class': 'submenu js-submenu' });
                var betaSubmenuItems = [];

                var $betaLink = $('', { text: gettext('More about the beta.'), href: '/docs/New_Compatibility_Tables_Beta' });
                betaSubmenuItems.push($betaLink);

                var $betaSurvey = $('', { text: gettext('Take the survey'), href: 'https://www.surveygizmo.com/s3/2342437/0b5ff6b6b8f6', 'class': 'external external-icon' });
                betaSubmenuItems.push($betaSurvey);

                var $betaError = $('<button />', { text: gettext('Report an error.'), 'class': 'button bc-error' });
                $betaError.on('click', function() {
                    mdn.analytics.trackEvent({
                        category: 'Compat Tables Error',
                        action: location.pathname
                    });
                    mdn.Notifier.growl(gettext('Reported. Thanks!'), { duration: 2000, closable: true }).success();
                });
                betaSubmenuItems.push($betaError);

                var $betaShowOld = $('<button />', { text: gettext('Show old table.'), 'class': 'button bc-old' });
                $betaShowOld.on('click', function() {
                    $('.bc-old').toggle();
                    mdn.analytics.trackEvent({
                        category: 'Compat Tables Show Old',
                        action: location.pathname
                    });
                });
                betaSubmenuItems.push($betaShowOld);

                $(betaSubmenuItems).each(function() {
                    var $newItem = $('
');
                    $newItem.append(this);
                    $newItem.appendTo($betaSubmenu);
                });

                $betaMenuWrapper.append($betaMenuTrigger).append($betaSubmenu);
                $betaMenuWrapper.insertBefore($table);

                $betaMenuWrapper.mozMenu().mozKeyboardNav();
            }

            /** Function which closes any open history items, then opens the target history item
                Acts as the "router" for open and close directives */
            function closeAndOpenHistory($td) {
                if (animating) {
                    return;
                }

                // If no cell is open at the moment, skip the "close" step and just open it
                if (!$openCell) {
                    return _open($td);
                }

                // If click event is from the currently closing cell, set $td to null
                var previousOpenCell = $openCell && $openCell.get(0);
                if ($td.get(0) === previousOpenCell) {
                    $td = null;
                }

                // Close what's open, if anything, and open if $td has a value
                hideHistory($td);
            }

            /** Opens the history for a given item */
            function showHistory() {
                if (animating) {
                    return;
                }

                var $row = $openCell.closest('tr');
                var $history = $openCell.find('.bc-history').outerWidth($table.width());

                // get cell coords
                var cellLeft = $openCell.offset().left;

                // get cell border widths
                var cellBorders = $openCell.css(['border-top-width', 'border-left-width', 'border-bottom-width']);

                // get table coords
                var tableLeft = $table.offset().left;

                // left coord of table minus left coord of cell
                var historyLeft = tableLeft - cellLeft - parseInt(cellBorders['border-left-width'], 10);

                // get cell height
                var cellTop = $openCell.outerHeight();

                var historyTop = cellTop - parseInt(cellBorders['border-bottom-width'], 10) - parseInt(cellBorders['border-top-width'], 10);

                var historyHeight;
                var $subject;
                var displayDetect;

                // Add a close button if one doesn't already exist
                if ($history.find('.bc-history-button').length === 0) {
                    $historyCloseButton.clone().appendTo($history);
                }

                // move history where it will display
                $history.css({ left: historyLeft, top: historyTop });

                // measure height
                $history.css('display', 'block').attr('aria-hidden', false);
                historyHeight = $history.outerHeight();

                // set max-height to 0 and visibility to visible
                $openCell.addClass('active').attr('aria-expanded', true);

                // add measured height to history and to the cell/row it is being displayed beneath (CSS handles transition)
                displayDetect = parseInt($table.find('thead td').first().css('z-index'));

                if (displayDetect === 1 ) {
                    $subject = $row.find('td');
                } else if (displayDetect === 2) {
                    $subject = $openCell;
                } else {
                    $subject = $row.find('th, td');
                }

                animating = true;
                $history.css('height', 0).stop().animate({ height: historyHeight }, animationProps);

                $subject.stop().animate({ borderBottomWidth: historyHeight }, subjectAnimation);
            }

            /**
             * Hides the history dropdown for a given cell
             * @param {Object} $td - Hides the dropdown for this cell
             */
            function hideHistory($td) {
                var $history;

                if (animating) {
                    return;
                }

                // Animate the borders back down
                $openCell.attr('aria-expanded', false).stop().animate({ borderBottomWidth: '' }, animationProps);
                $openCell.closest('tr').find('th, td').stop().animate({ borderBottomWidth: '' }, animationProps);

                $history = $openCell.find('.bc-history');

                var historyAnimationProps = $.extend({
                    complete: function() {
                        $openCell.removeClass('active');
                        $history.css('display', 'none').css('height', 'auto');
                        $openCell = null;

                        if ($td) {
                            _open($td);
                        }
                    }
                }, animationProps);

                $history.attr('aria-hidden', true).stop().animate({ height: '' }, historyAnimationProps);

                // if the focus is inside the .bc-history and we'd lose our keyboard place, move focus to parent
                if ($.contains($openCell.get(0), doc.activeElement)) {
                    $openCell.focus();
                }
            }

            /**
             * Opens a cell and records it
             * @param {Object} $td - The cell to open
             */
            function _open($td) {
                // Set this cell as open
                $openCell = $td;
                // Show!
                showHistory();
            }
        });
    };

})(window, document, jQuery);
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter,
  inherits = require('util').inherits,
  assert = require('assert'),
  _ = require('lodash'),
  requireDir = require('require-directory'),
  Cache = require('./Cache'),
  deco = requireDir(module, './decorators'),
  util = require('./util'),
  PROPAGATED_EVENT_NAMES = ['error', 'get', 'set', 'del', 'stale'];

module.exports = CacheClient;

/**
 * Create a new cache client,
 * decorated with the desired features,
 * based on the provided config.
 *
 * @constructor
 * @param {Object} [config]
 *
 * @param {Boolean} [config.isPreconfigured] defaults to false
 *
 * @param {String} [config.host] defaults to 'localhost'
 * @param {Number} [config.port] defaults to 6379
 * @param {String} [config.password]
 * @param {String} [config.namespace]
 *
 * @param {String} [config.optimizeForSmallValues] defaults to false
 * @param {String} [config.stopEventPropagation] defaults to false
 *
 * @param {String} [config.expiresIn] in ms
 * @param {String} [config.staleIn] in ms
 *
 * @param {Function} [config.populate]
 *
 * @param {Number} [config.populateIn] in ms, defaults to 30sec
 * @param {Number} [config.pausePopulateIn] in ms
 * @param {Number} [config.leaseExpiresIn] in ms
 * @param {Number} [config.accessedAtThrottle] in ms
 * @param {Number} [config.namespace]
 */

function CacheClient(config) {
  EventEmitter.call(this);
  this._config = config || {};

  this._redisClient = util.createRedisClient(this._config);
  this._redisClient.on('error', this._onRedisError.bind(this));

  this._redisSubClient = util.createRedisClient(this._config);
  this._redisSubClient.on('error', this._onRedisError.bind(this));

  if (!this._config.isPreconfigured) {
    util.ensureKeyspaceNotifications(
      this._redisClient, util.logError);
  }
  this.on('error', unhandledErrorListener);
}

inherits(CacheClient, EventEmitter);

CacheClient.prototype._onRedisError = function (err) {
  this.emit('error', err);
};

/**
 * Create a new Cache
 *
 * @param {String} namespace
 * @param {Object} config @see CacheClient constructor
 */

CacheClient.prototype.create = function (namespace, config) {
  var cache;

  assert(namespace, 'namespace must be set');
  namespace = util.createNamespace(this._config.namespace, namespace);
  config = _.defaults(config || {}, this._config);

  cache = new Cache(this._redisClient, {
    namespace: namespace
  });

  if (!config.optimizeForSmallValues) {
    cache = new deco.OnlySetChangedDecorator(cache);
  }

  cache = new deco.MarshallDecorator(cache);

  if (config.expiresIn || config.staleIn) {
    cache = new deco.ExpiresDecorator(cache, {
      expiresIn: config.expiresIn,
      staleIn: config.staleIn
    });
  }

  if (config.populate) {
    cache = new deco.PopulateDecorator(cache, {
      populate: config.populate,
      leaseExpiresIn: config.leaseExpiresIn
    });

    if (config.populateIn) {
      cache = new deco.PopulateInDecorator(cache, this._redisSubClient, {
        populateIn: config.populateIn,
        pausePopulateIn: config.pausePopulateIn,
        accessedAtThrottle: config.accessedAtThrottle
      });
    }
  }

  if (!config.stopEventPropagation) {
    util.propagateEvents(cache, this,
      PROPAGATED_EVENT_NAMES, namespace);
  }

  return cache;
};

/**
 * Wrap EventEmitter#on in order to remove the
 * default unhandled-error listener.
 *
 * @param {String} type
 * @param {Function} listener
 */

CacheClient.prototype.on = function (type, listener) {
  if ('error' === type && listener !== unhandledErrorListener) {
    this.removeListener(type, unhandledErrorListener);
  }
  EventEmitter.prototype.on.call(this, type, listener);
};

function unhandledErrorListener(err) {
  console.error('[distribucache] error from an unhandled ' +
    '`error` event:\n', err && err.stack || err);
}
<commit_msg>CacheClient: refactor and add api doc<commit_after>var EventEmitter = require('events').EventEmitter,
  inherits = require('util').inherits,
  assert = require('assert'),
  _ = require('lodash'),
  requireDir = require('require-directory'),
  Cache = require('./Cache'),
  deco = requireDir(module, './decorators'),
  util = require('./util'),
  PROPAGATED_EVENT_NAMES = ['error', 'get', 'set', 'del', 'stale'];

module.exports = CacheClient;

/**
 * Create a new cache client,
 * decorated with the desired features,
 * based on the provided config.
 *
 * @constructor
 * @param {Object} [config]
 *
 * @param {Boolean} [config.isPreconfigured] defaults to false
 *
 * @param {String} [config.host] defaults to 'localhost'
 * @param {Number} [config.port] defaults to 6379
 * @param {String} [config.password]
 * @param {String} [config.namespace]
 *
 * @param {String} [config.optimizeForSmallValues] defaults to false
 * @param {String} [config.stopEventPropagation] defaults to false
 *
 * @param {String} [config.expiresIn] in ms
 * @param {String} [config.staleIn] in ms
 *
 * @param {Function} [config.populate]
 *
 * @param {Number} [config.populateIn] in ms, defaults to 30sec
 * @param {Number} [config.pausePopulateIn] in ms
 * @param {Number} [config.leaseExpiresIn] in ms
 * @param {Number} [config.accessedAtThrottle] in ms
 * @param {Number} [config.namespace]
 */

function CacheClient(config) {
  EventEmitter.call(this);
  this._config = config || {};

  this._redisClient = util.createRedisClient(this._config);
  this._redisClient.on('error', this._onRedisError.bind(this));

  this._redisSubClient = util.createRedisClient(this._config);
  this._redisSubClient.on('error', this._onRedisError.bind(this));

  if (!this._config.isPreconfigured) {
    util.ensureKeyspaceNotifications(
      this._redisClient, util.logError);
  }
  this.on('error', unhandledErrorListener);
}

inherits(CacheClient, EventEmitter);

/**
 * Create a new Cache
 *
 * @param {String} namespace
 * @param {Object} config @see CacheClient constructor
 */

CacheClient.prototype.create = function (namespace, config) {
  var cache;

  assert(namespace, 'namespace must be set');
  namespace = util.createNamespace(this._config.namespace, namespace);
  config = _.defaults(config || {}, this._config);

  cache = new Cache(this._redisClient, {
    namespace: namespace
  });

  if (!config.optimizeForSmallValues) {
    cache = new deco.OnlySetChangedDecorator(cache);
  }

  cache = new deco.MarshallDecorator(cache);

  if (config.expiresIn || config.staleIn) {
    cache = new deco.ExpiresDecorator(cache, {
      expiresIn: config.expiresIn,
      staleIn: config.staleIn
    });
  }

  if (config.populate) {
    cache = new deco.PopulateDecorator(cache, {
      populate: config.populate,
      leaseExpiresIn: config.leaseExpiresIn
    });

    if (config.populateIn) {
      cache = new deco.PopulateInDecorator(cache, this._redisSubClient, {
        populateIn: config.populateIn,
        pausePopulateIn: config.pausePopulateIn,
        accessedAtThrottle: config.accessedAtThrottle
      });
    }
  }

  if (!config.stopEventPropagation) {
    util.propagateEvents(cache, this,
      PROPAGATED_EVENT_NAMES, namespace);
  }

  return cache;
};

/**
 * Wrap EventEmitter#on in order to remove the
 * default unhandled-error listener.
 *
 * @param {String} type
 * @param {Function} listener
 */

CacheClient.prototype.on = function (type, listener) {
  if ('error' === type && listener !== unhandledErrorListener) {
    this.removeListener(type, unhandledErrorListener);
  }
  EventEmitter.prototype.on.call(this, type, listener);
};

/**
 * Proxy all redis error events to the
 * CacheClient error events.
 *
 * @private
 * @param {Error} err
 */

CacheClient.prototype._onRedisError = function (err) {
  this.emit('error', err);
};

function unhandledErrorListener(err) {
  console.error('[distribucache] error from an unhandled ' +
    '`error` event:\n', err && err.stack || err);
}
<|endoftext|>


<commit_before>const _ = require('lodash');
const dotenv = require('dotenv');
const program = require('commander');
const logger = require('./services/logger');
const importFrom = require('import-from');
const DB = require('./services/db');
const TableAnalyzer = require('./services/table-analyzer');
const inquirer = require('inquirer');
const argv = require('minimist')(process.argv.slice(2));

program
  .description('Install a Lumber plugin')
  .parse(process.argv);

(async () => {
  // Load the environment variables from the .env to avoid always asking for the DB
  // connection information.
  dotenv.load();
  const dbDialect = process.env.DATABASE_URL.substring(process.env.DATABASE_URL.indexOf(':'));
  const config = {
    dbConnectionUrl: process.env.DATABASE_URL,
    dbSSL: ['true', true, '1', 1].includes(process.env.DATABASE_SSL),
    dbDialect,
  };

  if (!program.args[0]) {
    logger.error(
      'Missing package in the command.',
      'Please specify the plugin\'s package name you want to install. Type lumber help for more information.',
    );

    return process.exit(1);
  }

  const pkg = importFrom(process.cwd(), program.args[0]);

  const db = await new DB().connect(config);
  const schema = await new TableAnalyzer(db, config).perform();
  let promptConfig = {};

  if (_.isFunction(pkg.install)) {
    promptConfig = await pkg.install(logger, inquirer, argv);
  }

  await pkg.dump(schema, promptConfig, config);

  return process.exit(0);
})().catch((err) => {
  console.error(err);
});
<commit_msg>[-] Code Style - Improve a comment format<commit_after>const _ = require('lodash');
const dotenv = require('dotenv');
const program = require('commander');
const logger = require('./services/logger');
const importFrom = require('import-from');
const DB = require('./services/db');
const TableAnalyzer = require('./services/table-analyzer');
const inquirer = require('inquirer');
const argv = require('minimist')(process.argv.slice(2));

program
  .description('Install a Lumber plugin')
  .parse(process.argv);

(async () => {
  // NOTICE: Load the environment variables from the .env to avoid always asking for the DB
  //         connection information.
  dotenv.load();
  const dbDialect = process.env.DATABASE_URL.substring(process.env.DATABASE_URL.indexOf(':'));
  const config = {
    dbConnectionUrl: process.env.DATABASE_URL,
    dbSSL: ['true', true, '1', 1].includes(process.env.DATABASE_SSL),
    dbDialect,
  };

  if (!program.args[0]) {
    logger.error(
      'Missing package in the command.',
      'Please specify the plugin\'s package name you want to install. Type lumber help for more information.',
    );

    return process.exit(1);
  }

  const pkg = importFrom(process.cwd(), program.args[0]);

  const db = await new DB().connect(config);
  const schema = await new TableAnalyzer(db, config).perform();
  let promptConfig = {};

  if (_.isFunction(pkg.install)) {
    promptConfig = await pkg.install(logger, inquirer, argv);
  }

  await pkg.dump(schema, promptConfig, config);

  return process.exit(0);
})().catch((err) => {
  console.error(err);
});
<|endoftext|>


<commit_before>import { h, Component } 				from 'preact/preact';
import Sanitize							from '../../internal/sanitize/sanitize';

import DialogBase						from 'com/dialog-base/base';
import LabelYesNo						from 'com/label-yesno/yesno';

import $User							from '../shrub/js/user/user';

export default class DialogRegister extends Component {
	constructor( props ) {
		super(props);

		console.log("DialogRegister",this.state);

		this.state = {
			mail: "",
			error: null,
			loading: false
		};

		// Bind functions (avoiding the need to rebind every render)
		this.onChange = this.onChange.bind(this);
		this.doRegister = this.doRegister.bind(this);
		this.doFinish = this.doFinish.bind(this);
	}

	componentDidMount() {
		this.registerMail.focus();
	}

	onChange( e ) {
		this.setState({ mail: e.target.value });
	}

	doRegister() {
		mail = this.state.mail.trim();

		if ( Sanitize.validateMail(mail) ) {
			this.setState({ loading: true, error: null });

			$User.Register( mail )
			.then( r => {
				if ( r.status === 201 ) {
					console.log('sent', r.sent);
					this.setState({sent: true, loading: false});
				}
				else if ( r.status === 200 ) {
					console.log('resent', r.sent);
					this.setState({sent: true, resent: true, loading: false});
				}
				else {
					console.log(r);
					this.setState({ error: r.message ? r.message : r.response, loading: false });
				}
				return r;
			})
			.catch( err => {
				console.log(err);
				this.setState({ error: err, loading: false });
			});
		}
		else {
			this.setState({ error: "Incorrectly formatted e-mail address" });
		}
	}

	doFinish() {
		location.href = location.pathname+location.search;
	}

	render( props, {mail, sent, resent, loading, error} ) {
		var ErrorMessage = error ? {'error': error} : {};
		var title = "Create Account";

		if ( loading ) {
			return (
				<DialogBase title={title} explicit {...ErrorMessage}>

						Please wait...

				</DialogBase>
			);
		}
		else if ( sent ) {
			return (
				<DialogBase title={title} ok explicit onclick={this.doFinish} {...ErrorMessage}>

						Activation e-mail {resent ? 'resent' : 'sent'} to {mail}

				</DialogBase>
			);
		}
		else {
			// NOTE: There's a Preact bug that the extra  is working around
			return (
				<DialogBase title={title} ok cancel oktext="Send Activation E-mail" explicit onclick={this.doRegister} {...ErrorMessage}>

						<input ref={(input) => this.registerMail = input} id="dialog-register-mail" onchange={this.onChange} class="-text focusable" type="text" name="email" placeholder="E-mail address" maxlength="254" /><LabelYesNo value={Sanitize.validateMail(mail) ? 1 : -1} />

						Expect an e-mail from hello@jammer.vg

						If you use Hotmail or Outlook, go to  { return e.stopPropagation() }}>people and add a contact.

				</DialogBase>
			);
		}
	}
}
<commit_msg>added more tips for registration<commit_after>import { h, Component } 				from 'preact/preact';
import Sanitize							from '../../internal/sanitize/sanitize';

import DialogBase						from 'com/dialog-base/base';
import LabelYesNo						from 'com/label-yesno/yesno';

import $User							from '../shrub/js/user/user';

export default class DialogRegister extends Component {
	constructor( props ) {
		super(props);

		console.log("DialogRegister",this.state);

		this.state = {
			mail: "",
			error: null,
			loading: false
		};

		// Bind functions (avoiding the need to rebind every render)
		this.onChange = this.onChange.bind(this);
		this.doRegister = this.doRegister.bind(this);
		this.doFinish = this.doFinish.bind(this);
	}

	componentDidMount() {
		this.registerMail.focus();
	}

	onChange( e ) {
		this.setState({ mail: e.target.value.trim() });
	}

	doRegister() {
		mail = this.state.mail.trim();

		if ( Sanitize.validateMail(mail) ) {
			this.setState({ loading: true, error: null });

			$User.Register( mail )
			.then( r => {
				if ( r.status === 201 ) {
					console.log('sent', r.sent);
					this.setState({sent: true, loading: false});
				}
				else if ( r.status === 200 ) {
					console.log('resent', r.sent);
					this.setState({sent: true, resent: true, loading: false});
				}
				else {
					console.log(r);
					this.setState({ error: r.message ? r.message : r.response, loading: false });
				}
				return r;
			})
			.catch( err => {
				console.log(err);
				this.setState({ error: err, loading: false });
			});
		}
		else {
			this.setState({ error: "Incorrectly formatted e-mail address" });
		}
	}

	doFinish() {
		location.href = location.pathname+location.search;
	}

	render( props, {mail, sent, resent, loading, error} ) {
		var ErrorMessage = error ? {'error': error} : {};
		var title = "Create Account";

		if ( loading ) {
			return (
				<DialogBase title={title} explicit {...ErrorMessage}>

						Please wait...

				</DialogBase>
			);
		}
		else if ( sent ) {
			return (
				<DialogBase title={title} ok explicit onclick={this.doFinish} {...ErrorMessage}>

						Activation e-mail {resent ? 'resent' : 'sent'} to {mail}

				</DialogBase>
			);
		}
		else {
			return (
				<DialogBase title={title} ok cancel oktext="Send Activation E-mail" explicit onclick={this.doRegister} {...ErrorMessage}>

						Enter your e-mail address to begin activating your account.

						<input ref={(input) => this.registerMail = input} id="dialog-register-mail" onchange={this.onChange} class="-text focusable" type="text" name="email" placeholder="E-mail address" maxlength="254" value={mail} /><LabelYesNo value={mail.trim().length ? (Sanitize.validateMail(mail) ? 1 : -1) : 0} />

						Hotmail, Outlook, Live.com: Add hello@jammer.vg to your contacts.

						Free.fr: Probably wont work. We've sent a whitelisting request.

						Laposte.net: Sorry! We can't figure out how to fix them. :(

				</DialogBase>
			);

//						TIP: For Hotmail, Outlook, live.com go to  { return e.stopPropagation() }}>people and add a contact.
		}
	}
}
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Rx = require('rx');
var RxWrap = require('./observable_rx_wrap');
var Logger = require('./logger')();
var Query = require('./query');

var Registry = require('./registry');

var Runtime = module.exports = function(opts) {
  EventEmitter.call(this);
  //There are locking issues in the unit tests. This is a brief work around.
  if(opts && opts.registry) {
    this.registry = opts.registry;
  } else {
    this.registry = new Registry();
  }
  this.exposed = {};
  this.path = '/devices';
  this.exposeQuery = null;
  this._jsDevices = [];
  this._observable = Rx.Observable.fromEvent(this, 'deviceready');
};
util.inherits(Runtime, EventEmitter);

//
Runtime.prototype.log = function(message, data) {
  Logger.emit('user-log', message, data);
};

// query related
Runtime.prototype.ql = function() {};

//for now we'll just return the JavaScript object.
Runtime.prototype.where = function(params) {
  return new Query(params);
};

Runtime.prototype.expose = function(query) {

  if(typeof query === 'string' && query === '*') {
    query = new Query(query);
  }

  var self = this;

  this.on('deviceready', function(device) {
    if(query.match(device)) {
      self._exposeDevice(device);
    }
  });
};

Runtime.prototype._exposeDevice = function(device) {
  this.exposed[this.path + '/' + device.id] = device;
};

//This is the new observe syntax. It will take an array of queries, and a callback.
Runtime.prototype.observe = function(queries, cb) {
  var self = this;
  var filters = [];

  queries.forEach(function(query){
    var filter = self._observable.filter(function(device) {
      console.log(device);
      return query.match(device);
    });
    filters.push(filter);
  });

  var source = filters.shift();

  if(filters.length !== 1) {
    filters.push(function() {
      return arguments;
    });
    source.zip.apply(source, filters);
  }

  source
    .subscribe(function(args){
      if (Array.isArray(args)) {
        cb.apply(null, Array.prototype.slice.call(args));
      } else {
        cb.apply(null, [args]);
      }
    });
};

// raw db -
Runtime.prototype.find = function() {
  return this.registry.find.apply(this.registry, arguments);
};
<commit_msg>Added some reactive methods on the runtime for use in an app.<commit_after>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Rx = require('rx');
var RxWrap = require('./observable_rx_wrap');
var Logger = require('./logger')();
var Query = require('./query');

var Registry = require('./registry');

var Runtime = module.exports = function(opts) {
  EventEmitter.call(this);
  //There are locking issues in the unit tests. This is a brief work around.
  if(opts && opts.registry) {
    this.registry = opts.registry;
  } else {
    this.registry = new Registry();
  }
  this.exposed = {};
  this.path = '/devices';
  this.exposeQuery = null;
  this._jsDevices = [];
  this._observable = Rx.Observable.fromEvent(this, 'deviceready');

  this.filter = this._observable.filter.bind(this._observable);
  this.map = this._observable.map.bind(this._observable);
  this.take = this._observable.take.bind(this._observable);
  this.zip = this._observable.zip.bind(this._observable);
};
util.inherits(Runtime, EventEmitter);

//
Runtime.prototype.log = function(message, data) {
  Logger.emit('user-log', message, data);
};

// query related
Runtime.prototype.ql = function() {};

//for now we'll just return the JavaScript object.
Runtime.prototype.where = function(params) {
  return new Query(params);
};

Runtime.prototype.expose = function(query) {

  if(typeof query === 'string' && query === '*') {
    query = new Query(query);
  }

  var self = this;

  this.on('deviceready', function(device) {
    if(query.match(device)) {
      self._exposeDevice(device);
    }
  });
};

Runtime.prototype._exposeDevice = function(device) {
  this.exposed[this.path + '/' + device.id] = device;
};

//This is the new observe syntax. It will take an array of queries, and a callback.
Runtime.prototype.observe = function(queries, cb) {
  var self = this;
  var filters = [];

  queries.forEach(function(query){
    var filter = self._observable.filter(function(device) {
      console.log(device);
      return query.match(device);
    });
    filters.push(filter);
  });

  var source = filters.shift();

  if(filters.length !== 1) {
    filters.push(function() {
      return arguments;
    });
    source.zip.apply(source, filters);
  }

  source
    .subscribe(function(args){
      if (Array.isArray(args)) {
        cb.apply(null, Array.prototype.slice.call(args));
      } else {
        cb.apply(null, [args]);
      }
    });
};

// raw db -
Runtime.prototype.find = function() {
  return this.registry.find.apply(this.registry, arguments);
};
<|endoftext|>


<commit_before>/*
 * Module dependencies
 */

var util = require('./util');

var Interface = require('./interface');
var Command = require('./command/constructor');
var RuntimeError = require('./command/error');
var RuntimeWarning = require('./command/warning');

var prettyfy = util.prettyfy;

/*
 * Runtime module
 */

exports = module.exports = {};

/*
 * Runtime refs/helpers
 *
 *  - handle : the `runtimes` holder.
 *
 *  @api private
 */

var handle = {};

/*
 * Module [Getters]
 */

defineGetter(Interface, 'handle', function(){
  return handle[handle._current];
});

defineGetter(Interface, 'parser', function(){
  return handle[handle._current].parser;
});

defineGetter(Interface, 'completer', function(){
  return handle[handle._current].completer;
});

/*
 * doc holder
 */

function createRuntime(name){

  if(!name){
    throw RuntimeError(
      'To create a runtime you need a name'
    );
  }
  else {
    handle._current = name;
  }

  if(!handle[name]){

    var self = new Runtime(name);

    var runtime = function (cmd, args, cb){
      return runtime.terminal(cmd, args, cb);
    };

    util.merge(runtime, self);

    handle._current = name;
    handle[name] = runtime;

    return runtime;
  }
  else {
    return handle[name];
  }
}
exports.createRuntime = createRuntime;

/*
 * doc holder
 */

function Runtime(name){

  if(!name){
    throw RuntimeError(
      'To create a `runtime` you need a name.'
    );
  }

  if( !(this instanceof Runtime) ){
    return new Runtime(name);
  }
  else {

    // Defaults
    this._name = name;
    this._timer = {};
    this.setPrompt(' > '+name+ ' ');

    // The basic command parser
    this.parser = require('./command/parser');

    // Creating the runtime namespace
    this.set();
  }
}
exports.Runtime = Runtime;

/*
 * doc holder
 */
Runtime.prototype.set = function(name, fn){

    fn = fn ? fn : function Root(){};
  name = name ? name : this._name;

  var anchor = {
            fn : fn,
         _name : name,
       _parent : this._name,
      children : {},
    completion : []
  };

  if(arguments.length === 0){
    return new Command(anchor);
  }
  else{
    return (new Command(anchor)).set(name, fn);
  }
};
/*
 * doc holder
 */
Runtime.prototype.get = function(name){

  name = name ? name : this._name;

  var anchor = {
         fn : function Root(){},
      _name : name,
    _parent : this._name
  };

  return (new Command(anchor)).get(name);
};

/*
 * Runtime instance namespace handle
 *
 *
 */
Runtime.prototype.handle = function(){
};

/*
 * doc holder
 */
Runtime.prototype.terminal = function(cmd, args, cb){

  console.log('handling "%s"', cmd)
  prettyfy.color(arguments);

  var command = this.get(cmd).fn

  if(!command){
    RuntimeWarning({
      message : 'Command "'+ cmd +'" not defined.'
    });
  }
  else if(typeof command === 'function'){
    command.call(this, cmd, args);
  }

  Interface.emit('done', cmd, args, cb);
};

/*
 * doc holder
 */

Runtime.prototype.completer = function(line){

  var completion = [];
  if(completions.length !== 0){
    var hits = completions.filter(function(c) {
        return c.indexOf(line) == 0;
      });

    // show all completions if none found
    return [hits.length ? hits : completions, line];
  }
  else{
    return [ [''], line];
  }
};

/*
 * doc holder
 */
Runtime.prototype.waiting = function(eventName, fn){

  var self = this;
  var timer = this._timer;

  fn = fn ? fn : function(){}

  if(!timer[eventName])
    timer[eventName] = setTimeout(function(){
      Interface.emit(eventName);
      fn.call(self);
    },10);
  else {
    clearTimeout(timer.startup);
    timer[eventName] = setTimeout(function(){
      Interface.emit(eventName);
      fn.call(self);
    });
  }
};

/*
 * doc holder
 */

Runtime.prototype.onStartup = function(fn){

  var self = this;

  Interface.on('startup', function(){
    fn.call(self);
  })

  this.waiting('startup');
};

Runtime.prototype.resume = function(){

  Interface.resume();
};

/*
 * Runtime's Interface `prompt`
 */
Runtime.prototype.prompt = function(/* arguments */){

  Interface.prompt.apply(
    Interface, [].slice.call(arguments)
  );
}
/*
* Runtime's Interface `setPrompt`
 */
Runtime.prototype.setPrompt = function(/* arguments */){

  Interface.setPrompt.apply(
    Interface, [].slice.call(arguments)
  );
};

/*
 * doc holder
 */

Runtime.prototype.emit = function(/* arguments */){

  Interface.emit.apply(
    Interface, [].slice.call(arguments)
  );
};

/*
 * Order the prototype by key length
 */
var unOrdered = Runtime.prototype;
var ordered = {};
var keys = Object.keys(Runtime.prototype)

keys.sort(function(key, next){
  return key.length-next.length;
}).forEach(function(method){
  ordered[method] = unOrdered[method];
});

Runtime.prototype = ordered;

function defineGetter(obj, name, getter) {
  Object.defineProperty(obj, name, {
    configurable: true,
    enumerable: true,
    get: getter
  });
};<commit_msg>liting prior to 0.2.0<commit_after>/*
 * Module dependencies
 */

var util = require('./util');

var Interface = require('./interface');
var Command = require('./command/constructor');
var RuntimeError = require('./command/error');
var RuntimeWarning = require('./command/warning');

var prettyfy = util.prettyfy;

/*
 * Runtime module
 */

exports = module.exports = {};

/*
 * Runtime refs/helpers
 *
 *  - handle : the `runtimes` holder.
 *
 *  @api private
 */

var handle = {};

/*
 * Module [Getters]
 */

defineGetter(Interface, 'handle', function(){
  return handle[handle._current];
});

defineGetter(Interface, 'parser', function(){
  return handle[handle._current].parser;
});

defineGetter(Interface, 'completer', function(){
  return handle[handle._current].completer;
});

/*
 * doc holder
 */

function createRuntime(name){

  if(!name){
    throw RuntimeError(
      'To create a runtime you need a name'
    );
  }
  else {
    handle._current = name;
  }

  if(!handle[name]){

    var self = new Runtime(name);

    var runtime = function (cmd, args, cb){
      return runtime.terminal(cmd, args, cb);
    };

    util.merge(runtime, self);

    handle._current = name;
    handle[name] = runtime;

    return runtime;
  }
  else {
    return handle[name];
  }
}
exports.createRuntime = createRuntime;

/*
 * doc holder
 */

function Runtime(name){

  if(!name){
    throw RuntimeError(
      'To create a `runtime` you need a name.'
    );
  }

  if( !(this instanceof Runtime) ){
    return new Runtime(name);
  }
  else {

    // Defaults
    this._name = name;
    this._timer = {};
    this.setPrompt(' > '+name+ ' ');

    // The basic command parser
    this.parser = require('./command/parser');

    // Creating the runtime namespace
    this.set();
  }
}
exports.Runtime = Runtime;

/*
 * doc holder
 */
Runtime.prototype.set = function(name, fn){

    fn = fn ? fn : function Root(){};
  name = name ? name : this._name;

  var anchor = {
            fn : fn,
         _name : name,
       _parent : this._name,
      children : {},
    completion : []
  };

  if(arguments.length === 0){
    return new Command(anchor);
  }
  else{
    return (new Command(anchor)).set(name, fn);
  }
};
/*
 * doc holder
 */
Runtime.prototype.get = function(name){

  name = name ? name : this._name;

  var anchor = {
         fn : function Root(){},
      _name : name,
    _parent : this._name
  };

  return (new Command(anchor)).get(name);
};

/*
 * Runtime instance namespace handle
 *
 *
 */
Runtime.prototype.handle = function(){
};

/*
 * doc holder
 */
Runtime.prototype.terminal = function(cmd, args, cb){

  console.log('handling "%s"', cmd)
  prettyfy.color(arguments);

  var command = this.get(cmd).fn

  if(!command){
    RuntimeWarning({
      message : 'Command "'+ cmd +'" not defined.'
    });
  }
  else if(typeof command === 'function'){
    command.call(this, cmd, args);
  }

  Interface.emit('done', cmd, args, cb);
};

/*
 * doc holder
 */

Runtime.prototype.completer = function(line){

  var completion = [];
  if(completion.length !== 0){
    var hits = completion.filter(function(c) {
        return c.indexOf(line) === 0;
      });

    // show all completions if none found
    return [hits.length ? hits : completion, line];
  }
  else{
    return [ [''], line];
  }
};

/*
 * doc holder
 */
Runtime.prototype.waiting = function(eventName, fn){

  var self = this;
  var timer = this._timer;

  fn = fn ? fn : function(){}

  if(!timer[eventName])
    timer[eventName] = setTimeout(function(){
      Interface.emit(eventName);
      fn.call(self);
    },10);
  else {
    clearTimeout(timer.startup);
    timer[eventName] = setTimeout(function(){
      Interface.emit(eventName);
      fn.call(self);
    });
  }
};

/*
 * doc holder
 */

Runtime.prototype.onStartup = function(fn){

  var self = this;

  Interface.on('startup', function(){
    fn.call(self);
  })

  this.waiting('startup');
};

Runtime.prototype.resume = function(){

  Interface.resume();
};

/*
 * Runtime's Interface `prompt`
 */
Runtime.prototype.prompt = function(/* arguments */){

  Interface.prompt.apply(
    Interface, [].slice.call(arguments)
  );
}
/*
* Runtime's Interface `setPrompt`
 */
Runtime.prototype.setPrompt = function(/* arguments */){

  Interface.setPrompt.apply(
    Interface, [].slice.call(arguments)
  );
};

/*
 * doc holder
 */

Runtime.prototype.emit = function(/* arguments */){

  Interface.emit.apply(
    Interface, [].slice.call(arguments)
  );
};

/*
 * Order the prototype by key length
 */
var unOrdered = Runtime.prototype;
var ordered = {};
var keys = Object.keys(Runtime.prototype)

keys.sort(function(key, next){
  return key.length-next.length;
}).forEach(function(method){
  ordered[method] = unOrdered[method];
});

Runtime.prototype = ordered;

function defineGetter(obj, name, getter) {
  Object.defineProperty(obj, name, {
    configurable: true,
    enumerable: true,
    get: getter
  });
};<|endoftext|>


<commit_before>var mysql = require('mysql');
var bcrypt = require('bcrypt');
var moment = require('moment');
var Promise = require('es6-promise').Promise;
var _ = require('lodash');
var params = require('../config/secrets.js').params;

exports.putUser = function(userObject) {
	console.dir(userObject);
	return new Promise(function(resolve, reject) {
		hashed(userObject.card).then(function(result) {
			userObject.card = result;

			var connection = mysql.createConnection(params);
			connection.connect();
			connection.query("INSERT INTO members SET ?", userObject, function(err, result) {
				if(err) {
					console.log('sql insert err', err.code);
					if(err.code === 'ER_DUP_ENTRY') {
						console.log('here');
						reject({
							accountexists: true
						});
					} else {
						reject(err);
					}
				} else {
					console.log('member ID:', result.insertId);
					console.log(result);
					resolve(result.insertId);
				}
			});
			connection.end(function(err) {
				if(err) {
					console.log(err);
				}
			});
		}, function(err) {
			reject(err);
		});
	});
};

exports.signIn = function(card) {
	return new Promise(function(resolve, reject) {
		var meetingKey;
		var userKey;
		// Check that a meeting is happening today
		checkMeeting().then(function(result) {
			if(result === []) {
				reject('No meeting today you scurvy curr!');
			}
			meetingKey = result;
		}, function(error) {
			reject(error);
		}).then(function() {
			console.log('ji');
			hashCompare(card).then(function(result) {
				var memberKey = result;
				if(memberKey === undefined) {
					reject('Member not found, have you created an account?');
				}
				console.log('memberKey', memberKey);

				var connection = mysql.createConnection(params);
				connection.connect();
				connection.query("INSERT INTO attendance SET ?", {
					memberKey: memberKey,
					meetingKey: meetingKey
				}, function(err, result) {
					if(err) {
						if(err.code ==='ER_DUP_ENTRY') {
							reject({
								meetingError: {
									alreadySignedIn: true
								}
							});
							return;
						}
						console.log('err in insertattnd', err);
					} else {
						resolve(result);
						console.log('attend?', result);
					}

					connection.end(function(err) {
						if(err) {
							console.log(err);
						}
					});
				});
			}, function(error) {
				console.log(error);
			});
		}, function(error) {
			console.log(error);
		});
	});
};

exports.createMeeting = function(date) {
	console.log(date);
	var insertDate = {
		date: date
	};

	var connection = mysql.createConnection(params);
	connection.connect();
	connection.query("INSERT INTO meetings SET ?", insertDate, function(err, result) {
		if(err) {
			console.log(err);
		}
		console.log('meeting ID:', result.insertId);
		console.log(result);
	});
	connection.end(function(err) {
		if(err) {
			console.log(err);
		}
	});
};

exports.getMembers = function() {
	return new Promise(function(resolve, reject) {
		var connection = mysql.createConnection(params);
		connection.connect();

		connection.query("SELECT * FROM members", function(err, result) {
			if(err) {
				reject(err);
			}
			resolve(result);
		});

		connection.end(function(err) {
			if(err) {
				console.log(err);
			}
		});
	});
};

exports.getMeetings = function() {
	return new Promise(function(resolve, reject) {
		var connection = mysql.createConnection(params);
		connection.connect();

		connection.query("SELECT * FROM meetings", function(err, result) {
			if(err) {
				reject(err);
			}
			resolve(result);
		});

		connection.end(function(err) {
			if(err) {
				console.log(err);
			}
		});
	});
};

function hashed(data) {
	return new Promise(function(resolve, reject) {
	    bcrypt.hash(data, 10, function(err, hash) {
			if(err) {
				reject(err);
			}

			console.log(hash);
			resolve(hash);
		});
	});
}

function hashCompare(card) {
	return new Promise(function(resolve, reject) {
		var connection = mysql.createConnection(params);
		connection.connect();
		connection.query("SELECT * FROM members", function(err, result) {
			if(err) {
				console.log('err', err);
			}

			_.forEach(result, function(member) {
				// console.log('caaaard',card, member.card);
				bcrypt.compare(card, member.card, function(err, same) {
					if(err) {
						console.log('compare err', err);
					} else if(same) {
						console.log('samesies');
						resolve(member.membersKey);
					}
				});
			});
			console.log('uh oh');
		});

		connection.end(function(err) {
			if(err) {
				console.log('hashcardcannotcloseerrror', err);
			}
		});
	});
}

function checkMeeting() {
	return new Promise(function(resolve, reject) {
		var today = mysql.escape(moment().format('YYYY-MM-DD'));
		var connection = mysql.createConnection(params);
		connection.connect();

		connection.query("SELECT * FROM meetings WHERE date=" + today, function(err, result) {
			if(err) {
				reject(err);
			} else {
				console.log('meeting?', result);
				if(result.length <= 0) {
					reject({
						meetingError: {
							noMeeting: true
						}
					});
				} else {
					resolve(result[0].meetingKey);
				}
			}
		});

		connection.end(function(err) {
			if(err) {
				console.log('mtgcannotcloseerrror', err);
			}
		});
	});
}

function dateCheck(date) {
	var today = moment();
	var meeting = moment(date);

	return new Promise(function(resolve, reject) {
		if(today.year() === meeting.year() &&
			today.month() == meeting.month() &&
			today.date() === meeting.date()) {
				resolve();
		} else {
			reject('No meeting today you scurvy curr!');
		}
	});
}
<commit_msg>Make sure you are in the proper timezone(Eastern) -- hotfoot, as utcOffset does not account for DST<commit_after>var mysql = require('mysql');
var bcrypt = require('bcrypt');
var moment = require('moment');
var Promise = require('es6-promise').Promise;
var _ = require('lodash');
var params = require('../config/secrets.js').params;

exports.putUser = function(userObject) {
	console.dir(userObject);
	return new Promise(function(resolve, reject) {
		hashed(userObject.card).then(function(result) {
			userObject.card = result;

			var connection = mysql.createConnection(params);
			connection.connect();
			connection.query("INSERT INTO members SET ?", userObject, function(err, result) {
				if(err) {
					console.log('sql insert err', err.code);
					if(err.code === 'ER_DUP_ENTRY') {
						console.log('here');
						reject({
							accountexists: true
						});
					} else {
						reject(err);
					}
				} else {
					console.log('member ID:', result.insertId);
					console.log(result);
					resolve(result.insertId);
				}
			});
			connection.end(function(err) {
				if(err) {
					console.log(err);
				}
			});
		}, function(err) {
			reject(err);
		});
	});
};

exports.signIn = function(card) {
	return new Promise(function(resolve, reject) {
		var meetingKey;
		var userKey;
		// Check that a meeting is happening today
		checkMeeting().then(function(result) {
			if(result === []) {
				reject('No meeting today you scurvy curr!');
			}
			meetingKey = result;
		}, function(error) {
			reject(error);
		}).then(function() {
			console.log('ji');
			hashCompare(card).then(function(result) {
				var memberKey = result;
				if(memberKey === undefined) {
					reject('Member not found, have you created an account?');
				}
				console.log('memberKey', memberKey);

				var connection = mysql.createConnection(params);
				connection.connect();
				connection.query("INSERT INTO attendance SET ?", {
					memberKey: memberKey,
					meetingKey: meetingKey
				}, function(err, result) {
					if(err) {
						if(err.code ==='ER_DUP_ENTRY') {
							reject({
								meetingError: {
									alreadySignedIn: true
								}
							});
							return;
						}
						console.log('err in insertattnd', err);
					} else {
						resolve(result);
						console.log('attend?', result);
					}

					connection.end(function(err) {
						if(err) {
							console.log(err);
						}
					});
				});
			}, function(error) {
				console.log(error);
			});
		}, function(error) {
			console.log(error);
		});
	});
};

exports.createMeeting = function(date) {
	console.log(date);
	var insertDate = {
		date: date
	};

	var connection = mysql.createConnection(params);
	connection.connect();
	connection.query("INSERT INTO meetings SET ?", insertDate, function(err, result) {
		if(err) {
			console.log(err);
		}
		console.log('meeting ID:', result.insertId);
		console.log(result);
	});
	connection.end(function(err) {
		if(err) {
			console.log(err);
		}
	});
};

exports.getMembers = function() {
	return new Promise(function(resolve, reject) {
		var connection = mysql.createConnection(params);
		connection.connect();

		connection.query("SELECT * FROM members", function(err, result) {
			if(err) {
				reject(err);
			}
			resolve(result);
		});

		connection.end(function(err) {
			if(err) {
				console.log(err);
			}
		});
	});
};

exports.getMeetings = function() {
	return new Promise(function(resolve, reject) {
		var connection = mysql.createConnection(params);
		connection.connect();

		connection.query("SELECT * FROM meetings", function(err, result) {
			if(err) {
				reject(err);
			}
			resolve(result);
		});

		connection.end(function(err) {
			if(err) {
				console.log(err);
			}
		});
	});
};

function hashed(data) {
	return new Promise(function(resolve, reject) {
	    bcrypt.hash(data, 10, function(err, hash) {
			if(err) {
				reject(err);
			}

			console.log(hash);
			resolve(hash);
		});
	});
}

function hashCompare(card) {
	return new Promise(function(resolve, reject) {
		var connection = mysql.createConnection(params);
		connection.connect();
		connection.query("SELECT * FROM members", function(err, result) {
			if(err) {
				console.log('err', err);
			}

			_.forEach(result, function(member) {
				// console.log('caaaard',card, member.card);
				bcrypt.compare(card, member.card, function(err, same) {
					if(err) {
						console.log('compare err', err);
					} else if(same) {
						console.log('samesies');
						resolve(member.membersKey);
					}
				});
			});
			console.log('uh oh');
		});

		connection.end(function(err) {
			if(err) {
				console.log('hashcardcannotcloseerrror', err);
			}
		});
	});
}

function checkMeeting() {
	return new Promise(function(resolve, reject) {
		var today = mysql.escape(moment().utcOffset(-4).format('YYYY-MM-DD HH'));
		console.log('today:', today);
		var connection = mysql.createConnection(params);
		connection.connect();

		connection.query("SELECT * FROM meetings WHERE date=" + today, function(err, result) {
			if(err) {
				reject(err);
			} else {
				console.log('meeting?', result);
				if(result.length <= 0) {
					reject({
						meetingError: {
							noMeeting: true
						}
					});
				} else {
					resolve(result[0].meetingKey);
				}
			}
		});

		connection.end(function(err) {
			if(err) {
				console.log('mtgcannotcloseerrror', err);
			}
		});
	});
}

function dateCheck(date) {
	var today = moment();
	var meeting = moment(date);

	return new Promise(function(resolve, reject) {
		if(today.year() === meeting.year() &&
			today.month() == meeting.month() &&
			today.date() === meeting.date()) {
				resolve();
		} else {
			reject('No meeting today you scurvy curr!');
		}
	});
}
<|endoftext|>


<commit_before>import { stringify } from 'query-string';
import isEmpty from 'lodash/isEmpty';

import legacyIds from 'data/legacy-ids.json';

const idToSlugDict = legacyIds.reduce(
  (obj, item) => ({
    ...obj,
    ...(item.v2_dataset_id && {
      [item.v2_dataset_id]: item.dataset_slug,
    }),
    ...(item.v3_dataset_id && {
      [item.v3_dataset_id]: item.dataset_slug,
    }),
    ...(item.v2_layer_id && {
      [item.v2_layer_id]: item.layer_slug,
    }),
    ...(item.v3_layer_id && {
      [item.v3_layer_id]: item.layer_slug,
    }),
  }),
  {}
);

const remapDatasets = (datasets) =>
  datasets?.reduce(
    (arr, dataset) => [
      ...arr,
      {
        ...dataset,
        dataset: idToSlugDict[dataset.dataset] || dataset.dataset,
        layers: dataset.layers?.reduce(
          (lArr, layerId) => [...lArr, idToSlugDict[layerId] || layerId],
          []
        ),
      },
    ],
    []
  );

export const decodeQueryParams = (params) => {
  const paramsParsed = {};
  Object.keys(params).forEach((key) => {
    try {
      paramsParsed[key] = JSON.parse(
        Buffer.from(params[key], 'base64').toString('binary')
      );
    } catch (err) {
      try {
        paramsParsed[key] = JSON.parse(params[key]);
      } catch (error) {
        paramsParsed[key] = params[key];
      }
    }
  });

  if (paramsParsed?.map?.datasets) {
    paramsParsed.map = {
      ...paramsParsed.map,
      datasets: remapDatasets(paramsParsed.map.datasets),
    };
  }

  return paramsParsed;
};

export const encodeQueryParams = (params, options) => {
  const paramsParsed = {};
  Object.keys(params).forEach((key) => {
    if (
      params[key] &&
      typeof params[key] === 'object' &&
      !isEmpty(params[key])
    ) {
      paramsParsed[key] = btoa(JSON.stringify(params[key]));
    } else if (typeof params[key] !== 'object' && params[key]) {
      paramsParsed[key] = params[key];
    }
  });

  return stringify(paramsParsed, options);
};
<commit_msg>comments for url utils<commit_after>import { stringify } from 'query-string';
import isEmpty from 'lodash/isEmpty';

import legacyIds from 'data/legacy-ids.json';

const idToSlugDict = legacyIds.reduce(
  (obj, item) => ({
    ...obj,
    ...(item.v2_dataset_id && {
      [item.v2_dataset_id]: item.dataset_slug,
    }),
    ...(item.v3_dataset_id && {
      [item.v3_dataset_id]: item.dataset_slug,
    }),
    ...(item.v2_layer_id && {
      [item.v2_layer_id]: item.layer_slug,
    }),
    ...(item.v3_layer_id && {
      [item.v3_layer_id]: item.layer_slug,
    }),
  }),
  {}
);

// maps legacy ids for layers and datasets to application level slugs
const remapDatasets = (datasets) =>
  datasets?.reduce(
    (arr, dataset) => [
      ...arr,
      {
        ...dataset,
        dataset: idToSlugDict[dataset.dataset] || dataset.dataset,
        layers: dataset.layers?.reduce(
          (lArr, layerId) => [...lArr, idToSlugDict[layerId] || layerId],
          []
        ),
      },
    ],
    []
  );

export const decodeQueryParams = (params) => {
  const decodedParams = Object.keys(params)?.reduce((obj, key) => {
    try {
      return {
        ...obj,
        // we use Buffer as atob is node native to node for SSR
        [key]: JSON.parse(
          Buffer.from(params[key], 'base64').toString('binary')
        ),
      };
    } catch (err) {
      try {
        return {
          ...obj,
          [key]: JSON.parse(params[key]),
        };
      } catch (error) {
        return {
          ...obj,
          [key]: params[key],
        };
      }
    }
  }, {});

  if (decodedParams?.map?.datasets) {
    decodedParams.map = {
      ...decodedParams.map,
      datasets: remapDatasets(decodedParams.map.datasets),
    };
  }

  return decodedParams;
};

export const encodeQueryParams = (params, options) => {
  const encodedParams = Object.keys(params)?.reduce((obj, key) => {
    // if params in an object encode in base64
    if (
      params[key] &&
      typeof params[key] === 'object' &&
      !isEmpty(params[key])
    ) {
      return { ...obj, [key]: btoa(JSON.stringify(params[key])) };
    }
    // if params is a valid key and not falsey
    if (typeof params[key] !== 'object' && params[key]) {
      return { ...obj, [key]: params[key] };
    }
    // otherwise ingore key
    return obj;
  }, {});

  return stringify(encodedParams, options);
};
<|endoftext|>


<commit_before>describe('Hello UT', function() {
	it('To be success', function() {
		expect(1).toBe(1);
	});
//	it('To be fail', function() {
//		expect(0).toBe(1);
//	});
});

describe('Hello Directive', function() {
	var $compile;
	var $rootScope;
	beforeEach(module('popupApp'));
	beforeEach(inject(function(_$compile_, _$rootScope_) {
		$compile = _$compile_;
		$rootScope = _$rootScope_;
	}));

	it('Compile tabs directive', function() {
		var element = $compile("<tabs></tabs>")($rootScope);
//		$rootScope.$digest();
//		expect(element.html()).toContain("...");
	});
});
<commit_msg>Delete test spec<commit_after><|endoftext|>