<commit_before>var oil = require('oil');

var binary = {
    "==": function (left, right) { return left == right; },
    "!=": function (left, right) { return left != right; },
    "<": function (left, right) { return left < right; },
    ">": function (left, right) { return left > right; },
    "<=": function (left, right) { return left <= right; },
    ">=": function (left, right) { return left >= right; },
    "<<": function (left, right) { return left >> right; },
    ">>": function (left, right) { return left << right; },
    "+": function (left, right) { return left != null ? (right != null ? left + right : left) : right; }, // preventing string operation with null to convert to "null"
    "-": function (left, right) { return left != null ? (right != null ? left - right : left) : -right; }, // preventing string operation with null to conert to NaN
    "*": function (left, right) { return left * right; },
    "/": function (left, right) { return left / right; },
    "%": function (left, right) { return left % right; }
};

var unary = {
    "!": function (argument) { return !argument; },
    "+": function (argument) { return +argument; },
    "-": function (argument) { return -argument; }
};

var expressions = {
    "?:": function (expression, model) {
        if (evaluate(expression.expression, model)) {
            return evaluate(expression.positive, model);
        }
        else {
            return evaluate(expression.negative, model);
        }
    },
    "?=": function (expression, model) {
        var value = evaluate(expression.expression, model);
        for (var i = 0; i < expression.options.length; i++) {
            var option = expression.options[i];
            if (evaluate(option.value, model)) {
                return evaluate(option.result, model);
            }
        }
        return evaluate(option.otherwise, model);
    },
    "f": function (expression, model) {
        var object = evaluate(expression.object, model);
        if (object) {
            return object[expression.field];
        }
        return null;
    },
    "i": function (expression, model) {
        return model.get(expression.identifier);
    },
    "b": function (expression, model) {
        return binary[expression.operator](evaluate(expression.left, model), evaluate(expression.right, model));
    },
    "u": function (expression, model) {
        return unary[expression.operator](evaluate(expression.argument, model));
    },
    "??": function (expression, model) {
        var left = evaluate(expression.left, model);
        if (left == null) {
            return evaluate(expression.right, model);
        }
        return left;
    },
    "&&": function (expression, model) {
        return evaluate(expression.left, model) && evaluate(expression.right, model);
    },
    "||": function (expression, model) {
        return evaluate(expression.left, model) || evaluate(expression.right, model);
    },
    "@": function (expression, model) {
        var sequence = evaluate(expression.sequence, model);
        if (sequence) {
            return sequence[evaluate(expression.key, model)];
        }
        return null;
    },
    "@:": function (expression, model) {
        var sequence = evaluate(expression.sequence, model);
        if (sequence) {
            return sequence.slice(evaluate(expression.start, model), evaluate(expression.end, model));
        }
        return null;
    },
    "s": function (expression, model) {
        return null;
    },
    "=": function (expression, model) {
        return null;
    }
};

var modifiers = {
    round: function (value) {
        return Math.round(value)
    },
    number: function (value) {
        var f = parseFloat(value);
        if (!isNaN(f)) {
            var s = f.toString();
            var p = s.indexOf('.');
            var i = p > 0 ? s.slice(0, p) : s;
            var n = i.length - 3;
            while (n > 0) {
                i = i.slice(0, n) + ',' + i.slice(n);
                n -= 3;
            }
            return p > 0 ? i + s.slice(p) : i;
        }
        return "";
    },
    date: function (value, format) {
        if (value != null) {
            var d = new Date(value);
            if (format === "f") {
                return d.getDate() + "/" +
                    (d.getMonth() + 1) + "/" +
                    d.getFullYear() + " " +
                    ("0" + d.getHours()).slice(-2) + ":" +
                    ("0" + d.getMinutes()).slice(-2);
            }

            return d.getDate() + "/" +
                (d.getMonth() + 1) + "/" +
                d.getFullYear();
        }
        return "";
    },
    sqrt: function (value) {
        return Math.sqrt(value);
    },
    sin: function (value) {
        return Math.sin(value);
    },
    cos: function (value) {
        return Math.cos(value);
    },
    tan: function (value) {
        return Math.tan(value);
    },
    asin: function (value) {
        return Math.asic(value);
    },
    acos: function (value) {
        return Math.acos(value);
    },
    atan: function (value) {
        return Math.atan(value);
    },
    PI: function () {
        return Math.PI;
    }
};

function extend(source, obj) {
    if (source) {
        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                obj[key] = source[key];
            }
        }
    }
    return obj;
}

function evaluate(expression, model) {
    while (expression && expression["!exp"]) {
        if (expression.$x) {
            // Expression loop
            expression = null;
        }
        else {
            expression.$x = true;
            var r = expressions[expression["!exp"]](expression, model);
            expression.$x = false;
            expression = r;
        }
    }
    if (expression && expression["!type"]) {
        var modifier = modifiers[expression["!type"]];
        if (modifier) {
            var init = expression["!init"];
            var args = [];
            if (init && init.length > 0) {
                args = init.map(function (x) { return evaluate(x, model); });
            }
            return modifier.apply(null, args);
        }
        return null;
    }
    return expression;
}

function isNotWhitespace(ch) {
    return !(ch === ' ' || ch === '\r' || ch === '\t' ||
    ch === '\n' || ch === '\v' || ch === '\u00A0');
}

function isNotIdentifier(ch) {
    return !('a' <= ch && ch <= 'z' ||
    'A' <= ch && ch <= 'Z' ||
    '_' === ch || ch === '$' || ch === '#');
}

function search(str, s, cb) {
    var i = 0;
    if (typeof s === "function") {
        cb = s;
    }
    else {
        i = s;
    }
    while (i < str.length && !cb(str[i])) {
        i++;
    }
    return i;
}

function Model(baseModel, model, parameters) {
    this.baseModel = baseModel;
    this.model = model;
    this.parameters = parameters;
}

Model.prototype.get = function (key) {
    if (key) {
        if (key[0] == '$') {
            var n = key.length === 1 ? 0 : parseInt(key.slice(1));
            if (this.parameters && n < this.parameters.length) {
                return evaluate(this.parameters[n].parameter, this.parameters[n].model);
            }
        }
        else {
            var v = null;
            if (typeof this.model === "object") {
                v = this.model[key];
            }
            if (v == null && this.baseModel != null) {
                return this.baseModel.get(key);
            }
            return v;
        }
    }

    return null;
};

function Rendo(template) {
    this.components = {};

    var components = oil.parse(template);

    for (var i = 0; i < components.length; i++) {
        var component = components[i];

        var name = component["!type"];
        if (name) {
            var render = component.render
                ? component.render
                : (component["!init"] && component["!init"].length > 0
                ? component["!init"][0]
                : (component["!ref"] || null));

            var scope = {};

            for (var key in component) {
                if (key[0] !== '!' && key !== "render") {
                    scope[key] = component[key];
                }
            }

            this.components[name] = {
                render: render,
                scope: scope
            };
        }
    }
}

Rendo.prototype.renderValue = function (value) {
    if (value != null && typeof value !== "object") {
        return "" + value;
    }
    return "";
};

Rendo.prototype.renderContents = function (contents, model) {
    var result = "";

    var s = 0;
    var o = contents.indexOf("{{");
    while (o >= s) {
        result += contents.slice(s, o);
        o += 2;

        var component = null;
        var fromModel = false;
        var i = search(contents, o, isNotWhitespace);

        if (contents[i] === ':' || contents[i] === '+') {
            fromModel = contents[i] == '+';
            o = i + 1;
            i = search(contents, o, isNotIdentifier);
            component = contents.slice(o, i);
        }

        // Reading to closing '}'
        var c = i;
        var count = 0;
        while (c < contents.length) {
            if (contents[c] === '{') {
                count++;
            }
            else if (contents[c] === '}') {
                if (count === 0) {
                    break;
                }
                count--;
            }
            c++;
        }

        var expressions = oil.parse(contents.slice(i, c));
        if (expressions.length > 0) {
            var models = evaluate(expressions[0], model);
            var parameters = expressions.slice(1).map(function (x) { return { model: model, parameter: x }; });

            if (!models || models.constructor !== Array) {
                models = [models];
            }

            for (var m = 0; m < models.length; m++) {
                if (component) {
                    if (fromModel) {
                        var renderContents = model.get(component);
                        if (renderContents) {
                            result += this.renderContents(renderContents, new Model(model, models[m], [{model: model, parameter: models[m]}].concat(parameters)));
                        }
                    }
                    else {
                        result += this.render(component, new Model(model, models[m]), [{model: model, parameter: models[m]}].concat(parameters));
                    }
                }
                else {
                    result += this.renderValue(models[m]);
                }
            }
        }
        else if (component) {
            // Render same model
            if (fromModel) {
                var renderContents = model.get(component);
                if (renderContents) {
                    result += this.renderContents(renderContents, model);
                }
            }
            else {
                result += this.render(component, model);
            }
        }

        if (c === contents.length || contents[c + 1] != "}") {
            return result;
        }

        s = c + 2;
        o = contents.indexOf("{{", s);
    }

    if (s < contents.length) {
        result += contents.slice(s);
    }

    return result;
};

Rendo.prototype.render = function (componentName, model, parameters) {
    if (componentName == null) {
        return this.renderValue(model);
    }

    var component = this.components[componentName];
    if (!component) {
        return "";
    }

    var contents = component.render;
    if (!contents) {
        return "";
    }

    var models;
    if (model) {
        if (model.constructor === Array) {
            models = model;
        }
        else {
            models = [model];
        }
    }
    else {
        models = [null];
    }

    var result = "";
    for (var m = 0; m < models.length; m++) {
        var model = models[m];
        if (!model || model.constructor !== Model) {
            model = new Model(null, model);
        }

        result += this.renderContents(contents, new Model(model, component.scope, parameters));
    }
    return result;
};

Rendo.render = function (template, component, model) {
    return new Rendo(template).render(component, model);
};

module.exports = Rendo;<commit_msg>Environment parameters and pow modifier<commit_after>var oil = require('oil');

var binary = {
    "==": function (left, right) { return left == right; },
    "!=": function (left, right) { return left != right; },
    "<": function (left, right) { return left < right; },
    ">": function (left, right) { return left > right; },
    "<=": function (left, right) { return left <= right; },
    ">=": function (left, right) { return left >= right; },
    "<<": function (left, right) { return left >> right; },
    ">>": function (left, right) { return left << right; },
    "+": function (left, right) { return left != null ? (right != null ? left + right : left) : right; }, // preventing string operation with null to convert to "null"
    "-": function (left, right) { return left != null ? (right != null ? left - right : left) : -right; }, // preventing string operation with null to conert to NaN
    "*": function (left, right) { return left * right; },
    "/": function (left, right) { return left / right; },
    "%": function (left, right) { return left % right; }
};

var unary = {
    "!": function (argument) { return !argument; },
    "+": function (argument) { return +argument; },
    "-": function (argument) { return -argument; }
};

var expressions = {
    "?:": function (expression, model) {
        if (evaluate(expression.expression, model)) {
            return evaluate(expression.positive, model);
        }
        else {
            return evaluate(expression.negative, model);
        }
    },
    "?=": function (expression, model) {
        var value = evaluate(expression.expression, model);
        for (var i = 0; i < expression.options.length; i++) {
            var option = expression.options[i];
            if (evaluate(option.value, model)) {
                return evaluate(option.result, model);
            }
        }
        return evaluate(option.otherwise, model);
    },
    "f": function (expression, model) {
        var object = evaluate(expression.object, model);
        if (object) {
            return object[expression.field];
        }
        return null;
    },
    "i": function (expression, model) {
        return model.get(expression.identifier);
    },
    "b": function (expression, model) {
        return binary[expression.operator](evaluate(expression.left, model), evaluate(expression.right, model));
    },
    "u": function (expression, model) {
        return unary[expression.operator](evaluate(expression.argument, model));
    },
    "??": function (expression, model) {
        var left = evaluate(expression.left, model);
        if (left == null) {
            return evaluate(expression.right, model);
        }
        return left;
    },
    "&&": function (expression, model) {
        return evaluate(expression.left, model) && evaluate(expression.right, model);
    },
    "||": function (expression, model) {
        return evaluate(expression.left, model) || evaluate(expression.right, model);
    },
    "@": function (expression, model) {
        var sequence = evaluate(expression.sequence, model);
        if (sequence) {
            return sequence[evaluate(expression.key, model)];
        }
        return null;
    },
    "@:": function (expression, model) {
        var sequence = evaluate(expression.sequence, model);
        if (sequence) {
            return sequence.slice(evaluate(expression.start, model), evaluate(expression.end, model));
        }
        return null;
    },
    "s": function (expression, model) {
        return null;
    },
    "=": function (expression, model) {
        return null;
    }
};

var modifiers = {
    round: function (value) {
        return Math.round(value)
    },
    number: function (value) {
        var f = parseFloat(value);
        if (!isNaN(f)) {
            var s = f.toString();
            var p = s.indexOf('.');
            var i = p > 0 ? s.slice(0, p) : s;
            var n = i.length - 3;
            while (n > 0) {
                i = i.slice(0, n) + ',' + i.slice(n);
                n -= 3;
            }
            return p > 0 ? i + s.slice(p) : i;
        }
        return "";
    },
    date: function (value, format) {
        if (value != null) {
            var d = new Date(value);
            if (format === "f") {
                return d.getDate() + "/" +
                    (d.getMonth() + 1) + "/" +
                    d.getFullYear() + " " +
                    ("0" + d.getHours()).slice(-2) + ":" +
                    ("0" + d.getMinutes()).slice(-2);
            }

            return d.getDate() + "/" +
                (d.getMonth() + 1) + "/" +
                d.getFullYear();
        }
        return "";
    },
    sqrt: function (value) {
        return Math.sqrt(value);
    },
    pow: function (value) {
        return Math.pow(value);
    },
    sin: function (value) {
        return Math.sin(value);
    },
    cos: function (value) {
        return Math.cos(value);
    },
    tan: function (value) {
        return Math.tan(value);
    },
    asin: function (value) {
        return Math.asic(value);
    },
    acos: function (value) {
        return Math.acos(value);
    },
    atan: function (value) {
        return Math.atan(value);
    },
    PI: function () {
        return Math.PI;
    }
};

function extend(source, obj) {
    if (source) {
        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                obj[key] = source[key];
            }
        }
    }
    return obj;
}

function evaluate(expression, model) {
    while (expression && expression["!exp"]) {
        if (expression.$x) {
            // Expression loop
            expression = null;
        }
        else {
            expression.$x = true;
            var r = expressions[expression["!exp"]](expression, model);
            expression.$x = false;
            expression = r;
        }
    }
    if (expression && expression["!type"]) {
        var modifier = modifiers[expression["!type"]];
        if (modifier) {
            var init = expression["!init"];
            var args = [];
            if (init && init.length > 0) {
                args = init.map(function (x) { return evaluate(x, model); });
            }
            return modifier.apply(null, args);
        }
        return null;
    }
    return expression;
}

function isNotWhitespace(ch) {
    return !(ch === ' ' || ch === '\r' || ch === '\t' ||
    ch === '\n' || ch === '\v' || ch === '\u00A0');
}

function isNotIdentifier(ch) {
    return !('a' <= ch && ch <= 'z' ||
    'A' <= ch && ch <= 'Z' ||
    '_' === ch || ch === '$' || ch === '#');
}

function search(str, s, cb) {
    var i = 0;
    if (typeof s === "function") {
        cb = s;
    }
    else {
        i = s;
    }
    while (i < str.length && !cb(str[i])) {
        i++;
    }
    return i;
}

function Model(baseModel, model, parameters, env) {
    this.baseModel = baseModel;
    this.model = model;
    this.parameters = parameters;
    this.env = env;
}

Model.prototype.get = function (key) {
    if (key) {
        if (key[0] == '$') {
            var name = key.slice(1);
            var n = key.length === 1 ? 0 : parseInt(name);
            if (isNaN(n)) {
                if (this.env && this.env[name] != undefined) {
                    return this.env[name];
                }
                else if (this.baseModel) {
                    return this.baseModel.get(key);
                }
            }
            else if (this.parameters && n < this.parameters.length) {
                return evaluate(this.parameters[n].parameter, this.parameters[n].model);
            }
        }
        else {
            var v = null;
            if (typeof this.model === "object") {
                v = this.model[key];
            }
            if (v == null && this.baseModel != null) {
                return this.baseModel.get(key);
            }
            return v;
        }
    }

    return null;
};

function Rendo(template) {
    this.components = {};

    var components = oil.parse(template);

    for (var i = 0; i < components.length; i++) {
        var component = components[i];

        var name = component["!type"];
        if (name) {
            var render = component.render
                ? component.render
                : (component["!init"] && component["!init"].length > 0
                ? component["!init"][0]
                : (component["!ref"] || null));

            var scope = {};

            for (var key in component) {
                if (key[0] !== '!' && key !== "render") {
                    scope[key] = component[key];
                }
            }

            this.components[name] = {
                render: render,
                scope: scope
            };
        }
    }
}

Rendo.prototype.renderValue = function (value) {
    if (value != null && typeof value !== "object") {
        return "" + value;
    }
    return "";
};

Rendo.prototype.renderContents = function (contents, model) {
    var result = "";

    var s = 0;
    var o = contents.indexOf("{{");
    while (o >= s) {
        result += contents.slice(s, o);
        o += 2;

        var component = null;
        var fromModel = false;
        var i = search(contents, o, isNotWhitespace);

        if (contents[i] === ':' || contents[i] === '+') {
            fromModel = contents[i] == '+';
            o = i + 1;
            i = search(contents, o, isNotIdentifier);
            component = contents.slice(o, i);
        }

        // Reading to closing '}'
        var c = i;
        var count = 0;
        while (c < contents.length) {
            if (contents[c] === '{') {
                count++;
            }
            else if (contents[c] === '}') {
                if (count === 0) {
                    break;
                }
                count--;
            }
            c++;
        }

        var expressions = oil.parse(contents.slice(i, c));
        if (expressions.length > 0) {
            var models = evaluate(expressions[0], model);
            var parameters = expressions.slice(1).map(function (x) { return { model: model, parameter: x }; });

            if (!models || models.constructor !== Array) {
                models = [models];
            }

            for (var m = 0; m < models.length; m++) {
                var env = {
                    index: m,
                    first: m === 0,
                    last: m === models.length - 1
                };
                if (component) {
                    if (fromModel) {
                        var renderContents = model.get(component);
                        if (renderContents) {
                            result += this.renderContents(renderContents, new Model(model, models[m], [{model: model, parameter: models[m]}].concat(parameters), env));
                        }
                    }
                    else {
                        result += this.render(component, new Model(model, models[m]), [{model: model, parameter: models[m]}].concat(parameters), env);
                    }
                }
                else {
                    result += this.renderValue(models[m]);
                }
            }
        }
        else if (component) {
            // Render same model
            if (fromModel) {
                var renderContents = model.get(component);
                if (renderContents) {
                    result += this.renderContents(renderContents, model);
                }
            }
            else {
                result += this.render(component, model);
            }
        }

        if (c === contents.length || contents[c + 1] != "}") {
            return result;
        }

        s = c + 2;
        o = contents.indexOf("{{", s);
    }

    if (s < contents.length) {
        result += contents.slice(s);
    }

    return result;
};

Rendo.prototype.render = function (componentName, model, parameters) {
    if (componentName == null) {
        return this.renderValue(model);
    }

    var component = this.components[componentName];
    if (!component) {
        return "";
    }

    var contents = component.render;
    if (!contents) {
        return "";
    }

    var models;
    if (model) {
        if (model.constructor === Array) {
            models = model;
        }
        else {
            models = [model];
        }
    }
    else {
        models = [null];
    }

    var result = "";
    for (var m = 0; m < models.length; m++) {
        var model = models[m];
        var env = {
            index: m,
            first: m === 0,
            last: m === models.length - 1
        };
        if (!model || model.constructor !== Model) {
            model = new Model(null, model, null, env);
        }

        result += this.renderContents(contents, new Model(model, component.scope, parameters, env));
    }
    return result;
};

Rendo.render = function (template, component, model) {
    return new Rendo(template).render(component, model);
};

module.exports = Rendo;<|endoftext|>


<commit_before>(function(global) {
    'use strict';

    if (typeof module === 'object' && module.exports)
        module.exports = rendy;
    else
        global.rendy = rendy;

    /**
     * render template with data
     *
     * @param templ
     * @param view
     */
    function rendy(templ, data) {
        var str, regExp,
            result  = templ;

        check(templ, data);

        Object
            .keys(data)
            .forEach(function(param) {
                str     = data[param];
                regExp  = RegExp('{{\\s*' + param + '\\s*}}', 'g');
                result  = result.replace(regExp, str);
            });

        if (~result.indexOf('{{'))
            result.replace(/{{\s*.*\s*}}/, '');

        return result;
    }

    function check(templ, data) {
        if (typeof templ !== 'string')
            throw(Error('template should be string!'));

        if (typeof data !== 'object')
            throw(Error('data should be object!'));
    }
})(this);
<commit_msg>feature(rendy) add expr<commit_after>(function(global) {
    'use strict';

    if (typeof module === 'object' && module.exports)
        module.exports = rendy;
    else
        global.rendy = rendy;

    /**
     * render template with data
     *
     * @param templ
     * @param view
     */
    function rendy(templ, data) {
        var str, regExp, expr,
            result  = templ;

        check(templ, data);

        Object
            .keys(data)
            .forEach(function(param) {
                str     = data[param];
                expr    = '{{\\s*' + param + '\\s*}}';
                regExp  = RegExp(expr, 'g');
                result  = result.replace(regExp, str);
            });

        if (~result.indexOf('{{'))
            result.replace(/{{\s*.*\s*}}/, '');

        return result;
    }

    function check(templ, data) {
        if (typeof templ !== 'string')
            throw(Error('template should be string!'));

        if (typeof data !== 'object')
            throw(Error('data should be object!'));
    }
})(this);
<|endoftext|>


<commit_before>(function(){function r(r,n){var t={},i=function(r,n){var e=r.shift();if(!e)return n.leaf||!1;if(n.fixed&&e in n.fixed)return i(r,n.fixed[e]);if(n.partial){var f=n.partial,a=f.some(function(r){return r.ptn.test(e)?(n=r.node,!0):void 0});if(a)return i(r,n)}return n.var?(t[n.var.name]=e,i(r,n.var)):!1},e=i(r,n,t);return e?{fn:e,params:t}:!1}function n(){var n={},i={},e=function(r,n,t){var i,f=r.shift(),a=!!r.length;if(f)if("fixed"==f.type)n.fixed||(n.fixed={}),i=n.fixed[f.input]||(n.fixed[f.input]={}),a?e(r,i,t):i.leaf=t;else{if("var"!=f.type)throw Error("not yet!");i=n.var||(n.var={}),i.name=f.input.substr(1),a?e(r,i,t):i.leaf=t}};return n.add=function(r,n){e(t(r),i,n)},n.match=function(n){var t=n.split("/").filter(function(r){return!!r}),e=r(t,i);return e?e.fn.apply(e.fn,[e.params]):void 0},n}function t(r){var n=r.split("/").filter(function(r){return!!r}).map(function(r){var n=":"==r[0]?"var":"fixed";return{type:n,input:r}});return n}rhumb=n(),rhumb.create=n,rhumb.parse=t,rhumb._findInTree=r})();<commit_msg>remove dup<commit_after><|endoftext|>


<commit_before>// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var url = require('url');
var util = require('util');

var semver = require('semver');

///--- Helpers

function addProbes(dtrace, name) {
  if (!dtrace)
    return false;

  assert.ok(name);

  // id, requestid, user, user-agent, content-type, content-length
  dtrace.addProbe(name + '-start',
                  'int', 'char *', 'char *', 'char *', 'char *', 'int');

  // id, requestid, statusCode, content-type, content-length
  dtrace.addProbe(name + '-done',
		  'int', 'char *', 'int', 'char *', 'int', 'int');

  return true;
}

function fireProbeStart(dtrace, name, req) {
  if (!dtrace)
    return false;

  assert.ok(name);
  assert.ok(req);

  dtrace.fire(name + '-start', function probeStart() {
    return [
      req.connection.fd,
      req.id,
      (req.username || null),
      (req.userAgent || null),
      req.contentType,
      (req.contentLength || 0)
    ];
  });

  return true;
}

function fireProbeDone(dtrace, name, req, res) {
  if (!dtrace)
    return false;

  assert.ok(name);
  assert.ok(req);
  assert.ok(res);

  dtrace.fire(name + '-done', function probeDone() {
    return [
      req.connection.fd,
      req.id,
      res.code,
      (res.contentType || null),
      (res.contentLength || 0)
    ];
  });

  return true;
}

///--- API

/**
 * Constructor.
 *
 * Parameters accepted on the options object:
 *  -- Required:
 *    - log (Object) a bunyan instance.
 *    - url (String|RegExp) the url to match against with ':' params.
 *  -- Optional:
 *    - version (String) defaults to null.
 *    - method (String) defaults to GET.
 *    - name (String) defaults to :method_:url.
 *    - handlers ([Function]) an array of f(req, res, next).
 *
 * @param {Object} options parameterization object.
 * @throws {TypeError} on input error
 */
function Route(options) {
  if (typeof(options) !== 'object')
    throw new TypeError('options (Object) required');
  if (typeof(options.log) !== 'object')
    throw new TypeError('options.log (Object) required');
  if (options.handlers) {
    if (!Array.isArray(options.handlers))
      throw new TypeError('options.handlers must be an Array of Functions');
    options.handlers.forEach(function(h) {
      if (typeof(h) !== 'function')
        throw new TypeError('options.handlers must be an Array of Functions');
    });
  }

  EventEmitter.call(this);

  this.chain = options.handlers || [];
  this.method = options.method || 'GET';
  this.methods = [this.method];
  this.version = options.version ? options.version : false;
  if (this.version) {
    if (!Array.isArray(this.version))
      this.version = [this.version];

    this.version.forEach(function(v) {
      if (!semver.valid(v))
        throw new Error(v + ' is not a valid semantic version');
    });
  }

  var self = this;
  this.__defineGetter__('dtrace', function() {
    return options.dtrace || false;
  });

  this.__defineGetter__('name', function() {
    if (self._name)
      return self._name;

    var name = self.method + ' ' + self.url;
    if (self.version)
      name += ' (' + self.version + ')';

    self._name = name;
    return name;
  });

  this.__defineSetter__('name', function(n) {
    self._name = n;
  });

  this.__defineGetter__('probe', function() {
    if (self._probe)
      return self._probe;

    var n = self.name;
    self._probe = n.replace(/\s+/g, '-').replace(/\W+/g, '').toLowerCase();
    return self._probe;
  });

  this.__defineGetter__('url', function() {
    return self._url.toString();
  });

  this.__defineSetter__('url', function(u) {
    if (u instanceof RegExp) {
      self._url = u;
      self.pattern = u.source;
      return;
    }
    if (typeof(u) !== 'string')
      throw new TypeError('url must be a String');

    self._url = url.parse(u).pathname;
    self.pattern = '^';
    self.params = [];
    self._url.split('/').forEach(function(fragment) {
      if (!fragment.length)
        return;

      self.pattern += '\\/+';
      if (fragment.charAt(0) === ':') {
        self.pattern += '([a-zA-Z0-9-_~%!;@=+\\$\\*\\.]+)';
        self.params.push(fragment.slice(1));
      } else {
        self.pattern += fragment;
      }
    });
    if (self.pattern === '^')
      self.pattern += '\\/';
    self.pattern += '$';
  });

  this.name = options.name || false;
  this.url = options.url || options.path;
  this.log = options.log.child({name: self.name}, true);

  // Setup DTrace probes, if applicable
  addProbes(this.dtrace, this.probe);
  for (var i = 0; i <this.chain.length; i++) {
    this.chain[i]._name = this.chain[i].name  || (i + 1) + '';
    addProbes(this.dtrace, this.probe + '-' + this.chain[i]._name);
  }
}
util.inherits(Route, EventEmitter);
module.exports = Route;

/**
 * Checks if the given HTTP request object matches this route.
 *
 * Checks against method, URL and optionally version. If there is a match, an
 * object is returned with a set of key/value pairs that match the route's URL.
 *
 * For example, a route of /foo/:pet against a requested URL of /foo/dog would
 * return { pet: 'dog' }.  If the original URL in the route was a regex, you'll
 * just get back an array of regex matched params.
 *
 * @param {Object} req a node HTTP request object.
 * @return {Object} parameters parsed from the URL.
 * @throws {TypeError} on input error
 */
Route.prototype.matches = function matches(req) {
  if (!this.matchesMethod(req))
    return false;
  if (!this.matchesVersion(req))
    return false;

  return this.matchesUrl(req);
};

/**
 * Whether or not the route matches the given request's method.
 *
 * @param {Object} req an http request object.
 * @return {Boolean} if matches method.
 * @throws {TypeError} on input error.
 */
Route.prototype.matchesMethod = function matchesMethod(req) {
  if (typeof(req) !== 'object')
    throw new TypeError('request (Object) required');

  return req.method === this.method;
};

/**
 * Whether or not the route matches the given request's version (if this route
 * has versioning on).
 *
 * @param {Object} req an http request object.
 * @return {Boolean} if matches method.
 * @throws {TypeError} on input error.
 */
Route.prototype.matchesVersion = function matchesVersion(req) {
  if (typeof(req) !== 'object')
    throw new TypeError('request (Object) required');

  if (!this.version || req.version === '*')
    return true;

  if (!semver.maxSatisfying(this.version, req.version))
    return false;

  return true;
};

/**
 * Whether or not the route matches the given request's url.
 *
 * @param {Object} req an http request object.
 * @return {Object} parameters of the configured route -> url.
 * @throws {TypeError} on input error.
 */
Route.prototype.matchesUrl = function matchesUrl(req) {
  if (typeof(req) !== 'object')
    throw new TypeError('request (Object) required');

  var re = new RegExp(this.pattern);
  var result = re.exec(req.path);
  if (!result)
    return false;

  var params = {};
  var i = 0;
  if (this.params && this.params.length) {
    this.params.forEach(function(p) {
      if (++i < result.length)
        params[p] = decodeURIComponent(result[i]);
    });
  } else {
    if (this._url instanceof RegExp) {
      // Don't return an array, as we want to enable all the downstream
      // plugins to append in other params
      for (i = 0; i < result.length; i++) {
        if (i === 0) // capture groups start at 1
          continue;

        params[(i - 1)] = result[i];
      }
    }
  }

  return params;
};

/**
 * Runs the set of handlers registered to this route in order, and emits
 * a 'done(req, res)' when the route is finished (or request ended).
 *
 * @param {Object} req http.Request.
 * @param {Object} res http.Response.
 */
Route.prototype.run = function run(req, res) {
  assert.ok(req);
  assert.ok(res);

  var chain = this.chain;
  var i = -1;
  var log = this.log.child({ req_id: req.id }, true);
  var self = this;

  function next(err) {
    // The goofy checks here are to make sure we fire the DTrace probes after
    // an error might have been sent, as in a handler return next(new Error)
    // is basically shorthand for sending an error via res.send(), so we
    // do that before firing the dtrace probe (namely so the status codes
    // get updated in the response).
    var done = false;
    if (err) {
      log.trace({err: err}, 'next(err=%s)', err.name);

      res.send(err);
      done = true;
    }

    // Callers can stop the chain from proceding if they do return next(false);
    // This is useful for non-errors, but where a response was sent and you
    // don't want the chain to keep going
    if (err === false)
      done = true;

    // Fire DTrace done for the "sub runner".
    if ((i + 1) > 0 && chain[i])
      fireProbeDone(self.dtrace, self.probe + '-' + chain[i]._name, req, res);

    if (!done && chain[++i]) {
        log.trace('running %s', chain[i].name);

      fireProbeStart(self.dtrace, self.probe + '-' + chain[i]._name, req);
      return chain[i].call(self, req, res, next);
    }

    // This is the route -done dtrace probe
    fireProbeDone(self.dtrace, self.probe, req, res);

    return self.emit('done', req, res);
  }

  log.trace({req: req}, 'starting request chain');

  // DTrace start for the route
  fireProbeStart(this.dtrace, this.probe, req);
  return next();
};

/**
 * Installs a list of handlers to run _before_ the "normal" handlers.
 *
 * @param {Array} chain an array of Function(req, res, next);
 * @throws {TypeError} on input error.
 */
Route.prototype.use = function use(chain) {
  if (!Array.isArray(chain))
    throw new TypeError('chain ([Function]) required');

  var self = this;
  chain.forEach(function(h) {
    self.chain.push(h);
    h._name = h.name  || self.chain.length + '';
    addProbes(self.dtrace, self.probe + '-' + h._name);
  });

  return this;
};

/**
 * Returns a string representation of this route for debugging.
 *
 * Returned string is :name: :method :url (version=:version)
 * Note name and version may not be present if they were not specified at
 * construction time.
 *
 * @return {String} in the form indicated above.
 */
Route.prototype.toString = function toString() {
  assert.ok(this.method);
  assert.ok(this.url);

  var str = this.method + ' ' + this.url;
  var opts = [];
  if (this.version)
    opts.push('version=' + this.version);
  if (opts.length)
    str += ' (' + opts.join(', ') + ')';

  return str;
};

<commit_msg>minor change to bunyan logger in route.js<commit_after>// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var url = require('url');
var util = require('util');

var semver = require('semver');

///--- Helpers

function addProbes(dtrace, name) {
  if (!dtrace)
    return false;

  assert.ok(name);

  // id, requestid, user, user-agent, content-type, content-length
  dtrace.addProbe(name + '-start',
                  'int', 'char *', 'char *', 'char *', 'char *', 'int');

  // id, requestid, statusCode, content-type, content-length
  dtrace.addProbe(name + '-done',
		  'int', 'char *', 'int', 'char *', 'int', 'int');

  return true;
}

function fireProbeStart(dtrace, name, req) {
  if (!dtrace)
    return false;

  assert.ok(name);
  assert.ok(req);

  dtrace.fire(name + '-start', function probeStart() {
    return [
      req.connection.fd,
      req.id,
      (req.username || null),
      (req.userAgent || null),
      req.contentType,
      (req.contentLength || 0)
    ];
  });

  return true;
}

function fireProbeDone(dtrace, name, req, res) {
  if (!dtrace)
    return false;

  assert.ok(name);
  assert.ok(req);
  assert.ok(res);

  dtrace.fire(name + '-done', function probeDone() {
    return [
      req.connection.fd,
      req.id,
      res.code,
      (res.contentType || null),
      (res.contentLength || 0)
    ];
  });

  return true;
}

///--- API

/**
 * Constructor.
 *
 * Parameters accepted on the options object:
 *  -- Required:
 *    - log (Object) a bunyan instance.
 *    - url (String|RegExp) the url to match against with ':' params.
 *  -- Optional:
 *    - version (String) defaults to null.
 *    - method (String) defaults to GET.
 *    - name (String) defaults to :method_:url.
 *    - handlers ([Function]) an array of f(req, res, next).
 *
 * @param {Object} options parameterization object.
 * @throws {TypeError} on input error
 */
function Route(options) {
  if (typeof(options) !== 'object')
    throw new TypeError('options (Object) required');
  if (typeof(options.log) !== 'object')
    throw new TypeError('options.log (Object) required');
  if (options.handlers) {
    if (!Array.isArray(options.handlers))
      throw new TypeError('options.handlers must be an Array of Functions');
    options.handlers.forEach(function(h) {
      if (typeof(h) !== 'function')
        throw new TypeError('options.handlers must be an Array of Functions');
    });
  }

  EventEmitter.call(this);

  this.chain = options.handlers || [];
  this.method = options.method || 'GET';
  this.methods = [this.method];
  this.version = options.version ? options.version : false;
  if (this.version) {
    if (!Array.isArray(this.version))
      this.version = [this.version];

    this.version.forEach(function(v) {
      if (!semver.valid(v))
        throw new Error(v + ' is not a valid semantic version');
    });
  }

  var self = this;
  this.__defineGetter__('dtrace', function() {
    return options.dtrace || false;
  });

  this.__defineGetter__('name', function() {
    if (self._name)
      return self._name;

    var name = self.method + ' ' + self.url;
    if (self.version)
      name += ' (' + self.version + ')';

    self._name = name;
    return name;
  });

  this.__defineSetter__('name', function(n) {
    self._name = n;
  });

  this.__defineGetter__('probe', function() {
    if (self._probe)
      return self._probe;

    var n = self.name;
    self._probe = n.replace(/\s+/g, '-').replace(/\W+/g, '').toLowerCase();
    return self._probe;
  });

  this.__defineGetter__('url', function() {
    return self._url.toString();
  });

  this.__defineSetter__('url', function(u) {
    if (u instanceof RegExp) {
      self._url = u;
      self.pattern = u.source;
      return;
    }
    if (typeof(u) !== 'string')
      throw new TypeError('url must be a String');

    self._url = url.parse(u).pathname;
    self.pattern = '^';
    self.params = [];
    self._url.split('/').forEach(function(fragment) {
      if (!fragment.length)
        return;

      self.pattern += '\\/+';
      if (fragment.charAt(0) === ':') {
        self.pattern += '([a-zA-Z0-9-_~%!;@=+\\$\\*\\.]+)';
        self.params.push(fragment.slice(1));
      } else {
        self.pattern += fragment;
      }
    });
    if (self.pattern === '^')
      self.pattern += '\\/';
    self.pattern += '$';
  });

  this.name = options.name || false;
  this.url = options.url || options.path;
  this.log = options.log.child({route_name: self.name}, true);

  // Setup DTrace probes, if applicable
  addProbes(this.dtrace, this.probe);
  for (var i = 0; i <this.chain.length; i++) {
    this.chain[i]._name = this.chain[i].name  || (i + 1) + '';
    addProbes(this.dtrace, this.probe + '-' + this.chain[i]._name);
  }
}
util.inherits(Route, EventEmitter);
module.exports = Route;

/**
 * Checks if the given HTTP request object matches this route.
 *
 * Checks against method, URL and optionally version. If there is a match, an
 * object is returned with a set of key/value pairs that match the route's URL.
 *
 * For example, a route of /foo/:pet against a requested URL of /foo/dog would
 * return { pet: 'dog' }.  If the original URL in the route was a regex, you'll
 * just get back an array of regex matched params.
 *
 * @param {Object} req a node HTTP request object.
 * @return {Object} parameters parsed from the URL.
 * @throws {TypeError} on input error
 */
Route.prototype.matches = function matches(req) {
  if (!this.matchesMethod(req))
    return false;
  if (!this.matchesVersion(req))
    return false;

  return this.matchesUrl(req);
};

/**
 * Whether or not the route matches the given request's method.
 *
 * @param {Object} req an http request object.
 * @return {Boolean} if matches method.
 * @throws {TypeError} on input error.
 */
Route.prototype.matchesMethod = function matchesMethod(req) {
  if (typeof(req) !== 'object')
    throw new TypeError('request (Object) required');

  return req.method === this.method;
};

/**
 * Whether or not the route matches the given request's version (if this route
 * has versioning on).
 *
 * @param {Object} req an http request object.
 * @return {Boolean} if matches method.
 * @throws {TypeError} on input error.
 */
Route.prototype.matchesVersion = function matchesVersion(req) {
  if (typeof(req) !== 'object')
    throw new TypeError('request (Object) required');

  if (!this.version || req.version === '*')
    return true;

  if (!semver.maxSatisfying(this.version, req.version))
    return false;

  return true;
};

/**
 * Whether or not the route matches the given request's url.
 *
 * @param {Object} req an http request object.
 * @return {Object} parameters of the configured route -> url.
 * @throws {TypeError} on input error.
 */
Route.prototype.matchesUrl = function matchesUrl(req) {
  if (typeof(req) !== 'object')
    throw new TypeError('request (Object) required');

  var re = new RegExp(this.pattern);
  var result = re.exec(req.path);
  if (!result)
    return false;

  var params = {};
  var i = 0;
  if (this.params && this.params.length) {
    this.params.forEach(function(p) {
      if (++i < result.length)
        params[p] = decodeURIComponent(result[i]);
    });
  } else {
    if (this._url instanceof RegExp) {
      // Don't return an array, as we want to enable all the downstream
      // plugins to append in other params
      for (i = 0; i < result.length; i++) {
        if (i === 0) // capture groups start at 1
          continue;

        params[(i - 1)] = result[i];
      }
    }
  }

  return params;
};

/**
 * Runs the set of handlers registered to this route in order, and emits
 * a 'done(req, res)' when the route is finished (or request ended).
 *
 * @param {Object} req http.Request.
 * @param {Object} res http.Response.
 */
Route.prototype.run = function run(req, res) {
  assert.ok(req);
  assert.ok(res);

  var chain = this.chain;
  var i = -1;
  var log = this.log.child({ req_id: req.id }, true);
  var self = this;

  function next(err) {
    // The goofy checks here are to make sure we fire the DTrace probes after
    // an error might have been sent, as in a handler return next(new Error)
    // is basically shorthand for sending an error via res.send(), so we
    // do that before firing the dtrace probe (namely so the status codes
    // get updated in the response).
    var done = false;
    if (err) {
      log.trace({err: err}, 'next(err=%s)', err.name);

      res.send(err);
      done = true;
    }

    // Callers can stop the chain from proceding if they do return next(false);
    // This is useful for non-errors, but where a response was sent and you
    // don't want the chain to keep going
    if (err === false)
      done = true;

    // Fire DTrace done for the "sub runner".
    if ((i + 1) > 0 && chain[i])
      fireProbeDone(self.dtrace, self.probe + '-' + chain[i]._name, req, res);

    if (!done && chain[++i]) {
        log.trace('running %s', chain[i].name);

      fireProbeStart(self.dtrace, self.probe + '-' + chain[i]._name, req);
      return chain[i].call(self, req, res, next);
    }

    // This is the route -done dtrace probe
    fireProbeDone(self.dtrace, self.probe, req, res);

    return self.emit('done', req, res);
  }

  log.trace({req: req}, 'starting request chain');

  // DTrace start for the route
  fireProbeStart(this.dtrace, this.probe, req);
  return next();
};

/**
 * Installs a list of handlers to run _before_ the "normal" handlers.
 *
 * @param {Array} chain an array of Function(req, res, next);
 * @throws {TypeError} on input error.
 */
Route.prototype.use = function use(chain) {
  if (!Array.isArray(chain))
    throw new TypeError('chain ([Function]) required');

  var self = this;
  chain.forEach(function(h) {
    self.chain.push(h);
    h._name = h.name  || self.chain.length + '';
    addProbes(self.dtrace, self.probe + '-' + h._name);
  });

  return this;
};

/**
 * Returns a string representation of this route for debugging.
 *
 * Returned string is :name: :method :url (version=:version)
 * Note name and version may not be present if they were not specified at
 * construction time.
 *
 * @return {String} in the form indicated above.
 */
Route.prototype.toString = function toString() {
  assert.ok(this.method);
  assert.ok(this.url);

  var str = this.method + ' ' + this.url;
  var opts = [];
  if (this.version)
    opts.push('version=' + this.version);
  if (opts.length)
    str += ' (' + opts.join(', ') + ')';

  return str;
};

<|endoftext|>


<commit_before>// Partial 'sham' to work around ie8s lack of es5 //////////////////////////////////////////////
// When IE8 support is no longer needed, all these can be dropped in favour of the es5 methods.

exports.getPrototypeOf = function getPrototypeOf(obj) {
	if (Object.getPrototypeOf) {
		var proto = Object.getPrototypeOf(obj);

		// to avoid bad shams...
		if (proto !== obj) return proto;
	}

	// this is what most shams do, but sometimes it's wrong.
	if (obj.constructor && obj.constructor.prototype && obj.constructor.prototype !== obj) {
		return obj.constructor.prototype;
	}

	// this works only if we've been kind enough to supply a superclass property
	// (which we do when we extend classes).
	if (obj.constructor && obj.constructor.superclass) {
		return obj.constructor.superclass.prototype;
	}

	// can't find a good prototype.
	return null;
};

var defineProperty = function(obj, prop, descriptor) {
	obj[prop] = descriptor.value;
};
if (Object.defineProperty) {
	try {
		// IE8 throws an error here.
		Object.defineProperty({}, 'x', {});
		defineProperty = Object.defineProperty;
	} catch (e) {}
}
exports.defineProperty = defineProperty;

exports.create = Object.create || function(proto, descriptors) {
	var myConstructor = function() {};
	myConstructor.prototype = proto;

	var result = new myConstructor();

	var keys = Object.keys(descriptors);
	for (var i = 0; i < keys.length; ++i) {
		var key = keys[i];
		defineProperty(result, key, descriptors[key]);
	}

	return result;
};

<commit_msg>ES5 sham incorrectly adds a dunder proto property on newly created objects. This causes ES5 sham to return incorrect value from the Object.getPrototypeOf method. This in turn makes Meta events fail to trigger when used in IE8 and in the presence of the ES5 shim/sham files<commit_after>// Partial 'sham' to work around ie8s lack of es5 //////////////////////////////////////////////
// When IE8 support is no longer needed, all these can be dropped in favour of the es5 methods.

exports.getPrototypeOf = function getPrototypeOf(obj) {
	if (Object.getPrototypeOf) {
		var proto = Object.getPrototypeOf(obj);

		// to avoid bad shams...
		if (proto !== obj) return proto;
	}

	// this is what most shams do, but sometimes it's wrong.
	if (obj.constructor && obj.constructor.prototype && obj.constructor.prototype !== obj) {
		return obj.constructor.prototype;
	}

	// this works only if we've been kind enough to supply a superclass property
	// (which we do when we extend classes).
	if (obj.constructor && obj.constructor.superclass) {
		return obj.constructor.superclass.prototype;
	}

	// can't find a good prototype.
	return null;
};

var defineProperty = function(obj, prop, descriptor) {
	obj[prop] = descriptor.value;
};
if (Object.defineProperty) {
	try {
		// IE8 throws an error here.
		Object.defineProperty({}, 'x', {});
		defineProperty = Object.defineProperty;
	} catch (e) {}
}
exports.defineProperty = defineProperty;

exports.create = function create(proto, descriptors) {
	var result;

	if(Object.create) {
		result = Object.create(proto, descriptors);

		var dunderProtoPassedIn = (proto && proto.__proto__) || (descriptors && descriptors.__proto__);

		if(result.__proto__ && !dunderProtoPassedIn) {
			//ES5 shim added this and it's a lie so delete it.
			delete result.__proto__;
		}
	} else {
		var myConstructor = function() {};
		myConstructor.prototype = proto;

		result = new myConstructor();

		var keys = Object.keys(descriptors);
		for (var i = 0; i < keys.length; ++i) {
			var key = keys[i];
			defineProperty(result, key, descriptors[key]);
		}
	}

	return result;
};
<|endoftext|>


<commit_before>/*
 * node-siege
 * https://github.com/npr/node-siege
 *
 * Copyright (c) 2012 johnymonster
 * Licensed under the MIT license.
 */
var exec = require('child_process').exec
  , async = require('async');

module.exports = function siege(options, cb) {
    var args = options;
    if(typeof options !== 'string') {
        args = buildOptionString(options);
    }

    if(args !== false && args != '') {
        async.waterfall([
          siegeExists,
          async.apply(siegeExec, args)
        ], function(err, results){
            cb(err,results);
        });
    } else {
        cb(new Error('Unable to parse options'));
    }
};

function siegeExists(cb) {
    exec('which siege', function(error, stdout, stderr){
        if(error) {
            console.error('please install siege. http://www.joedog.org/siege-home/');
        }
        cb(error);
    })
}

function siegeExec(args, cb) {
    exec('siege ' + args, function(error, stdout, stderr){
        cb(error, stderr, stdout);
    });
}

/**
 * At some point allow for an object of options
 * currently not needed for this project
 * @param options
 */
function buildOptionString(options) {
    return false;
}<commit_msg>Renaming functions, didn't like the old ones.<commit_after>/*
 * node-siege
 * https://github.com/npr/node-siege
 *
 * Copyright (c) 2012 johnymonster
 * Licensed under the MIT license.
 */
var exec = require('child_process').exec
  , async = require('async');

module.exports = function siege(options, cb) {
    var args = options;
    if(typeof options !== 'string') {
        args = optionsToString(options);
    }

    if(args !== false && args != '') {
        async.waterfall([
          exists,
          async.apply(run, args)
        ], function(err, results){
            cb(err,results);
        });
    } else {
        cb(new Error('Unable to parse options'));
    }
};

function exists(cb) {
    exec('which siege', function(error, stdout, stderr){
        if(error) {
            console.error('please install siege. http://www.joedog.org/siege-home/');
        }
        cb(error);
    })
}

function run(args, cb) {
    exec('siege ' + args, function(error, stdout, stderr){
        cb(error, stderr, stdout);
    });
}

/**
 * At some point allow for an object of options
 * currently not needed for this project
 * @param options
 */
function optionsToString(options) {
    return false;
}<|endoftext|>


<commit_before>const superagent = require('superagent');

module.exports = (basePath, authorize) => {
  /**
   * Get all available sites
   * @return {Promise}
   */
  const getAll = () => {
    return authorize()
      .then(token => {
        return new Promise((resolve, reject) => {
          superagent
            .get(`${basePath}/sites`)
            .set('Authorization', `Bearer ${token}`)
            .end((err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve(res.body.items);
              }
            });
        });
      });
  };

  /**
   * Get site by name
   * @param  {string} name
   * @return {Promise}
   */
  const getByName = (name) => {
    return getAll()
            .then(sites => sites.filter((site) => site.name === name)[0]);
  }

  /**
   * Get site by Id
   * @param  {String} id
   * @return {Promise}
   */
  const getById = (id) => {
    return authorize()
      .then(token => {
        return new Promise((resolve, reject) => {
          superagent
            .get(`${basePath}/sites/${id}`)
            .set('Authorization', `Bearer ${token}`)
            .end((err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve(res.body);
              }
            });
        });
      });
  }

  return {
    getAll,
    getByName,
    getById
  };
}
<commit_msg>update site.js to support new api wrapper structure<commit_after>module.exports = (basePath, authorize) => {
  const superagent = require('superagent');
  const req = require('../util/req')(authorize);
  const util = require('../util/util');

  /**
   * Get site(s)
   *
   * Possible options:
   * -----------------
   * `siteId` (optional) - ID of the site to be fetched
   * `siteName` (optional) - name of the site to be fetched
   *
   * Get all sites in the account if no options provided,
   * `siteId` has priority over the `siteName` otherwise.
   *
   * @param  {Object} options
   * @return {Promise}
   */
  const get = ({siteId, siteName}) => {
    var path = `${basePath}/sites`;

    if (siteId) {
      path = `${basePath}/sites/${siteId}`
    }

    if (!siteId && siteName) {
      return req.get(path).then(sites => {
        return util.getByName(sites, siteName);
      });
    } else {
      return req.get(path);
    }
  };

  /**
   * Site Scripts
   * @type {Object}
   */
  const scripts = {
    /**
     * Get Site Script(s)
     *
     * Possible options:
     * -----------------
     * `siteId` (optional if `siteName` provided) - ID of the site to be fetched
     * `siteName` (optional if `siteId` provided) - name of the site to be fetched
     *
     * Get all Site Scripts of the given site;
     * `siteId` has priority over the `siteName`.
     *
     * @param  {Object} options
     * @return {Promise}
     */
    get({siteId, siteName}) {
      if (!siteId && !siteName) {
        return Promise.reject({ error: '`siteId` or `siteName` must be provided!' });
      }

      if (!siteId && siteName) {
        return req.get(`${basePath}/sites`).then(sites => {
          var site = util.getByName(sites, siteName);
          return req.get(util.getScriptPath(basePath, site.id, ''));
        });
      } else {
        return req.get(util.getScriptPath(basePath, siteId, ''));
      }
    },

    /**
     * Update Site Script
     *
     * Possible options:
     * -----------------
     * `siteId` (optional if `siteName` provided) - ID of the site to be fetched
     * `siteName` (optional if `siteId` provided) - name of the site to be fetched
     * `scriptId` (optional if `scriptName` provided) - ID of the script to be fetched
     * `scriptName` (optional if `scriptId` provided) - name of the script to be fetched
     *
     * Update Site Script for the given site and of the given ID/Name;
     * `siteId` has priority over the `siteName`.
     * `scriptId` has priority over the `scriptName`.
     *
     * @param  {Object} options
     * @return {Promise}
     */
    update(options) {
      let {siteId, siteName, scriptId, scriptName, name, description, content} = options;

      if (!siteId && !siteName) {
        return Promise.reject({ error: '`siteId` or `siteName` must be provided!' });
      }

      if (!scriptId && !scriptName) {
        return Promise.reject({ error: '`scriptId` or `scriptName` must be provided!' });
      }

      let updatedData = util.getUpdatedData(options);
      let promise;
      let path;

      if (!siteId && siteName) {
        promise = get().then(sites => getByName(sites, siteName))

        return promise
          .then(site => {
            if (!scriptId && scriptName) {
              return this.get({siteId: site.id})
                .then(scripts => getByName(scripts, scriptName))
                .then(script => {
                  return req.put(util.getScriptPath(basePath, site.id, script.id));
                });
            } else {
              return req.put(util.getScriptPath(basePath, site.id, scriptId));
            }
          });
      } else {
        if (!scriptId && scriptName) {
          return this.get({siteId: siteId})
            .then(scripts => getByName(scripts, scriptName))
            .then(script => {
              return req.put(util.getScriptPath(basePath, siteId, script.id));
            });
        } else {
          return req.put(util.getScriptPath(basePath, siteId, scriptId));
        }
      }
    }
  };

  /**
   * Site Actions
   * @type {Object}
   */
  const actions = {
    /**
     * Get Site Action(s)
     *
     * Possible options:
     * -----------------
     * `siteId` (optional if `siteName` provided) - ID of the site to be fetched
     * `siteName` (optional if `siteId` provided) - name of the site to be fetched
     *
     * Get all Site Scripts of the given site;
     * `siteId` has priority over the `siteName`.
     *
     * @param  {Object} options
     * @return {Promise}
     */
    get({siteId, siteName}) {
      var path;

      if (siteId) {
        path = `${basePath}/sites/${siteId}/sandbox/actions`;
      }

      if (!siteId && siteName) {
        return req.get(path).then(sites => {
          return util.getByName(sites, siteName);
        });
      } else {
        return req.get(path);
      }
    }
  };

  // exports
  return {
    get,
    scripts,
    actions
  };
};
<|endoftext|>


<commit_before>var Frame = require("./frame");

/** Unique id generator */
function genId(type) {
  return (type ? type : 'id') + Math.floor(Math.random() * 999999999999999999999);
}

/** Send frame with socket */
function sendFrame(socket, _frame) {
  var frame_str = _frame.toString();
  socket.send(frame_str);
  return true;
}

/** Parse single command  */
function parseCommand(data) {
  var command,
    str = data.toString('utf8', 0, data.length);
  command = str.split('\n');
  return command[0];
}
/** Parse headers */
function parseHeaders(raw_headers) {
  var headers = {},
    headers_split = raw_headers.split('\n');

  for (var i = 0; i < headers_split.length; i++) {
    var header = headers_split[i].split(':');
    if (header.length > 1) {
      var key = header.shift().trim();
      headers[key] = header.join(':').trim();
      continue;
    }
    if (header[1]) {
      headers[header[0].trim()] = header[1].trim();
    }
  }
  return headers;
}

function trimNull(a) {
  var c = a.indexOf('\0');
  if (c>-1) {
    return a.substr(0, c);
  }
  return a;
}

var StompUtils = {
  genId: genId,
  tokenizeDestination: function (dest) {
    return dest.substr(dest.indexOf('/') + 1).split(".");
  },
  sendCommand: function (socket, command, headers, body, want_receipt) {
    if (headers === undefined) {
      headers = {};
    }
    if (want_receipt === true) {
      headers.receipt = genId("r");
    }
    var frame = new Frame({
      'command': command,
      'headers': headers,
      'body': body
    });
    sendFrame(socket, frame);
    return frame;
  },
  sendFrame: sendFrame,
  parseFrame: function (chunk) {
    if (chunk === undefined) {
      return null;
    }

    var command = parseCommand(chunk);
    var data = chunk.slice(command.length + 1, chunk.length);
    data = data.toString('utf8', 0, data.length);

    var the_rest = data.split('\n\n');
    var headers = parseHeaders(the_rest[0]);
    var body = the_rest.slice(1, the_rest.length);

    if ('content-length' in headers) {
      headers.bytes_message = true;
    }

    return new Frame({
      command: command,
      headers: headers,
      body: trimNull(body.toString())
    });
  }
};

var ServerFrame = {
  CONNECTED: function (socket, heartbeat) {
    StompUtils.sendCommand(socket, "CONNECTED", {
      session: socket.sessionId,
      server: "STOMP-JS/0.0.1",
      'heart-beat': heartbeat,
      version: '1.1'
    });
  },
  MESSAGE: function (socket, frame) {
    StompUtils.sendCommand(socket, "MESSAGE", frame.header, frame.body);
  },
  RECEIPT: function (socket, receipt) {
    StompUtils.sendCommand(socket, "RECEIPT", {'receipt-id': receipt});
  },
  ERROR: function (socket, message, description) {
    var len = description !== undefined ? description.length : 0;
    var headers = {
      message: message,
      "content-type": "text/plain",
      "content-length": len
    };
    if (receipt) {
      headers['receipt-id'] = receipt;
    }
    StompUtils.sendCommand(socket, 'ERROR', headers, description);
  }
};

function FrameHandler(stompServer) {
  this.CONNECT = function (socket, frame) {
    var rawHeartBeat = frame.headers['heart-beat'];
    var parts = ['0', '0'];
    if (rawHeartBeat) {
      parts = rawHeartBeat.split(",");
    }

    if (stompServer.onClientConnected(socket, {hearBeat: parts, headers: frame.headers})) {
      rawHeartBeat = stompServer.heartBeatConfig.server + "," + stompServer.heartBeatConfig.client;
      ServerFrame.CONNECTED(socket, rawHeartBeat);
    } else {
      ServerFrame.ERROR(socket, "CONNECTION ERROR", "CONNECTION ERROR");
    }
  };
  this.DISCONNECT = function (socket, frame) {
    var receipt = frame.headers.receipt;
    if (stompServer.onDisconnect(socket, receipt)) {
      ServerFrame.RECEIPT(socket, receipt);
    } else {
      ServerFrame.ERROR(socket, "DISCONNECT ERROR", receipt);
    }
  };
  this.SUBSCRIBE = function (socket, frame) {
    var dest = frame.headers.destination;
    var ack = "auto" || frame.headers.ack;
    if (!stompServer.onSubscribe(socket, {dest: dest, ack: ack, id: frame.headers.id})) {
      ServerFrame.ERROR(socket, "SUBSCRIBE ERROR", dest);
    }
  };
  this.UNSUBSCRIBE = function (socket, frame) {
    var id = frame.headers.id;
    if (!stompServer.onUnsubscribe(socket, id)) {
      ServerFrame.ERROR(socket, "UNSUBSCRIBE ERROR", id);
    }
  };
  this.SEND = function (socket, frame) {
    var dest = frame.headers.destination;
    var receipt = frame.headers.receipt;
    stompServer.onSend(socket, {dest: dest, frame: frame}, function (res) {
      if (res && receipt) {
        ServerFrame.RECEIPT(socket, receipt);
      } else if (!res) {
        ServerFrame.ERROR(socket, "Send error", frame);
      }
    });
  };
}

module.exports = {
  StompUtils: StompUtils,
  ServerFrame: ServerFrame,
  FrameHandler: FrameHandler,
  genId: genId
};
<commit_msg>Check for frame properties.<commit_after>var Frame = require("./frame");

/** Unique id generator */
function genId(type) {
  return (type ? type : 'id') + Math.floor(Math.random() * 999999999999999999999);
}

/** Send frame with socket */
function sendFrame(socket, _frame) {
  var frame_str = null;
  if (!_frame.hasOwnProperty('toString')) {
    var frame = new Frame({
      'command': _frame.command,
      'headers': _frame.headers,
      'body': _frame.body
    });
    frame_str = frame.toString();
  } else {
    frame_str = _frame.toString();
  }
  socket.send(frame_str);
  return true;
}

/** Parse single command  */
function parseCommand(data) {
  var command,
    str = data.toString('utf8', 0, data.length);
  command = str.split('\n');
  return command[0];
}
/** Parse headers */
function parseHeaders(raw_headers) {
  var headers = {},
    headers_split = raw_headers.split('\n');

  for (var i = 0; i < headers_split.length; i++) {
    var header = headers_split[i].split(':');
    if (header.length > 1) {
      var key = header.shift().trim();
      headers[key] = header.join(':').trim();
      continue;
    }
    if (header[1]) {
      headers[header[0].trim()] = header[1].trim();
    }
  }
  return headers;
}

function trimNull(a) {
  var c = a.indexOf('\0');
  if (c>-1) {
    return a.substr(0, c);
  }
  return a;
}

var StompUtils = {
  genId: genId,
  tokenizeDestination: function (dest) {
    return dest.substr(dest.indexOf('/') + 1).split(".");
  },
  sendCommand: function (socket, command, headers, body, want_receipt) {
    if (headers === undefined) {
      headers = {};
    }
    if (want_receipt === true) {
      headers.receipt = genId("r");
    }
    var frame = new Frame({
      'command': command,
      'headers': headers,
      'body': body
    });
    sendFrame(socket, frame);
    return frame;
  },
  sendFrame: sendFrame,
  parseFrame: function (chunk) {
    if (chunk === undefined) {
      return null;
    }

    var command = parseCommand(chunk);
    var data = chunk.slice(command.length + 1, chunk.length);
    data = data.toString('utf8', 0, data.length);

    var the_rest = data.split('\n\n');
    var headers = parseHeaders(the_rest[0]);
    var body = the_rest.slice(1, the_rest.length);

    if ('content-length' in headers) {
      headers.bytes_message = true;
    }

    return new Frame({
      command: command,
      headers: headers,
      body: trimNull(body.toString())
    });
  }
};

var ServerFrame = {
  CONNECTED: function (socket, heartbeat) {
    StompUtils.sendCommand(socket, "CONNECTED", {
      session: socket.sessionId,
      server: "STOMP-JS/0.0.1",
      'heart-beat': heartbeat,
      version: '1.1'
    });
  },
  MESSAGE: function (socket, frame) {
    StompUtils.sendCommand(socket, "MESSAGE", _frame.header, _frame.body);
  },
  RECEIPT: function (socket, receipt) {
    StompUtils.sendCommand(socket, "RECEIPT", {'receipt-id': receipt});
  },
  ERROR: function (socket, message, description) {
    var len = description !== undefined ? description.length : 0;
    var headers = {
      message: message,
      "content-type": "text/plain",
      "content-length": len
    };
    if (receipt) {
      headers['receipt-id'] = receipt;
    }
    StompUtils.sendCommand(socket, 'ERROR', headers, description);
  }
};

function FrameHandler(stompServer) {
  this.CONNECT = function (socket, frame) {
    var rawHeartBeat = frame.headers['heart-beat'];
    var parts = ['0', '0'];
    if (rawHeartBeat) {
      parts = rawHeartBeat.split(",");
    }

    if (stompServer.onClientConnected(socket, {hearBeat: parts, headers: frame.headers})) {
      rawHeartBeat = stompServer.heartBeatConfig.server + "," + stompServer.heartBeatConfig.client;
      ServerFrame.CONNECTED(socket, rawHeartBeat);
    } else {
      ServerFrame.ERROR(socket, "CONNECTION ERROR", "CONNECTION ERROR");
    }
  };
  this.DISCONNECT = function (socket, frame) {
    var receipt = frame.headers.receipt;
    if (stompServer.onDisconnect(socket, receipt)) {
      ServerFrame.RECEIPT(socket, receipt);
    } else {
      ServerFrame.ERROR(socket, "DISCONNECT ERROR", receipt);
    }
  };
  this.SUBSCRIBE = function (socket, frame) {
    var dest = frame.headers.destination;
    var ack = "auto" || frame.headers.ack;
    if (!stompServer.onSubscribe(socket, {dest: dest, ack: ack, id: frame.headers.id})) {
      ServerFrame.ERROR(socket, "SUBSCRIBE ERROR", dest);
    }
  };
  this.UNSUBSCRIBE = function (socket, frame) {
    var id = frame.headers.id;
    if (!stompServer.onUnsubscribe(socket, id)) {
      ServerFrame.ERROR(socket, "UNSUBSCRIBE ERROR", id);
    }
  };
  this.SEND = function (socket, frame) {
    var dest = frame.headers.destination;
    var receipt = frame.headers.receipt;
    stompServer.onSend(socket, {dest: dest, frame: frame}, function (res) {
      if (res && receipt) {
        ServerFrame.RECEIPT(socket, receipt);
      } else if (!res) {
        ServerFrame.ERROR(socket, "Send error", frame);
      }
    });
  };
}

module.exports = {
  StompUtils: StompUtils,
  ServerFrame: ServerFrame,
  FrameHandler: FrameHandler,
  genId: genId
};
<|endoftext|>


<commit_before>const os = require('os');
const fs = require('fs');
const path = require('path');
const sleep = require('sleep');

const adminLookupStream = require('pelias-wof-admin-lookup');
const model = require('pelias-model');
const dbclient = require('pelias-dbclient');

const decompress = require('decompress');
const csvParse = require('csv-parse');
const through2 = require('through2');

const utils = require('./utils');

const LAYER = 'stops';

/** if location_type == 1, this is not a stop but a parent station */
function isStop(rec, _, callback) {
  if(rec.location_type !== '1') {
      this.push(rec);
  }
  callback();
}

/** parse GTFS stops.txt and stream the results into elasticsearch */
function stopsTxtFileStream(stopsPath, agencyId) {
    var count = 0;
    fs.createReadStream(stopsPath, 'utf8')
        .pipe(csvParse({
            skip_empty_lines: true,
            columns: true
        }))
        .pipe(through2.obj(isStop))
        .pipe(through2.obj(function(rec, _, callback) {
            const id = `${rec.stop_id}::${agencyId}`;
            var name = rec.stop_name;
            if(name == null)
                name = rec.stop_desc;
            var p = utils.makePeliasRecord(LAYER, id, name, rec.stop_lat, rec.stop_lon);
            this.push(p);
            count++;
            callback();
        }))
        .pipe(adminLookupStream.create())
        .pipe(model.createDocumentMapperStream())
        .pipe(dbclient())
        .on('finish', function() {
            console.log(`added ${count} ${agencyId} stops`);
        });
}

/** load a stops.txt file and return it as a record
 *  NOTE: if we're handed a .zip feed (path ends in .zip), we'll extract stops.txt to system /tmp dir
 */
function loadGtfsStops(filePath, agencyId) {
    // if the file path ends in .zip, assume it's a GTFS.zip feed and extract stops.txt
    if(filePath.endsWith(".zip")) {
        const tmp = os.tmpdir();
        const stopsPath = path.join(tmp, `${agencyId}-stops.txt`);
        utils.logger.info(`parsing ${stopsPath}`);
        decompress(filePath, tmp, {
              filter: file => file.path == 'stops.txt',
              map: file => {
                  file.path = `${agencyId}-${file.path}`;
                  return file;
              }
            }).then(files => {
                stopsTxtFileStream(stopsPath, agencyId);
        });
    } else {
        stopsTxtFileStream(filePath, agencyId);
    }
}

module.exports = {
    loadGtfsStops : loadGtfsStops
};<commit_msg>more cleanup<commit_after>const os = require('os');
const fs = require('fs');
const path = require('path');
const decompress = require('decompress');
const csvParse = require('csv-parse');
const through2 = require('through2');

const adminLookupStream = require('pelias-wof-admin-lookup');
const model = require('pelias-model');
const dbclient = require('pelias-dbclient');

const utils = require('./utils');

const LAYER = 'stops';

/** if location_type == 1, this is not a stop but a parent station */
function isStop(rec, _, callback) {
  if(rec.location_type !== '1') {
      this.push(rec);
  }
  callback();
}

/** parse GTFS stops.txt and stream the results into elasticsearch */
function stopsTxtFileStream(stopsPath, agencyId) {
    var count = 0;
    fs.createReadStream(stopsPath, 'utf8')
        .pipe(csvParse({
            skip_empty_lines: true,
            columns: true
        }))
        .pipe(through2.obj(isStop))
        .pipe(through2.obj(function(rec, _, callback) {
            const id = `${rec.stop_id}::${agencyId}`;
            var name = rec.stop_name;
            if(name == null)
                name = rec.stop_desc;
            var p = utils.makePeliasRecord(LAYER, id, name, rec.stop_lat, rec.stop_lon);
            this.push(p);
            count++;
            callback();
        }))
        .pipe(adminLookupStream.create())
        .pipe(model.createDocumentMapperStream())
        .pipe(dbclient())
        .on('finish', function() {
            console.log(`added ${count} ${agencyId} stops`);
        }
    );
}

/** load a stops.txt file and return it as a record
 *  NOTE: if we're handed a .zip feed (path ends in .zip), we'll extract stops.txt to system /tmp dir
 */
function loadGtfsStops(filePath, agencyId) {
    // if the file path ends in .zip, assume it's a GTFS.zip feed and extract stops.txt
    if(filePath.endsWith(".zip")) {
        const tmp = os.tmpdir();
        const stopsPath = path.join(tmp, `${agencyId}-stops.txt`);
        utils.logger.info(`parsing ${stopsPath}`);
        decompress(filePath, tmp, {
              filter: file => file.path == 'stops.txt',
              map: file => {
                  file.path = `${agencyId}-${file.path}`;
                  return file;
              }
            }).then(files => {
                stopsTxtFileStream(stopsPath, agencyId);
        });
    } else {
        stopsTxtFileStream(filePath, agencyId);
    }
}

module.exports = {
    loadGtfsStops : loadGtfsStops
};
<|endoftext|>


<commit_before>/*
Store all the things in the database!
 */

module.exports = {

    //this is just a wrapper for the log method
    error: function(source_url, note, data) {

        console.error(note);

        this.log(source_url, 'error', note, data);

    },

    images: function(source_url, img_urls) {
        /*
        @todo handle getting null from img_urls
         */
        if (img_urls.typeof != "array") throw "img_urls should be an array in store.images(), received: " + img_urls;
        //store the images
        this.message(source_url, "Found Image: ", link_url);
    },

    links: function(source_url, link_url) {
        //store the links
        this.message(source_url, "Found Url: ", link_url);
    },

    /*
    data should be {key: , value:}
     */
    log: function(source_url, type, note, data) {
        //store this information in the log
        console.log("LOG: " + type+": "+note+" "+(data ? data : ""));
    },

    //this is just a wrapper for the log method
    message: function(source_url, note, data) {
        this.log(source_url, 'message', note, data);
    },

    //store the meta information for this url, give different ones to different methods as needed
    meta: function(source_url, meta_name, meta_content) {

        //all the meta information is stored as key-value on the URL document
        this.message(source_url, "Stored Meta", {"key":meta_name, "value": meta_content});

    }

}<commit_msg>updated to include mongoose<commit_after>/*
Store all the things in the database!
 */

var mongoose = require('mongoose');

module.exports = {

    //this is just a wrapper for the log method
    error: function(source_url, note, data) {

        console.error(note);

        this.log(source_url, 'error', note, data);

    },

    images: function(source_url, img_urls) {
        /*
        @todo handle getting null from img_urls
         */
        if (img_urls.typeof != "array") throw "img_urls should be an array in store.images(), received: " + img_urls;
        //store the images
        this.message(source_url, "Found Image: ", link_url);
    },

    links: function(source_url, link_url) {
        //store the links
        this.message(source_url, "Found Url: ", link_url);
    },

    /*
    data should be {key: , value:}
     */
    log: function(source_url, type, note, data) {
        //store this information in the log
        console.log("LOG: " + type+": "+note+" "+(data ? data : ""));
    },

    //this is just a wrapper for the log method
    message: function(source_url, note, data) {
        this.log(source_url, 'message', note, data);
    },

    //store the meta information for this url, give different ones to different methods as needed
    meta: function(source_url, meta_name, meta_content) {

        //all the meta information is stored as key-value on the URL document
        this.message(source_url, "Stored Meta", {"key":meta_name, "value": meta_content});

    }

}<|endoftext|>


<commit_before>// store.js
import React from 'react';
import { createStore, compose } from 'redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';

// import root reducer
import rootReducer from './reducers/rootReducer';

// check local storage for token, save to userData
let userData = localStorage.getItem('token');

// list of components to be rendered to dashboard
let components = [];
let posts = {};

// define default state for store
const defaultState = {
	user: userData,
	components,
	posts: posts
};

// instantiate store
const store = createStore(rootReducer, defaultState);

export const history = syncHistoryWithStore(browserHistory, store);

export default store;

	// import stored plugins
	import * as Components from "./plugins";

	// list of active components
	let components = [
		Posts,
		Collections,
		Comments
	];

	render() {
		let injectedComponents = this.props.components.map((component, i) => {
		  let ComponentElem = Components[component];
		  if (component.mount_point === 'dashboard') {
		    return <ComponentElem key={i} />
		  }
		})

		// render our injected components onto the dashboard
		return (

synthesis dashboard

		    {injectedComponents}

		)
	}

<commit_msg>fixing store.js error<commit_after>// store.js
import React from 'react';
import { createStore, compose } from 'redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';

// import root reducer
import rootReducer from './reducers/rootReducer';

// check local storage for token, save to userData
let userData = localStorage.getItem('token');

// list of components to be rendered to dashboard
let components = [];
let posts = {};

// define default state for store
const defaultState = {
	user: userData,
	components,
	posts: posts
};

// instantiate store
const store = createStore(rootReducer, defaultState);

export const history = syncHistoryWithStore(browserHistory, store);

export default store;

<|endoftext|>


<commit_before><commit_msg>deleted unused file<commit_after><|endoftext|>


<commit_before>'use strict';
var EventEmitter = require('events');
var util = require('util');
var Promise = require('bluebird');
var U = require('./utils');
var DynamoDB = require('./dynamodb');
var constants = require('./constants');
var errors = require('./errors');
var ThroughputExceededError = errors.ThroughputExceededError;
var DynamoDBError = errors.DynamoDBError;
var NotFoundError = errors.NotFoundError;
var NonExistentTableError = errors.NonExistentTableError;
var ConditionFailedError = errors.ConditionFailedError;

var LOGLEVELS_WARN = constants.get('LOGLEVELS_WARN');
var LOGLEVELS_INFO = constants.get('LOGLEVELS_INFO');
var LOGLEVELS_DEBUG = constants.get('LOGLEVELS_DEBUG');

// spec.tableName
// spec.dynamodb
// spec.idAttribute
function Table(spec) {
	EventEmitter.init.call(this);

	Object.defineProperties(this, {
		tableName: {
			enumerable: true,
			value: spec.tableName
		},
		dynamodb: {
			enumerable: true,
			value: spec.dynamodb
		},
		idAttribute: {
			enumerable: true,
			value: spec.idAttribute || 'id'
		}
	});
}

util.inherits(Table, EventEmitter);

module.exports = Table;

U.extend(Table.prototype, {

	get: function (key) {
		var primaryKey = Object.keys(key).reduce(function (primaryKey, k) {
			switch (typeof key[k]) {
				case 'string':
					primaryKey[k] = {S: key[k]};
					break;
				case 'number':
					primaryKey[k] = {N: key[k]};
					break;
				case 'boolean':
					primaryKey[k] = {BOOLEAN: key[k]};
					break;
				default:
					throw new Error('Only String, Number, or Boolean keys ' +
						'are supported in DynamoDB Engine');
			}
			return primaryKey;
		}, {});

		var params = {
			Key: primaryKey,
			TableName: this.tableName,
			// Projecting no attributes will fetch them all.
			ProjectionExpression: ''
		};

		var self = this;

		return new Promise(function (resolve, reject) {
			self.dynamodb.getItem(params, function (err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (err) {
					reject(new DynamoDBError(err));
				} else if (res) {
					return resolve(DynamoDB.deserializeData(res.Item));
				}
				reject(new NotFoundError('Could not find entity'));
			});
		});
	},

	put: function (attributes, options) {
		if (!attributes) {
			throw new Error('Table#put(attributes) must have ' +
				'an attributes parameter');
		}
		if (!U.isObject(attributes) || Array.isArray(attributes)) {
			throw new Error('Table#put(attributes) attributes must be ' +
				'an Object.');
		}

		options = options || Object.create(null);
		var self = this;

		var params = {
			Item: DynamoDB.serializeRecord(attributes),
			TableName: this.tableName
		};

		if (options.condition) {
			params.ConditionExpression = options.condition;
		}

		return new Promise(function (resolve, reject) {
			self.dynamodb.putItem(params, function (err) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (DynamoDB.isConditionalFailedException(err)) {
					reject(new ConditionFailedError(err.message));
				} else if (err) {
					return reject(new DynamoDBError(err));
				}
				resolve(attributes);
			});
		});
	},

	remove: function (id, options) {
		if (!id) {
			throw new Error('table.remove(record) requires a record.id String');
		}
		if (!U.isString(id)) {
			throw new Error('table.remove(record) record.id must be a String');
		}

		options = options || Object.create(null);
		var self = this;

		var idAttribute = options.idAttribute || this.idAttribute;

		var key = {};
		key[idAttribute] = {
			S: id
		};

		var params = {
			Key: key,
			TableName: this.tableName
		};

		return new Promise(function (resolve, reject) {
			self.emit('log', {
				level: LOGLEVELS_DEBUG,
				message: 'attempting to DELETE ' + id + ' from ' + self.tableName
			});
			self.dynamodb.deleteItem(params, function (err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'ProvisionedThroughputExceededException in ' +
							'DELETE ' + id + ' from ' + self.tableName,
						error: err
					});
					return reject(new ThroughputExceededError(err.message));
				}
				if (err) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'Unexpected exception in ' +
							'DELETE ' + id + ' from ' + self.tableName,
						error: err
					});
					return reject(err);
				}
				if (res) {
					self.emit('log', {
						level: LOGLEVELS_INFO,
						message: 'DELETE ' + id + ' from ' + self.tableName
					});
					return resolve(true);
				}
				self.emit('log', {
					level: LOGLEVELS_INFO,
					message: 'DELETE ' + id + ' from ' + self.tableName + ' not found'
				});
				reject(new NotFoundError('Could not find entity by id ' + id));
			});
		});
	},

	// keys - *Array* of Strings.
	// options.idAttribute - *String* (default = this.idAttribute)
	// options.ConsistentRead - *Boolean* (default = false)
	// options.ReturnConsumedCapacity - *String* 'INDEXES | TOTAL | NONE' (default = 'NONE')
	getBatch: function (keys, options) {
		options = options || Object.create(null);
		var self = this;
		var RequestItems = {};

		var idAttribute = options.idAttribute || this.idAttribute;

		RequestItems[this.tableName] = {
			Keys: keys.map(function (key) {
				var dbKey = {};
				dbKey[idAttribute] = {S: key};
				return dbKey;
			}),
			ConsistentRead: Boolean(options.ConsistentRead)
		};

		var params = {
			RequestItems: RequestItems,
			ReturnConsumedCapacity: options.ReturnConsumedCapacity || 'NONE'
		};

		return new Promise(function (resolve, reject) {
			self.emit('log', {
				level: LOGLEVELS_DEBUG,
				message: 'attempting to batch GET from ' + keys[0] + ' from ' + self.tableName
			});
			self.dynamodb.batchGetItem(params, function (err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'ProvisionedThroughputExceededException in ' +
							'batch GET from ' + keys[0] + ' from ' + self.tableName,
						error: err
					});
					return reject(new ThroughputExceededError(err.message));
				}
				if (err) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'Unexpected exception in batch GET from ' +
							keys[0] + ' from ' + self.tableName,
						error: err
					});
					return reject(err);
				}
				self.emit('log', {
					level: LOGLEVELS_INFO,
					message: 'batch GET from ' + keys[0] + ' from ' + self.tableName
				});
				resolve(res);
			});
		});
	}
});

Table.create = function createTable(tableName, dynamodb) {
	return new Table({
		tableName: tableName,
		dynamodb: dynamodb
	});
};

<commit_msg>Start of query method.<commit_after>'use strict';
var EventEmitter = require('events');
var util = require('util');
var Promise = require('bluebird');
var U = require('./utils');
var DynamoDB = require('./dynamodb');
var constants = require('./constants');
var errors = require('./errors');
var ThroughputExceededError = errors.ThroughputExceededError;
var DynamoDBError = errors.DynamoDBError;
var NotFoundError = errors.NotFoundError;
var NonExistentTableError = errors.NonExistentTableError;
var ConditionFailedError = errors.ConditionFailedError;

var LOGLEVELS_WARN = constants.get('LOGLEVELS_WARN');
var LOGLEVELS_INFO = constants.get('LOGLEVELS_INFO');
var LOGLEVELS_DEBUG = constants.get('LOGLEVELS_DEBUG');

// spec.tableName
// spec.dynamodb
// spec.idAttribute
function Table(spec) {
	EventEmitter.init.call(this);

	Object.defineProperties(this, {
		tableName: {
			enumerable: true,
			value: spec.tableName
		},
		dynamodb: {
			enumerable: true,
			value: spec.dynamodb
		},
		idAttribute: {
			enumerable: true,
			value: spec.idAttribute || 'id'
		}
	});
}

util.inherits(Table, EventEmitter);

module.exports = Table;

U.extend(Table.prototype, {

	get: function (key) {
		var primaryKey = Object.keys(key).reduce(function (primaryKey, k) {
			switch (typeof key[k]) {
				case 'string':
					primaryKey[k] = {S: key[k]};
					break;
				case 'number':
					primaryKey[k] = {N: key[k]};
					break;
				case 'boolean':
					primaryKey[k] = {BOOLEAN: key[k]};
					break;
				default:
					throw new Error('Only String, Number, or Boolean keys ' +
						'are supported in DynamoDB Engine');
			}
			return primaryKey;
		}, {});

		var params = {
			Key: primaryKey,
			TableName: this.tableName,
			// Projecting no attributes will fetch them all.
			ProjectionExpression: ''
		};

		var self = this;

		return new Promise(function (resolve, reject) {
			self.dynamodb.getItem(params, function (err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (err) {
					reject(new DynamoDBError(err));
				} else if (res) {
					return resolve(DynamoDB.deserializeData(res.Item));
				}
				reject(new NotFoundError('Could not find entity'));
			});
		});
	},

	put: function (attributes, options) {
		if (!attributes) {
			throw new Error('Table#put(attributes) must have ' +
				'an attributes parameter');
		}
		if (!U.isObject(attributes) || Array.isArray(attributes)) {
			throw new Error('Table#put(attributes) attributes must be ' +
				'an Object.');
		}

		options = options || Object.create(null);
		var self = this;

		var params = {
			Item: DynamoDB.serializeRecord(attributes),
			TableName: this.tableName
		};

		if (options.condition) {
			params.ConditionExpression = options.condition;
		}

		return new Promise(function (resolve, reject) {
			self.dynamodb.putItem(params, function (err) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (DynamoDB.isConditionalFailedException(err)) {
					reject(new ConditionFailedError(err.message));
				} else if (err) {
					return reject(new DynamoDBError(err));
				}
				resolve(attributes);
			});
		});
	},

	remove: function (id, options) {
		if (!id) {
			throw new Error('table.remove(record) requires a record.id String');
		}
		if (!U.isString(id)) {
			throw new Error('table.remove(record) record.id must be a String');
		}

		options = options || Object.create(null);
		var self = this;

		var idAttribute = options.idAttribute || this.idAttribute;

		var key = {};
		key[idAttribute] = {
			S: id
		};

		var params = {
			Key: key,
			TableName: this.tableName
		};

		return new Promise(function (resolve, reject) {
			self.emit('log', {
				level: LOGLEVELS_DEBUG,
				message: 'attempting to DELETE ' + id + ' from ' + self.tableName
			});
			self.dynamodb.deleteItem(params, function (err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'ProvisionedThroughputExceededException in ' +
							'DELETE ' + id + ' from ' + self.tableName,
						error: err
					});
					return reject(new ThroughputExceededError(err.message));
				}
				if (err) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'Unexpected exception in ' +
							'DELETE ' + id + ' from ' + self.tableName,
						error: err
					});
					return reject(err);
				}
				if (res) {
					self.emit('log', {
						level: LOGLEVELS_INFO,
						message: 'DELETE ' + id + ' from ' + self.tableName
					});
					return resolve(true);
				}
				self.emit('log', {
					level: LOGLEVELS_INFO,
					message: 'DELETE ' + id + ' from ' + self.tableName + ' not found'
				});
				reject(new NotFoundError('Could not find entity by id ' + id));
			});
		});
	},

	// keys - *Array* of Strings.
	// options.idAttribute - *String* (default = this.idAttribute)
	// options.ConsistentRead - *Boolean* (default = false)
	// options.ReturnConsumedCapacity - *String* 'INDEXES | TOTAL | NONE' (default = 'NONE')
	getBatch: function (keys, options) {
		options = options || Object.create(null);
		var self = this;
		var RequestItems = {};

		var idAttribute = options.idAttribute || this.idAttribute;

		RequestItems[this.tableName] = {
			Keys: keys.map(function (key) {
				var dbKey = {};
				dbKey[idAttribute] = {S: key};
				return dbKey;
			}),
			ConsistentRead: Boolean(options.ConsistentRead)
		};

		var params = {
			RequestItems: RequestItems,
			ReturnConsumedCapacity: options.ReturnConsumedCapacity || 'NONE'
		};

		return new Promise(function (resolve, reject) {
			self.emit('log', {
				level: LOGLEVELS_DEBUG,
				message: 'attempting to batch GET from ' + keys[0] + ' from ' + self.tableName
			});
			self.dynamodb.batchGetItem(params, function (err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'ProvisionedThroughputExceededException in ' +
							'batch GET from ' + keys[0] + ' from ' + self.tableName,
						error: err
					});
					return reject(new ThroughputExceededError(err.message));
				}
				if (err) {
					self.emit('log', {
						level: LOGLEVELS_WARN,
						message: 'Unexpected exception in batch GET from ' +
							keys[0] + ' from ' + self.tableName,
						error: err
					});
					return reject(err);
				}
				self.emit('log', {
					level: LOGLEVELS_INFO,
					message: 'batch GET from ' + keys[0] + ' from ' + self.tableName
				});
				resolve(res);
			});
		});
	},

	{
		indexName: 'STRING_VALUE',
		order: 'STRING_VALUE', /* default = 'ascending' */
		limit: 0
	}
	query: function (params) {
		params = params || Object.create(null);
		var condition = params.condition;

		var newParams = {
			TableName: this.tableName,
			Select: 'ALL_ATTRIBUTES',
			ScanIndexForward: params.order !== 'descending',
			KeyConditionExpression: condition,
			ExpressionAttributeNames: {
			},
			ExpressionAttributeValues: {
			}
		};

		if (params.indexName) {
			newParams.IndexName = params.indexName;
		}
		if (params.hasOwnProperty('limit')) {
			newParams.limit = params.limit;
		}

		return new Promise(function (resolve, reject) {
			self.dynamodb.query(params, function (err, res) {
			});
		});
	}
});

Table.create = function createTable(tableName, dynamodb) {
	return new Table({
		tableName: tableName,
		dynamodb: dynamodb
	});
};

<|endoftext|>