<commit_before>"use strict";

var path = require("path");

function _logDoclet (doclet) {
    var title = [];
    if (doclet.meta && doclet.meta.lineno) {
        title.push("@", doclet.meta.lineno, ": ");
    }
    if (doclet.undocumented) {
        title.push("(u) ");
    }
    title.push(doclet.longname, " (", doclet.kind, ")");
    console.log(title.join(""));
    // try {
    //     if (doclet.longname === "_gpfAssertImpl") {
    //         console.log(doclet);
    //     }
    // } catch (e) {
    //     // ignore
    // }
}

function _findDoclet (doclets, longname, tag) {
    var resultDoclet;
    doclets.every(function (doclet) {
        if (doclet.longname === longname && !doclet.undocumented) {
            resultDoclet = doclet;
            return false;
        }
        return true;
    });
    if (!resultDoclet) {
        throw new Error("invalid reference for @" + tag.title);
    }
    return resultDoclet;
}

function _findRefDoclet (doclets, doclet, tag) {
    var refLongname = tag.value;
    if (-1 === refLongname.indexOf("#") && -1 !== doclet.longname.indexOf("#")) {
        refLongname = doclet.longname.split("#")[0] + "#" + refLongname;
    }
    return _findDoclet(doclets, refLongname, tag);
}

var _customTags = {

    // Returns the same type with a generic comment
    chainable: function (doclet/*, tag, doclets*/) {
        doclet.returns = [{
            type: {
                names: [doclet.memberof]
            },
            description: "Self reference to allow chaining"
        }];
    },

    // Read accessor on a property
    read: function (doclet, tag, doclets) {
        var refDoclet = _findRefDoclet(doclets, doclet, tag);
        doclet.returns = [{
            type: refDoclet.type,
            description: refDoclet.description
        }];
        doclet.description = "GET accessor for " + refDoclet.description;
    },

    // Write accessor on a property
    write: function (/*doclet, tag, doclets*/) {
        // var refDoclet = _findRefDoclet(doclets, doclet, tag);
    },

    // Same as another doclet
    sameas: function (doclet, tag, doclets) {
        var refDoclet = _findRefDoclet(doclets, doclet, tag);
        [
            "description",
            "params",
            "returns",
            "exceptions",
            "kind"
        ].forEach(function (propertyName) {
            doclet[propertyName] = refDoclet[propertyName];
        });
    }

};

function _handleCustomTags (doclet, doclets) {
    if (doclet.tags) {
        doclet.tags.forEach(function (tag) {
            var customTag = tag.title.split("gpf:")[1];
            var handler = _customTags[customTag];
            if (undefined !== handler) {
                try {
                    handler(doclet, tag, doclets);
                } catch (e) {
                    console.error(doclet.meta.path + path.sep + doclet.meta.filename + "@" + doclet.meta.lineno + ": "
                        + e.message);
                    console.error(doclet);
                    throw e;
                }
            }
        });
    }
}

function _addMemberType (doclet) {
    if (!doclet.type) {
        // type: { names: [ 'String' ] }
        var codeType = doclet.meta.code.type,
            type;
        if (codeType === "Literal") {
            type = typeof doclet.meta.code.value;
            type = type.charAt(0).toUpperCase() + type.substr(1);
        } else if (codeType === "ArrayExpression") {
            type = "Array";
        } else if (codeType === "ObjectExpression") {
            type = "Object";
        }
        doclet.type = {
            names: [
                type
            ]
        };
    }
}

function _checkAccess (doclet) {
    if (!doclet.access) {
        if (doclet.name.charAt(0) === "_") {
            doclet.access = "private";
        } else {
            doclet.access = "public";
        }
    }
}

function _postProcessDoclet (doclet, index, doclets) {
    var kind = doclet.kind;
    _logDoclet(doclet);
    _handleCustomTags(doclet, doclets);
    if (kind === "member") {
        _addMemberType(doclet);
        _checkAccess(doclet);
    } else if (-1 !== ["function", "class"].indexOf(kind)) {
        _checkAccess(doclet);
    }
}

var _reErrorDeclare = /_gpfErrorDeclare\("([a-zA-Z\\]+)", {\n((?:.*\n)*)\s*}\)/g,
    _reErrorItems = /(?:\/\*\*((?:[^*]|\s|\*[^/])*)\*\/)?\s*([a-zA-Z]+):\s*"([^"]*)"/g,
    _reContextualParams = /{(\w+)}/g;

function _generateJsDocForError (name, message, comment) {
    var className = name.charAt(0).toUpperCase() + name.substr(1),
        result,
        params = [],
        param;
    _reContextualParams.lastIndex = 0;
    param = _reContextualParams.exec(message);
    while (param) {
        params.push(" * - {String} " + param[1]);
        param = _reContextualParams.exec(message);
    }
    if (params.length) {
        params.unshift(" * @param {Object} context Dictionary of parameters used to format the message, must contain");
        params = params.join("\r\n");
    } else {
        params = undefined;
    }
    result = [
        "/**",
        " * throw {@link gpf.Error." + className + "}",
        " * @method gpf.Error." + name,
        " * @throws {gpf.Error." + className + "}",
        params,
        " */",
        "/**",
        comment,
        " * @class gpf.Error." + className,
        params,
        " */"
    ];
    return result.join("\r\n");
}

function _checkForGpfErrorDeclare (event) {
    _reErrorDeclare.lastIndex = 0;
    var match = _reErrorDeclare.exec(event.source);
    if (match) {
        var // moduleName = match[1],
            errorsPart = match[2],
            errorItem,
            comments = [];
        _reErrorItems.lastIndex = 0;
        errorItem = _reErrorItems.exec(errorsPart);
        while (errorItem) {
            comments.push(_generateJsDocForError(errorItem[2], errorItem[3], errorItem[1]));
            errorItem = _reErrorItems.exec(errorsPart);
        }
        event.source += comments.join("\r\n");
    }
}

// http://usejsdoc.org/about-plugins.html
module.exports = {

    handlers: {

        beforeParse: function (event) {
            _checkForGpfErrorDeclare(event);
        },

        processingComplete: function (event) {
            event.doclets.forEach(_postProcessDoclet);
        }

    }

};
<commit_msg>FIX #103<commit_after>"use strict";

var path = require("path");

function _logDoclet (doclet) {
    var title = [];
    if (doclet.meta && doclet.meta.lineno) {
        title.push("@", doclet.meta.lineno, ": ");
    }
    if (doclet.undocumented) {
        title.push("(u) ");
    }
    title.push(doclet.longname, " (", doclet.kind, ")");
    console.log(title.join(""));
    // try {
    //     if (doclet.longname === "_gpfAssertImpl") {
    //         console.log(doclet);
    //     }
    // } catch (e) {
    //     // ignore
    // }
}

function _findDoclet (doclets, longname, tag) {
    var resultDoclet;
    doclets.every(function (doclet) {
        if (doclet.longname === longname && !doclet.undocumented) {
            resultDoclet = doclet;
            return false;
        }
        return true;
    });
    if (!resultDoclet) {
        throw new Error("invalid reference for @" + tag.title);
    }
    return resultDoclet;
}

function _findRefDoclet (doclets, doclet, tag) {
    var refLongname = tag.value;
    if (-1 === refLongname.indexOf("#") && -1 !== doclet.longname.indexOf("#")) {
        refLongname = doclet.longname.split("#")[0] + "#" + refLongname;
    }
    return _findDoclet(doclets, refLongname, tag);
}

var _customTags = {

    // Returns the same type with a generic comment
    chainable: function (doclet/*, tag, doclets*/) {
        doclet.returns = [{
            type: {
                names: [doclet.memberof]
            },
            description: "Self reference to allow chaining"
        }];
    },

    // Read accessor on a property
    read: function (doclet, tag, doclets) {
        var refDoclet = _findRefDoclet(doclets, doclet, tag);
        doclet.returns = [{
            type: refDoclet.type,
            description: refDoclet.description
        }];
        doclet.description = "GET accessor for " + refDoclet.description;
    },

    // Write accessor on a property
    write: function (/*doclet, tag, doclets*/) {
        // var refDoclet = _findRefDoclet(doclets, doclet, tag);
    },

    // Same as another doclet
    sameas: function (doclet, tag, doclets) {
        var refDoclet = _findRefDoclet(doclets, doclet, tag);
        [
            "description",
            "params",
            "returns",
            "exceptions",
            "kind"
        ].forEach(function (propertyName) {
            doclet[propertyName] = refDoclet[propertyName];
        });
    }

};

function _handleCustomTags (doclet, doclets) {
    if (doclet.tags) {
        doclet.tags.forEach(function (tag) {
            var customTag = tag.title.split("gpf:")[1];
            var handler = _customTags[customTag];
            if (undefined !== handler) {
                try {
                    handler(doclet, tag, doclets);
                } catch (e) {
                    console.error(doclet.meta.path + path.sep + doclet.meta.filename + "@" + doclet.meta.lineno + ": "
                        + e.message);
                    console.error(doclet);
                    throw e;
                }
            }
        });
    }
}

function _addMemberType (doclet) {
    if (!doclet.type) {
        // type: { names: [ 'String' ] }
        var codeType = doclet.meta.code.type,
            type;
        if (codeType === "Literal") {
            type = typeof doclet.meta.code.value;
            type = type.charAt(0).toUpperCase() + type.substr(1);
        } else if (codeType === "ArrayExpression") {
            type = "Array";
        } else if (codeType === "ObjectExpression") {
            type = "Object";
        }
        doclet.type = {
            names: [
                type
            ]
        };
    }
}

function _checkAccess (doclet) {
    if (!doclet.access) {
        if (doclet.name.charAt(0) === "_") {
            doclet.access = "private";
        } else {
            doclet.access = "public";
        }
    }
}

function _postProcessDoclet (doclet, index, doclets) {
    var kind = doclet.kind;
    _logDoclet(doclet);
    _handleCustomTags(doclet, doclets);
    if (kind === "member") {
        _addMemberType(doclet);
        _checkAccess(doclet);
    } else if (-1 !== ["function", "class"].indexOf(kind)) {
        _checkAccess(doclet);
    }
}

var _reErrorDeclare = /_gpfErrorDeclare\("([a-zA-Z\\]+)", {\n((?:.*\n)*)\s*}\)/g,
    _reErrorItems = /(?:\/\*\*((?:[^*]|\s|\*[^/])*)\*\/)?\s*([a-zA-Z]+):\s*"([^"]*)"/g,
    _reContextualParams = /{(\w+)}/g;

function _generateJsDocForError (name, message, comment) {
    var className = name.charAt(0).toUpperCase() + name.substr(1),
        result,
        params = [],
        param;
    _reContextualParams.lastIndex = 0;
    param = _reContextualParams.exec(message);
    while (param) {
        params.push(" * - {String} " + param[1]);
        param = _reContextualParams.exec(message);
    }
    if (params.length) {
        params.unshift(" * @param {Object} context Dictionary of parameters used to format the message, must contain");
        params = params.join("\r\n");
    } else {
        params = undefined;
    }
    result = [
        "/**",
        " * throw {@link gpf.Error." + className + "}",
        " * @method gpf.Error." + name,
        " * @throws {gpf.Error." + className + "}",
        params,
        " */",
        "/**",
        comment,
        " * @class gpf.Error." + className,
        params,
        " */"
    ];
    return result.join("\r\n");
}

function _checkForGpfErrorDeclare (event) {
    _reErrorDeclare.lastIndex = 0;
    var match = _reErrorDeclare.exec(event.source);
    if (match) {
        var // moduleName = match[1],
            errorsPart = match[2],
            errorItem,
            comments = [];
        _reErrorItems.lastIndex = 0;
        errorItem = _reErrorItems.exec(errorsPart);
        while (errorItem) {
            comments.push(_generateJsDocForError(errorItem[2], errorItem[3], errorItem[1]));
            errorItem = _reErrorItems.exec(errorsPart);
        }
        event.source += comments.join("\r\n");
    }
}

function _isInsideGpfErrorDeclare (node) {
    var ancestor;
    try {
        ancestor = node.parent.parent.parent;
    } catch (e) {
        return false;
    }
    return ancestor
        && ancestor.type === "ExpressionStatement"
        && ancestor.expression.type === "CallExpression"
        && ancestor.expression.callee.name === "_gpfErrorDeclare"
        && "Property" === node.type;
}

function _visitNode (node, e/*, parser, currentSourceName*/) { //eslint-disable-line max-params

    if (_isInsideGpfErrorDeclare(node)) {
        // This documentation is handled through beforeParse
        e.preventDefault = true;
        return;
    }

}

// http://usejsdoc.org/about-plugins.html
module.exports = {

    astNodeVisitor: {

        visitNode: _visitNode

    },

    handlers: {

        beforeParse: function (event) {
            _checkForGpfErrorDeclare(event);
        },

        processingComplete: function (event) {
            event.doclets.forEach(_postProcessDoclet);
        }

    }

};
<|endoftext|>


<commit_before>
/** Note: This file doesn't contain any unit tests. It has some architecture for
 * performing common test function.*/

const RG = require('../client/src/battles');
const expect = require('chai').expect;

const RGTest = {};

RGTest.rng = new RG.Random();

/* Creates a mock-level for unit tests. */
RGTest.createMockLevel = function(cols, rows) {
    const level = {cols: cols, rows: rows,
        map: {
            getCell: function(x, y) {
                return { x: x, y: y };
            },
            hasXY: function() {
                return true;
            },
            isPassable: function(x, y) {
                return x > -1 && y > -1;
            }
        },
        getMap: function() {return this.map;},

        addActor: function(actor, x, y) {
            actor.setXY(x, y);
            actor.setLevel(this);
        }
    };
    return level;
};

RGTest.createLevel = function(type, cols, rows) {
    return RG.FACT.createLevel('arena', cols, rows);
};

RGTest.equipItem = function(actor, item) {
    const invEq = actor.getInvEq();
    invEq.addItem(item);
    expect(invEq.equipItem(item)).to.equal(true);
};

/* Wraps an object into a cell for later use. Some functions require a map cell
* instead of taking the object directly, so this is useful. */
RGTest.wrapObjWithCell = function(obj) {
    const cell = RG.FACT.createFloorCell();
    cell.setExplored(true); // Otherwise returns darkness
    const propType = obj.getPropType();
    cell.setProp(propType, obj);
    return cell;
};

RGTest.getMeAWizard = function(conf = {}) {
    const wizard = new RG.Actor.Rogue('wizard');
    wizard.setType(conf.type || 'human');
    const brain = new RG.Brain.SpellCaster(wizard);
    brain.setCastProbability(1.1);
    wizard.setBrain(brain);

    wizard._spellbook = new RG.Spell.SpellBook(wizard);
    const spell = RG.FACT.createSpell('FrostBolt');
    spell.setPower(conf.power || 11);
    spell.setRange(conf.range || 7);
    spell.setDice([RG.FACT.createDie([1, 2, 3])]);
    wizard._spellbook.addSpell(spell);

    const spellPower = new RG.Component.SpellPower();
    spellPower.setPP(30);
    spellPower.setMaxPP(40);
    wizard.add('SpellPower', spellPower);
    return wizard;

};

RGTest.checkActorXY = function(actor, x, y) {
    expect(actor.getX(), `X must be ${x}`).to.equal(x);
    expect(actor.getY(), `Y must be ${y}`).to.equal(y);
};

RGTest.checkChar = function(obj, expChar) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getCellChar(cell)).to.equal(expChar);
};

RGTest.checkCSSClassName = function(obj, expClass) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getStyleClassForCell(cell)).to.equal(expClass);

};

RGTest.expectEqualHealth = function(o1, o2) {
    expect(o1.get('Health').getHP()).to.equal(o2.get('Health').getHP());
};

RGTest.verifyStairsConnectivity = function(stairs) {
    let connVerified = 0;
    stairs.forEach(s => {
        expect(s.getTargetStairs()).not.to.be.empty;
        expect(s.getTargetLevel()).not.to.be.empty;
        expect(s.getSrcLevel()).not.to.be.empty;
        ++connVerified;
    });
    console.log(`verifyStairsConnectivity ${connVerified} connections OK`);
};

// Expect that branches b1 and b2 are connected by number of connections
// given by nConns.
RGTest.expectConnected = function(b1, b2, nConns) {
    let connFound = 0;
    const b1Stairs = b1.getStairsOther();
    const b2Stairs = b2.getStairsOther();
    expect(b1Stairs, 'B1 must have stairs').to.have.length.above(0);
    expect(b2Stairs, 'B2 must have stairs').to.have.length.above(0);

    b1Stairs.forEach(stair1 => {
        const s1TargetID = stair1.getTargetLevel().getID();
        expect(stair1.getTargetStairs()).not.to.be.empty;
        b2Stairs.forEach(stair2 => {
            const s2SourceID = stair2.getSrcLevel().getID();
            if (s1TargetID === s2SourceID) {
                // stair1 should be the target of stair2
                if (stair2.getTargetStairs() === stair1) {
                    ++connFound;
                }
                expect(stair2.getTargetStairs()).not.to.be.empty;
            }
        });
    });
    expect(connFound, `Connections between branches must be ${nConns}`)
        .to.equal(nConns);
};

/* Adds each entity into the level. */
RGTest.wrapIntoLevel = function(arr) {
    const level = RG.FACT.createLevel('empty', 20, 20);
    arr.forEach(ent => {
        const x = RGTest.rng.getUniformInt(0, 19);
        const y = RGTest.rng.getUniformInt(0, 19);
        if (ent.getPropType() === RG.TYPE_ACTOR) {
            level.addActor(ent, x, y);
        }
        if (ent.getPropType() === RG.TYPE_ITEM) {
            level.addItem(ent, x, y);
        }
    });
    return level;
};

/* Moves entity from its current position to x,y. */
RGTest.moveEntityTo = function(ent, x, y) {
    const map = ent.getLevel().getMap();
    const xOld = ent.getX();
    const yOld = ent.getY();
    const propType = ent.getPropType();
    if (map.removeProp(xOld, yOld, propType, ent)) {
        map.setProp(x, y, propType, ent);
        ent.setXY(x, y);
        return true;
    }
    throw new Error(`Cannot move entity to ${x}, ${y}`);
};

/* Equips all given items for the given actor, and checks that everything
 * succeeds. */
RGTest.equipItems = function(ent, items) {
    const inv = ent.getInvEq();
    items.forEach(item => {
        inv.addItem(item);
        if (!inv.equipItem(item)) {
            throw new Error(`Cannot equip item ${item}`);
        }
    });
};

module.exports = RGTest;
<commit_msg>Created MsgCather to see game messages on console.log.<commit_after>
/** Note: This file doesn't contain any unit tests. It has some architecture for
 * performing common test function.*/

const RG = require('../client/src/battles');
const expect = require('chai').expect;

const RGTest = {};

RGTest.rng = new RG.Random();

/* Creates a mock-level for unit tests. */
RGTest.createMockLevel = function(cols, rows) {
    const level = {cols: cols, rows: rows,
        map: {
            getCell: function(x, y) {
                return { x: x, y: y };
            },
            hasXY: function() {
                return true;
            },
            isPassable: function(x, y) {
                return x > -1 && y > -1;
            }
        },
        getMap: function() {return this.map;},

        addActor: function(actor, x, y) {
            actor.setXY(x, y);
            actor.setLevel(this);
        }
    };
    return level;
};

RGTest.createLevel = function(type, cols, rows) {
    return RG.FACT.createLevel('arena', cols, rows);
};

RGTest.equipItem = function(actor, item) {
    const invEq = actor.getInvEq();
    invEq.addItem(item);
    expect(invEq.equipItem(item)).to.equal(true);
};

/* Wraps an object into a cell for later use. Some functions require a map cell
* instead of taking the object directly, so this is useful. */
RGTest.wrapObjWithCell = function(obj) {
    const cell = RG.FACT.createFloorCell();
    cell.setExplored(true); // Otherwise returns darkness
    const propType = obj.getPropType();
    cell.setProp(propType, obj);
    return cell;
};

RGTest.getMeAWizard = function(conf = {}) {
    const wizard = new RG.Actor.Rogue('wizard');
    wizard.setType(conf.type || 'human');
    const brain = new RG.Brain.SpellCaster(wizard);
    brain.setCastProbability(1.1);
    wizard.setBrain(brain);

    wizard._spellbook = new RG.Spell.SpellBook(wizard);
    const spell = RG.FACT.createSpell('FrostBolt');
    spell.setPower(conf.power || 11);
    spell.setRange(conf.range || 7);
    spell.setDice([RG.FACT.createDie([1, 2, 3])]);
    wizard._spellbook.addSpell(spell);

    const spellPower = new RG.Component.SpellPower();
    spellPower.setPP(30);
    spellPower.setMaxPP(40);
    wizard.add('SpellPower', spellPower);
    return wizard;

};

RGTest.checkActorXY = function(actor, x, y) {
    expect(actor.getX(), `X must be ${x}`).to.equal(x);
    expect(actor.getY(), `Y must be ${y}`).to.equal(y);
};

RGTest.checkChar = function(obj, expChar) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getCellChar(cell)).to.equal(expChar);
};

RGTest.checkCSSClassName = function(obj, expClass) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getStyleClassForCell(cell)).to.equal(expClass);

};

RGTest.expectEqualHealth = function(o1, o2) {
    expect(o1.get('Health').getHP()).to.equal(o2.get('Health').getHP());
};

RGTest.verifyStairsConnectivity = function(stairs) {
    let connVerified = 0;
    stairs.forEach(s => {
        expect(s.getTargetStairs()).not.to.be.empty;
        expect(s.getTargetLevel()).not.to.be.empty;
        expect(s.getSrcLevel()).not.to.be.empty;
        ++connVerified;
    });
    console.log(`verifyStairsConnectivity ${connVerified} connections OK`);
};

// Expect that branches b1 and b2 are connected by number of connections
// given by nConns.
RGTest.expectConnected = function(b1, b2, nConns) {
    let connFound = 0;
    const b1Stairs = b1.getStairsOther();
    const b2Stairs = b2.getStairsOther();
    expect(b1Stairs, 'B1 must have stairs').to.have.length.above(0);
    expect(b2Stairs, 'B2 must have stairs').to.have.length.above(0);

    b1Stairs.forEach(stair1 => {
        const s1TargetID = stair1.getTargetLevel().getID();
        expect(stair1.getTargetStairs()).not.to.be.empty;
        b2Stairs.forEach(stair2 => {
            const s2SourceID = stair2.getSrcLevel().getID();
            if (s1TargetID === s2SourceID) {
                // stair1 should be the target of stair2
                if (stair2.getTargetStairs() === stair1) {
                    ++connFound;
                }
                expect(stair2.getTargetStairs()).not.to.be.empty;
            }
        });
    });
    expect(connFound, `Connections between branches must be ${nConns}`)
        .to.equal(nConns);
};

/* Adds each entity into the level. */
RGTest.wrapIntoLevel = function(arr) {
    const level = RG.FACT.createLevel('empty', 20, 20);
    arr.forEach(ent => {
        const x = RGTest.rng.getUniformInt(0, 19);
        const y = RGTest.rng.getUniformInt(0, 19);
        if (ent.getPropType() === RG.TYPE_ACTOR) {
            level.addActor(ent, x, y);
        }
        if (ent.getPropType() === RG.TYPE_ITEM) {
            level.addItem(ent, x, y);
        }
    });
    return level;
};

/* Moves entity from its current position to x,y. */
RGTest.moveEntityTo = function(ent, x, y) {
    const map = ent.getLevel().getMap();
    const xOld = ent.getX();
    const yOld = ent.getY();
    const propType = ent.getPropType();
    if (map.removeProp(xOld, yOld, propType, ent)) {
        map.setProp(x, y, propType, ent);
        ent.setXY(x, y);
        return true;
    }
    throw new Error(`Cannot move entity to ${x}, ${y}`);
};

/* Equips all given items for the given actor, and checks that everything
 * succeeds. */
RGTest.equipItems = function(ent, items) {
    const inv = ent.getInvEq();
    items.forEach(item => {
        inv.addItem(item);
        if (!inv.equipItem(item)) {
            throw new Error(`Cannot equip item ${item}`);
        }
    });
};

/* Can be used to catch the emitted game messages. */
RGTest.MsgCatcher = function() {

    this.hasNotify = true;
    this.notify = (evtName, msg) => {
        console.log('\tMsg: |' + msg.msg + '|');
    };

    RG.POOL.listenEvent(RG.EVT_MSG, this);
};

module.exports = RGTest;
<|endoftext|>


<commit_before>'use strict';

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

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _s = require('s3');

var _s2 = _interopRequireDefault(_s);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path2 = require('path');

var _path3 = _interopRequireDefault(_path2);

var _progress = require('progress');

var _progress2 = _interopRequireDefault(_progress);

var _cdnizer = require('cdnizer');

var _cdnizer2 = _interopRequireDefault(_cdnizer);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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

_http2.default.globalAgent.maxSockets = _https2.default.globalAgent.maxSockets = 50;

var UPLOAD_IGNORES = ['.DS_Store'];

var DEFAULT_UPLOAD_OPTIONS = {
  ACL: 'public-read'
};

var DEFAULT_S3_OPTIONS = {
  region: 'us-west-2'
};

var REQUIRED_S3_OPTS = ['accessKeyId', 'secretAccessKey'],
    REQUIRED_S3_UP_OPTS = ['Bucket'];

var PATH_SEP = _path3.default.sep;

module.exports = (function () {
  function S3Plugin() {
    var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

    _classCallCheck(this, S3Plugin);

    var _options$s3Options = options.s3Options;
    var s3Options = _options$s3Options === undefined ? {} : _options$s3Options;
    var _options$s3UploadOpti = options.s3UploadOptions;
    var s3UploadOptions = _options$s3UploadOpti === undefined ? {} : _options$s3UploadOpti;
    var directory = options.directory;
    var include = options.include;
    var exclude = options.exclude;
    var basePath = options.basePath;
    var _options$cdnizerOptio = options.cdnizerOptions;
    var cdnizerOptions = _options$cdnizerOptio === undefined ? {} : _options$cdnizerOptio;
    var htmlFiles = options.htmlFiles;

    this.uploadOptions = s3UploadOptions;
    this.isConnected = false;
    this.cdnizerOptions = cdnizerOptions;
    this.urlMappings = [];
    this.uploadTotal = 0;
    this.uploadProgress = 0;
    basePath = basePath ? basePath.replace(/\/?(\?|#|$)/, '/$1') : '';

    this.options = {
      directory: directory,
      include: include,
      exclude: exclude,
      basePath: basePath,
      htmlFiles: typeof htmlFiles === 'string' ? [htmlFiles] : htmlFiles
    };

    this.clientConfig = {
      maxAsyncS3: 50,
      s3Options: _lodash2.default.merge({}, DEFAULT_S3_OPTIONS, s3Options)
    };

    this.noCdnizer = !Object.keys(this.cdnizerOptions).length;

    if (!this.noCdnizer && !this.cdnizerOptions.files) this.cdnizerOptions.files = [];
  }

  _createClass(S3Plugin, [{
    key: 'apply',
    value: function apply(compiler) {
      var _this = this;

      this.connect();

      var isDirectoryUpload = !!this.options.directory,
          hasRequiredOptions = this.client.s3.config.credentials !== null,
          hasRequiredUploadOpts = REQUIRED_S3_UP_OPTS.every(function (type) {
        return _this.uploadOptions[type];
      });

      // Set directory to output dir or custom
      this.options.directory = this.options.directory || compiler.options.output.path || compiler.options.output.context || '.';

      compiler.plugin('after-emit', function (compilation, cb) {
        if (!hasRequiredOptions) {
          compilation.errors.push(new Error('S3Plugin: Must provide ' + REQUIRED_S3_OPTS.join(', ')));
          cb();
        }

        if (!hasRequiredUploadOpts) {
          compilation.errors.push(new Error('S3Plugin-RequiredS3UploadOpts: ' + REQUIRED_S3_UP_OPTS.join(', ')));
          cb();
        }

        if (isDirectoryUpload) {
          var _path = _this.options.directory.endsWith(PATH_SEP) ? _this.options.directory : _this.options.directory + PATH_SEP;

          _this.getAllFilesRecursive(_path).then(_this.filterAllowedFiles.bind(_this)).then(_this.uploadFiles.bind(_this)).then(_this.changeHtmlUrls.bind(_this)).then(function () {
            return cb();
          }).catch(function (e) {
            compilation.errors.push(new Error('S3Plugin: ' + e));
            cb();
          });
        } else {
          _this.uploadFiles(_this.getAssetFiles(compilation)).then(_this.changeHtmlUrls.bind(_this)).then(function () {
            return cb();
          }).catch(function (e) {
            compilation.errors.push(new Error('S3Plugin: ' + e));
            cb();
          });
        }
      });
    }
  }, {
    key: 'getAllFilesRecursive',
    value: function getAllFilesRecursive(path) {
      return new Promise(function (resolve, reject) {
        var results = [];

        _fs2.default.readdir(path, function (err, list) {
          if (err) return reject(err);

          var i = 0;

          (function next() {
            var file = list[i++];

            if (!file) return resolve(results);

            file = (path.endsWith(PATH_SEP) || file.startsWith(PATH_SEP) ? path : path + PATH_SEP) + file;

            _fs2.default.stat(file, function (err, stat) {
              if (stat && stat.isDirectory()) {
                this.getAllFilesRecursive(file).then(function (res) {
                  results.push.apply(results, _toConsumableArray(res));
                  next();
                });
              } else {
                results.push(file);
                next();
              }
            });
          })();
        });
      });
    }
  }, {
    key: 'addPathToFiles',
    value: function addPathToFiles(files, fPath) {
      return files.map(function (file) {
        return _path3.default.resolve(fPath, file);
      });
    }
  }, {
    key: 'getFileName',
    value: function getFileName() {
      var file = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];

      return file.includes(PATH_SEP) ? file.substring(file.lastIndexOf(PATH_SEP) + 1) : file;
    }
  }, {
    key: 'getAssetFiles',
    value: function getAssetFiles(_ref) {
      var chunks = _ref.chunks;
      var options = _ref.options;

      var publicPath = options.output.publicPath || options.output.path;

      var files = (0, _lodash2.default)(chunks).pluck('files').flatten().map(function (file) {
        return _path3.default.resolve(publicPath, file);
      }).value();

      return this.filterAllowedFiles(files);
    }
  }, {
    key: 'cdnizeHtml',
    value: function cdnizeHtml(htmlPath) {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        _fs2.default.readFile(htmlPath, function (err, data) {
          if (err) return reject(err);

          _fs2.default.writeFile(htmlPath, _this2.cdnizer(data.toString()), function (err) {
            if (err) return reject(err);

            resolve();
          });
        });
      });
    }
  }, {
    key: 'changeHtmlUrls',
    value: function changeHtmlUrls() {
      var _this3 = this;

      if (this.noCdnizer) return Promise.resolve();

      var _options = this.options;
      var directory = _options.directory;
      var htmlFiles = _options.htmlFiles;
      var htmlFiles = htmlFiles || _fs2.default.readdirSync(directory).filter(function (file) {
        return (/\.html$/.test(file)
        );
      });
      var allHtml = this.addPathToFiles(htmlFiles, directory);

      this.cdnizer = (0, _cdnizer2.default)(this.cdnizerOptions);

      return Promise.all(allHtml.map(function (file) {
        return _this3.cdnizeHtml(file);
      }));
    }
  }, {
    key: 'filterAllowedFiles',
    value: function filterAllowedFiles(files) {
      var _this4 = this;

      return files.reduce(function (res, file) {
        if (_this4.isIncludeOrExclude(file) && !_this4.isIgnoredFile(file)) res.push({
          name: _this4.getFileName(file),
          path: file
        });

        return res;
      }, []);
    }
  }, {
    key: 'isIgnoredFile',
    value: function isIgnoredFile(file) {
      return _lodash2.default.some(UPLOAD_IGNORES, function (ignore) {
        return new RegExp(ignore).test(file);
      });
    }
  }, {
    key: 'isIncludeOrExclude',
    value: function isIncludeOrExclude(file) {
      var isExclude;
      var isInclude;
      var _options2 = this.options;
      var include = _options2.include;
      var exclude = _options2.exclude;

      isInclude = include ? include.test(file) : true;
      isExclude = exclude ? exclude.test(file) : false;

      return isInclude && !isExclude;
    }
  }, {
    key: 'connect',
    value: function connect() {
      if (this.isConnected) return;

      this.client = _s2.default.createClient(this.clientConfig);
      this.isConnected = true;
    }
  }, {
    key: 'uploadFiles',
    value: function uploadFiles() {
      var _this5 = this;

      var files = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];

      var sum = function sum(array) {
        return array.reduce(function (res, val) {
          return res += val;
        }, 0);
      };
      var uploadFiles = files.map(function (file) {
        return _this5.uploadFile(file.name, file.path);
      });
      var progressAmount = Array(files.length);
      var progressTotal = Array(files.length);

      var progressBar = new _progress2.default('Uploading [:bar] :percent :etas', {
        complete: '>',
        incomplete: '∆',
        total: 100
      });

      //uploadFiles.forEach(function({upload}, i) {
      //upload.on('progress', function() {
      //progressTotal[i] = this.progressTotal
      //progressAmount[i] = this.progressAmount

      //progressBar.update((sum(progressAmount) / sum(progressTotal)).toFixed(2))
      //})
      //})

      return Promise.all(uploadFiles.map(function (_ref2) {
        var promise = _ref2.promise;
        return promise;
      }));
    }
  }, {
    key: 'uploadFile',
    value: function uploadFile(fileName, file) {
      var upload,
          s3Params = _lodash2.default.merge({ Key: this.options.basePath + fileName }, DEFAULT_UPLOAD_OPTIONS, this.uploadOptions);

      // Remove Gzip from encoding if ico
      if (/\.ico/.test(fileName) && s3Params.ContentEncoding === 'gzip') delete s3Params.ContentEncoding;

      upload = this.client.uploadFile({
        localFile: file,
        s3Params: s3Params
      });

      if (!this.noCdnizer) this.cdnizerOptions.files.push('*' + fileName + '*');

      var promise = new Promise(function (resolve, reject) {
        upload.on('error', reject);
        upload.on('end', function () {
          return resolve(file);
        });
      });

      return { upload: upload, promise: promise };
    }
  }]);

  return S3Plugin;
})();<commit_msg>Build<commit_after>'use strict';

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

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _s = require('s3');

var _s2 = _interopRequireDefault(_s);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _progress = require('progress');

var _progress2 = _interopRequireDefault(_progress);

var _cdnizer = require('cdnizer');

var _cdnizer2 = _interopRequireDefault(_cdnizer);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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

_http2.default.globalAgent.maxSockets = _https2.default.globalAgent.maxSockets = 50;

var UPLOAD_IGNORES = ['.DS_Store'];

var DEFAULT_UPLOAD_OPTIONS = {
  ACL: 'public-read'
};

var DEFAULT_S3_OPTIONS = {
  region: 'us-west-2'
};

var REQUIRED_S3_OPTS = ['accessKeyId', 'secretAccessKey'],
    REQUIRED_S3_UP_OPTS = ['Bucket'];

var PATH_SEP = _path2.default.sep;

module.exports = (function () {
  function S3Plugin() {
    var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

    _classCallCheck(this, S3Plugin);

    var _options$s3Options = options.s3Options;
    var s3Options = _options$s3Options === undefined ? {} : _options$s3Options;
    var _options$s3UploadOpti = options.s3UploadOptions;
    var s3UploadOptions = _options$s3UploadOpti === undefined ? {} : _options$s3UploadOpti;
    var directory = options.directory;
    var include = options.include;
    var exclude = options.exclude;
    var basePath = options.basePath;
    var _options$cdnizerOptio = options.cdnizerOptions;
    var cdnizerOptions = _options$cdnizerOptio === undefined ? {} : _options$cdnizerOptio;
    var htmlFiles = options.htmlFiles;

    this.uploadOptions = s3UploadOptions;
    this.isConnected = false;
    this.cdnizerOptions = cdnizerOptions;
    this.urlMappings = [];
    this.uploadTotal = 0;
    this.uploadProgress = 0;
    basePath = basePath ? basePath.replace(/\/?(\?|#|$)/, '/$1') : '';

    this.options = {
      directory: directory,
      include: include,
      exclude: exclude,
      basePath: basePath,
      htmlFiles: typeof htmlFiles === 'string' ? [htmlFiles] : htmlFiles
    };

    this.clientConfig = {
      maxAsyncS3: 50,
      s3Options: _lodash2.default.merge({}, DEFAULT_S3_OPTIONS, s3Options)
    };

    this.noCdnizer = !Object.keys(this.cdnizerOptions).length;

    if (!this.noCdnizer && !this.cdnizerOptions.files) this.cdnizerOptions.files = [];
  }

  _createClass(S3Plugin, [{
    key: 'apply',
    value: function apply(compiler) {
      var _this = this;

      this.connect();

      var isDirectoryUpload = !!this.options.directory,
          hasRequiredOptions = this.client.s3.config.credentials !== null,
          hasRequiredUploadOpts = REQUIRED_S3_UP_OPTS.every(function (type) {
        return _this.uploadOptions[type];
      });

      // Set directory to output dir or custom
      this.options.directory = this.options.directory || compiler.options.output.path || compiler.options.output.context || '.';

      compiler.plugin('after-emit', function (compilation, cb) {
        if (!hasRequiredOptions) {
          compilation.errors.push(new Error('S3Plugin: Must provide ' + REQUIRED_S3_OPTS.join(', ')));
          cb();
        }

        if (!hasRequiredUploadOpts) {
          compilation.errors.push(new Error('S3Plugin-RequiredS3UploadOpts: ' + REQUIRED_S3_UP_OPTS.join(', ')));
          cb();
        }

        if (isDirectoryUpload) {
          var dPath = _this.addSeperatorToPath(_this.options.directory);
          _this.getAllFilesRecursive(dPath).then(_this.filterPathFromFiles(dPath)).then(_this.filterAllowedFiles.bind(_this)).then(_this.uploadFiles.bind(_this)).then(_this.changeHtmlUrls.bind(_this)).then(function () {
            return cb();
          }).catch(function (e) {
            compilation.errors.push(new Error('S3Plugin: ' + e));
            cb();
          });
        } else {
          _this.uploadFiles(_this.getAssetFiles(compilation)).then(_this.changeHtmlUrls.bind(_this)).then(function () {
            return cb();
          }).catch(function (e) {
            compilation.errors.push(new Error('S3Plugin: ' + e));
            cb();
          });
        }
      });
    }
  }, {
    key: 'filterPathFromFiles',
    value: function filterPathFromFiles(path) {
      return function (files) {
        return files.map(function (file) {
          return {
            path: file,
            name: file.replace(path, '')
          };
        });
      };
    }
  }, {
    key: 'addSeperatorToPath',
    value: function addSeperatorToPath(path) {
      return path.endsWith(PATH_SEP) ? path : path + PATH_SEP;
    }
  }, {
    key: 'getAllFilesRecursive',
    value: function getAllFilesRecursive(path) {
      var _this3 = this;

      return new Promise(function (resolve, reject) {
        var results = [];

        _fs2.default.readdir(path, function (err, list) {
          if (err) return reject(err);

          var i = 0;

          (function next() {
            var _this2 = this;

            var file = list[i++];

            if (!file) return resolve(results);

            file = (path.endsWith(PATH_SEP) || file.startsWith(PATH_SEP) ? path : path + PATH_SEP) + file;

            _fs2.default.stat(file, function (err, stat) {
              if (stat && stat.isDirectory()) {
                _this2.getAllFilesRecursive(file).then(function (res) {
                  results.push.apply(results, _toConsumableArray(res));
                  next();
                });
              } else {
                results.push(file);
                next();
              }
            });
          }).call(_this3);
        });
      });
    }
  }, {
    key: 'addPathToFiles',
    value: function addPathToFiles(files, fPath) {
      return files.map(function (file) {
        return _path2.default.resolve(fPath, file);
      });
    }
  }, {
    key: 'getFileName',
    value: function getFileName() {
      var file = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];

      return file.includes(PATH_SEP) ? file.substring(file.lastIndexOf(PATH_SEP) + 1) : file;
    }
  }, {
    key: 'getAssetFiles',
    value: function getAssetFiles(_ref) {
      var chunks = _ref.chunks;
      var options = _ref.options;

      var publicPath = options.output.publicPath || options.output.path;

      var files = (0, _lodash2.default)(chunks).pluck('files').flatten().map(function (name) {
        return { path: _path2.default.resolve(publicPath, name), name: name };
      }).value();

      return this.filterAllowedFiles(files);
    }
  }, {
    key: 'cdnizeHtml',
    value: function cdnizeHtml(htmlPath) {
      var _this4 = this;

      return new Promise(function (resolve, reject) {
        _fs2.default.readFile(htmlPath, function (err, data) {
          if (err) return reject(err);

          _fs2.default.writeFile(htmlPath, _this4.cdnizer(data.toString()), function (err) {
            if (err) return reject(err);

            resolve();
          });
        });
      });
    }
  }, {
    key: 'changeHtmlUrls',
    value: function changeHtmlUrls() {
      var _this5 = this;

      if (this.noCdnizer) return Promise.resolve();

      var allHtml;
      var _options = this.options;
      var directory = _options.directory;
      var htmlFiles = _options.htmlFiles;

      htmlFiles = htmlFiles || _fs2.default.readdirSync(directory).filter(function (file) {
        return (/\.html$/.test(file)
        );
      });

      allHtml = this.addPathToFiles(htmlFiles, directory);

      this.cdnizer = (0, _cdnizer2.default)(this.cdnizerOptions);

      return Promise.all(allHtml.map(function (file) {
        return _this5.cdnizeHtml(file);
      }));
    }
  }, {
    key: 'filterAllowedFiles',
    value: function filterAllowedFiles(files) {
      var _this6 = this;

      return files.reduce(function (res, file) {
        if (_this6.isIncludeAndNotExclude(file.name) && !_this6.isIgnoredFile(file.name)) res.push(file);

        return res;
      }, []);
    }
  }, {
    key: 'isIgnoredFile',
    value: function isIgnoredFile(file) {
      return _lodash2.default.some(UPLOAD_IGNORES, function (ignore) {
        return new RegExp(ignore).test(file);
      });
    }
  }, {
    key: 'isIncludeAndNotExclude',
    value: function isIncludeAndNotExclude(file) {
      var isExclude;
      var isInclude;
      var _options2 = this.options;
      var include = _options2.include;
      var exclude = _options2.exclude;

      isInclude = include ? include.test(file) : true;
      isExclude = exclude ? exclude.test(file) : false;

      return isInclude && !isExclude;
    }
  }, {
    key: 'connect',
    value: function connect() {
      if (this.isConnected) return;

      this.client = _s2.default.createClient(this.clientConfig);
      this.isConnected = true;
    }
  }, {
    key: 'uploadFiles',
    value: function uploadFiles() {
      var _this7 = this;

      var files = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];

      var sum = function sum(array) {
        return array.reduce(function (res, val) {
          return res += val;
        }, 0);
      };
      var uploadFiles = files.map(function (file) {
        return _this7.uploadFile(file.name, file.path);
      });
      var progressAmount = Array(files.length);
      var progressTotal = Array(files.length);

      var progressBar = new _progress2.default('Uploading [:bar] :percent :etas', {
        complete: '>',
        incomplete: '∆',
        total: 100
      });

      //uploadFiles.forEach(function({upload}, i) {
      //upload.on('progress', function() {
      //progressTotal[i] = this.progressTotal
      //progressAmount[i] = this.progressAmount

      //progressBar.update((sum(progressAmount) / sum(progressTotal)).toFixed(2))
      //})
      //})

      return Promise.all(uploadFiles.map(function (_ref2) {
        var promise = _ref2.promise;
        return promise;
      }));
    }
  }, {
    key: 'uploadFile',
    value: function uploadFile(fileName, file) {
      var upload,
          s3Params = _lodash2.default.merge({ Key: this.options.basePath + fileName }, DEFAULT_UPLOAD_OPTIONS, this.uploadOptions);

      // Remove Gzip from encoding if ico
      if (/\.ico/.test(fileName) && s3Params.ContentEncoding === 'gzip') delete s3Params.ContentEncoding;

      upload = this.client.uploadFile({
        localFile: file,
        s3Params: s3Params
      });

      if (!this.noCdnizer) this.cdnizerOptions.files.push('*' + fileName + '*');

      var promise = new Promise(function (resolve, reject) {
        upload.on('error', reject);
        upload.on('end', function () {
          return resolve(file);
        });
      });

      return { upload: upload, promise: promise };
    }
  }]);

  return S3Plugin;
})();<|endoftext|>


<commit_before>export default {
    BOOKS: [{
        "_id": 1,
        title: "abc123",
        isbn: "0001122223334",
        author: {
            last: "zzz",
            first: "aaa"
        },
        copies: 5
    }],
    BOOKMARKS: [{
        _id: 1,
        user: "1234",
        stop: {
            title: "book1",
            author: "xyz",
            page: 32
        }
    }, {
        _id: 2,
        user: "7890",
        stop: [{
            title: "book2",
            author: "abc",
            page: 5
        }, {
            title: "book3",
            author: "ijk",
            page: 100
        }]
    }],
    inventory: [{
        "_id": 1,
        "item": "abc1",
        description: "product 1",
        qty: 300
    }, {
        "_id": 2,
        "item": "abc2",
        description: "product 2",
        qty: 200
    }, {
        "_id": 3,
        "item": "xyz1",
        description: "product 3",
        qty: 250
    }, {
        "_id": 4,
        "item": "VWZ1",
        description: "product 4",
        qty: 300
    }, {
        "_id": 5,
        "item": "VWZ2",
        description: "product 5",
        qty: 180
    }]
};
<commit_msg>feat(test): Adds more test collections<commit_after>export default {
    BOOKS: [{
        "_id": 1,
        title: "abc123",
        isbn: "0001122223334",
        author: {
            last: "zzz",
            first: "aaa"
        },
        copies: 5
    }],
    BOOKMARKS: [{
        _id: 1,
        user: "1234",
        stop: {
            title: "book1",
            author: "xyz",
            page: 32
        }
    }, {
        _id: 2,
        user: "7890",
        stop: [{
            title: "book2",
            author: "abc",
            page: 5
        }, {
            title: "book3",
            author: "ijk",
            page: 100
        }]
    }],
    inventory: [{
        "_id": 1,
        "item": "abc1",
        description: "product 1",
        qty: 300
    }, {
        "_id": 2,
        "item": "abc2",
        description: "product 2",
        qty: 200
    }, {
        "_id": 3,
        "item": "xyz1",
        description: "product 3",
        qty: 250
    }, {
        "_id": 4,
        "item": "VWZ1",
        description: "product 4",
        qty: 300
    }, {
        "_id": 5,
        "item": "VWZ2",
        description: "product 5",
        qty: 180
    }],
    experiments: [{
        "_id": 1,
        "A": ["red", "blue"],
        "B": ["red", "blue"]
    }, {
        "_id": 2,
        "A": ["red", "blue"],
        "B": ["blue", "red", "blue"]
    }, {
        "_id": 3,
        "A": ["red", "blue"],
        "B": ["red", "blue", "green"]
    }, {
        "_id": 4,
        "A": ["red", "blue"],
        "B": ["green", "red"]
    }, {
        "_id": 5,
        "A": ["red", "blue"],
        "B": []
    }, {
        "_id": 6,
        "A": ["red", "blue"],
        "B": [
            ["red"],
            ["blue"]
        ]
    }, {
        "_id": 7,
        "A": ["red", "blue"],
        "B": [
            ["red", "blue"]
        ]
    }, {
        "_id": 8,
        "A": [],
        "B": []
    }, {
        "_id": 9,
        "A": [],
        "B": ["red"]
    } ]
};
<|endoftext|>


<commit_before>/*
 *  Copyright 2011 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var util = require('util');

var swiz = require('swiz');

// Mock set of serialization defs
var def = {
  'Node' : [
    ['id' , {'src' : 'hash_id', 'type' : 'string',
      'desc' : 'hash ID for the node'}],
    ['is_active' , {'src' : 'active', 'type' : 'bool',
      'desc' : 'is the node active?'}],
    ['name' , {'src' : 'get_name', 'type' : 'string', 'desc' : 'name' }],
    ['agent_name' , {'type': 'string'}],
    ['ipaddress' , {'src' : 'get_public_address', 'type' : 'ip'}],
    ['public_ips' , {'cache_key' : 'node_addrs_public', 'type' : 'list<ip>'}],
    ['state', {'enumerated' : {inactive: 0, active: 1, full_no_new_checks: 2}}],
    ['opts', {'src': 'options', 'type': 'NodeOpts'}],
    ['data', {'src': 'data', 'type': 'map<string, object>'}]
  ],
  'NodeOpts': [
    ['option1', {'src': 'opt1', 'type': 'string'}],
    ['option2', {'src': 'opt2', 'type': 'string'}],
    ['option3', {'src': 'opt3', 'type': 'string'}]
  ]
};

/** Completely mock node object.
* @constructor
*/
function Node() {
  this.hash_id = '15245';
  this.active = true;
  this.agent_name = 'gl<ah';
  this.public_ips = ['123.45.55.44', '122.123.32.2'];
  this.public_address = '123.33.22.1';
  this.state = 1;
  this.options = {
    'opt1': 'defaultval',
    'opt2': 'defaultval',
    'opt3': function(callback) {
      callback(null, 'something');
    }
  };

  this.options.getSerializerType = function() {
    return 'NodeOpts';
  };

  this.data = {
    'foo': 'thingone',
    'bar': 'thingtwo'
  };
}

/**
 * Dummy funct
 * @param {function(*,*)} callback junk.
 */
Node.prototype.get_name = function(callback) {
  callback(null, 'gggggg');
};

/**
 * Dummy funct
 * @param {function(*,*)} callback junk.
*/
Node.prototype.get_public_address = function(callback) {
  callback(null, this.public_address);
};

/**
 * Dummy funct
 * @return {string} junk.
*/
Node.prototype.getSerializerType = function() {return 'Node';};

exports['test_xml_escape_string'] = function(test, assert) {
  var sw = new swiz.Swiz(def);
  assert.deepEqual(sw.xmlEscapeString('<&blah>'), '<&blah>');

  test.finish();
};

exports['test_build_object'] = function(test, assert) {
  var blahnode = new Node();
  var sw = new swiz.Swiz(def);
  sw.buildObject(blahnode, function(err, result) {
    assert.ifError(err);
    assert.deepEqual(result, {
      id: 15245,
      is_active: true,
      name: 'gggggg',
      agent_name: 'gl<ah',
      ipaddress: '123.33.22.1',
      public_ips: ['123.45.55.44', '122.123.32.2'],
      opts: {
        option1: 'defaultval',
        option2: 'defaultval',
        option3: 'something'
      },
      data: {
        foo: 'thingone',
        bar: 'thingtwo'
      },
      state: 'active'
    });
    test.finish();
  });
};

exports['test_serial_xml'] = function(test, assert) {
  var blahnode = new Node();
  var sw = new swiz.Swiz(def);
  //swiz.loadDefinitions(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, blahnode,
      function(err, results)
      {
        // need to make an appointemnt with a DOM for this one.
        assert.deepEqual(results, '<?xml version="1.0" encoding="UTF-8"?>' +
            '<Node><id>15245</id><is_active>true</' +
            'is_active><name>gggggg</name><agent_name>gl<ah</' +
            'agent_name><ipaddress>123.33.22.1</ipaddress>' +
            '<public_ips>123.45.55.44</public_ips>' +
            '<public_ips>122.123.32.2</public_ips>' +
            '<state>active</state>' +
            '<opts><NodeOpts>' +
            '<option1>defaultval</option1>' +
            '<option2>defaultval</option2>' +
            '<option3>something</option3>' +
            '</NodeOpts></opts>' +
            '<data><foo>thingone</foo><bar>thingtwo</bar></data></Node>');

        test.finish();
      }
  );
};

exports['test_serial_json'] = function(test, assert) {
  var blahnode = new Node();
  var sw = new swiz.Swiz(def);
  //swiz.loadDefinitions(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, blahnode,
      function(err, results)
      {
        var rep = JSON.parse(results);
        assert.deepEqual(rep.id, 15245);
        assert.deepEqual(rep.is_active, true);
        assert.deepEqual(rep.name, 'gggggg');
        assert.deepEqual(rep.agent_name, 'gl<ah');
        assert.deepEqual(rep.ipaddress, '123.33.22.1');
        assert.deepEqual(rep.public_ips, ['123.45.55.44', '122.123.32.2']);
        assert.deepEqual(rep.opts, {
          option1: 'defaultval',
          option2: 'defaultval',
          option3: 'something'
        });
        assert.deepEqual(rep.data, {
          foo: 'thingone',
          bar: 'thingtwo'
        });
        assert.deepEqual(rep.state, 'active');
        test.finish();
      }
  );
};

exports['test_serial_array_xml'] = function(test, assert) {
  var blahnode = new Node();
  var blahnode2 = new Node();
  blahnode2.hash_id = '444';
  blahnode2.agent_name = 'your mom';
  var blaharr = [blahnode, blahnode2];
  var sw = new swiz.Swiz(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, blaharr,
      function(err, results)
      {

        assert.deepEqual(results, '<?xml version="1.0" encoding="UTF-8"?>' +
            '<group><Node><id>15245</id><is_active>true</' +
            'is_active><name>gggggg</name><agent_name>gl<ah</' +
            'agent_name><ipaddress>123.33.22.1</ipaddress>' +
            '<public_ips>123.45.55.44</public_ips>' +
            '<public_ips>122.123.32.2</public_ips>' +
            '<state>active</state>' +
            '<opts><NodeOpts>' +
            '<option1>defaultval</option1><option2>defaultval</option2>' +
            '<option3>something</option3></NodeOpts></opts>' +
            '<data><foo>thingone</foo><bar>thingtwo</bar></data></Node>' +
            '<Node><id>444</id><is_active>true</' +
            'is_active><name>gggggg</name><agent_name>your mom</' +
            'agent_name><ipaddress>123.33.22.1</ipaddress>' +
            '<public_ips>123.45.55.44</public_ips>' +
            '<public_ips>122.123.32.2</public_ips>' +
            '<state>active</state>' +
            '<opts><NodeOpts>' +
            '<option1>defaultval</option1><option2>defaultval</option2>' +
            '<option3>something</option3></NodeOpts></opts>' +
            '<data><foo>thingone</foo><bar>thingtwo</bar></data></Node>' +
            '</group>');

        test.finish();
      }
  );
};

exports['test_error_type'] = function(test, assert) {
  var blah = { };
  var sw = new swiz.Swiz(def);
  blah.getSerializerType = function() {return 'monito';};
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, blah,
      function(err, results)
      {
        assert.ok(err instanceof Error);

        test.finish();
      }
  );
};

exports['test_serial_array_json'] = function(test, assert) {
  var blahnode = new Node();
  var blahnode2 = new Node();
  blahnode2.hash_id = '444';
  blahnode2.agent_name = 'your mom';
  var blaharr = [blahnode, blahnode2];
  var sw = new swiz.Swiz(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, blaharr,
      function(err, results)
      {
        var rep = JSON.parse(results);
        assert.deepEqual(rep[0].id, 15245);
        assert.deepEqual(rep[0].is_active, true);
        assert.deepEqual(rep[0].name, 'gggggg');
        assert.deepEqual(rep[0].agent_name, 'gl<ah');
        assert.deepEqual(rep[0].ipaddress, '123.33.22.1');
        assert.deepEqual(rep[0].public_ips,
            ['123.45.55.44', '122.123.32.2']);
        assert.deepEqual(rep[0].opts, {
          option1: 'defaultval',
          option2: 'defaultval',
          option3: 'something'
        });
        assert.deepEqual(rep[0].data, {
          foo: 'thingone',
          bar: 'thingtwo'
        });
        assert.deepEqual(rep[0].state, 'active');
        assert.deepEqual(rep[1].id, 444);
        assert.deepEqual(rep[1].is_active, true);
        assert.deepEqual(rep[1].name, 'gggggg');
        assert.deepEqual(rep[1].agent_name, 'your mom');
        assert.deepEqual(rep[1].ipaddress, '123.33.22.1');
        assert.deepEqual(rep[1].public_ips,
            ['123.45.55.44', '122.123.32.2']);
        assert.deepEqual(rep[1].opts, {
          option1: 'defaultval',
          option2: 'defaultval',
          option3: 'something'
        });
        assert.deepEqual(rep[1].data, {
          foo: 'thingone',
          bar: 'thingtwo'
        });
        assert.deepEqual(rep[1].state, 'active');
        test.finish();
      }
  );
};
<commit_msg>Also add tests for stripNull option.<commit_after>/*
 *  Copyright 2011 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var util = require('util');

var swiz = require('swiz');

// Mock set of serialization defs
var def = {
  'Node' : [
    ['id' , {'src' : 'hash_id', 'type' : 'string',
      'desc' : 'hash ID for the node'}],
    ['is_active' , {'src' : 'active', 'type' : 'bool',
      'desc' : 'is the node active?'}],
    ['name' , {'src' : 'get_name', 'type' : 'string', 'desc' : 'name' }],
    ['agent_name' , {'type': 'string'}],
    ['ipaddress' , {'src' : 'get_public_address', 'type' : 'ip'}],
    ['public_ips' , {'cache_key' : 'node_addrs_public', 'type' : 'list<ip>'}],
    ['state', {'enumerated' : {inactive: 0, active: 1, full_no_new_checks: 2}}],
    ['opts', {'src': 'options', 'type': 'NodeOpts'}],
    ['data', {'src': 'data', 'type': 'map<string, object>'}]
  ],
  'NodeOpts': [
    ['option1', {'src': 'opt1', 'type': 'string'}],
    ['option2', {'src': 'opt2', 'type': 'string'}],
    ['option3', {'src': 'opt3', 'type': 'string'}]
  ]
};

/** Completely mock node object.
* @constructor
*/
function Node() {
  this.hash_id = '15245';
  this.active = true;
  this.agent_name = 'gl<ah';
  this.public_ips = ['123.45.55.44', '122.123.32.2'];
  this.public_address = '123.33.22.1';
  this.state = 1;
  this.options = {
    'opt1': 'defaultval',
    'opt2': 'defaultval',
    'opt3': function(callback) {
      callback(null, 'something');
    }
  };

  this.options.getSerializerType = function() {
    return 'NodeOpts';
  };

  this.data = {
    'foo': 'thingone',
    'bar': 'thingtwo'
  };
}

/**
 * Dummy funct
 * @param {function(*,*)} callback junk.
 */
Node.prototype.get_name = function(callback) {
  callback(null, 'gggggg');
};

/**
 * Dummy funct
 * @param {function(*,*)} callback junk.
*/
Node.prototype.get_public_address = function(callback) {
  callback(null, this.public_address);
};

/**
 * Dummy funct
 * @return {string} junk.
*/
Node.prototype.getSerializerType = function() {return 'Node';};

exports['test_xml_escape_string'] = function(test, assert) {
  var sw = new swiz.Swiz(def);
  assert.deepEqual(sw.xmlEscapeString('<&blah>'), '<&blah>');

  test.finish();
};

exports['test_build_object'] = function(test, assert) {
  var blahnode = new Node();
  var sw = new swiz.Swiz(def);
  sw.buildObject(blahnode, function(err, result) {
    assert.ifError(err);
    assert.deepEqual(result, {
      id: 15245,
      is_active: true,
      name: 'gggggg',
      agent_name: 'gl<ah',
      ipaddress: '123.33.22.1',
      public_ips: ['123.45.55.44', '122.123.32.2'],
      opts: {
        option1: 'defaultval',
        option2: 'defaultval',
        option3: 'something'
      },
      data: {
        foo: 'thingone',
        bar: 'thingtwo'
      },
      state: 'active'
    });
    test.finish();
  });
};

exports['test_serial_xml'] = function(test, assert) {
  var blahnode = new Node();
  blahnode.active = false;
  var sw = new swiz.Swiz(def, { stripNulls: true });
  //swiz.loadDefinitions(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, blahnode,
      function(err, results)
      {
        // need to make an appointemnt with a DOM for this one.
        assert.deepEqual(results, '<?xml version="1.0" encoding="UTF-8"?>' +
            '<Node><id>15245</id><is_active>false</' +
            'is_active><name>gggggg</name><agent_name>gl<ah</' +
            'agent_name><ipaddress>123.33.22.1</ipaddress>' +
            '<public_ips>123.45.55.44</public_ips>' +
            '<public_ips>122.123.32.2</public_ips>' +
            '<state>active</state>' +
            '<opts><NodeOpts>' +
            '<option1>defaultval</option1>' +
            '<option2>defaultval</option2>' +
            '<option3>something</option3>' +
            '</NodeOpts></opts>' +
            '<data><foo>thingone</foo><bar>thingtwo</bar></data></Node>');

        test.finish();
      }
  );
};

exports['test_serial_xml_stripNulls'] = function(test, assert) {
  var blahnode = new Node();
  blahnode.active = null;
  var sw = new swiz.Swiz(def, { stripNulls: true });
  //swiz.loadDefinitions(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, blahnode,
      function(err, results)
      {
        // need to make an appointemnt with a DOM for this one.
        assert.deepEqual(results, '<?xml version="1.0" encoding="UTF-8"?>' +
            '<Node><id>15245</id>' +
            '<name>gggggg</name><agent_name>gl<ah</' +
            'agent_name><ipaddress>123.33.22.1</ipaddress>' +
            '<public_ips>123.45.55.44</public_ips>' +
            '<public_ips>122.123.32.2</public_ips>' +
            '<state>active</state>' +
            '<opts><NodeOpts>' +
            '<option1>defaultval</option1>' +
            '<option2>defaultval</option2>' +
            '<option3>something</option3>' +
            '</NodeOpts></opts>' +
            '<data><foo>thingone</foo><bar>thingtwo</bar></data></Node>');

        test.finish();
      }
  );
};

exports['test_serial_json'] = function(test, assert) {
  var blahnode = new Node();
  blahnode.active = false;
  var sw = new swiz.Swiz(def, { stripNulls: true });
  //swiz.loadDefinitions(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, blahnode,
      function(err, results)
      {
        var rep = JSON.parse(results);
        assert.deepEqual(rep.id, 15245);
        assert.deepEqual(rep.is_active, false);
        assert.deepEqual(rep.name, 'gggggg');
        assert.deepEqual(rep.agent_name, 'gl<ah');
        assert.deepEqual(rep.ipaddress, '123.33.22.1');
        assert.deepEqual(rep.public_ips, ['123.45.55.44', '122.123.32.2']);
        assert.deepEqual(rep.opts, {
          option1: 'defaultval',
          option2: 'defaultval',
          option3: 'something'
        });
        assert.deepEqual(rep.data, {
          foo: 'thingone',
          bar: 'thingtwo'
        });
        assert.deepEqual(rep.state, 'active');
        test.finish();
      }
  );
};

exports['test_serial_json_stripNulls'] = function(test, assert) {
  var blahnode = new Node();
  blahnode.active = null;
  var sw = new swiz.Swiz(def, { stripNulls: true });
  //swiz.loadDefinitions(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, blahnode,
      function(err, results)
      {
        var rep = JSON.parse(results);
        assert.deepEqual(rep.id, 15245);
        assert.ok(!rep.hasOwnProperty('is_active'));
        assert.deepEqual(rep.name, 'gggggg');
        assert.deepEqual(rep.agent_name, 'gl<ah');
        assert.deepEqual(rep.ipaddress, '123.33.22.1');
        assert.deepEqual(rep.public_ips, ['123.45.55.44', '122.123.32.2']);
        assert.deepEqual(rep.opts, {
          option1: 'defaultval',
          option2: 'defaultval',
          option3: 'something'
        });
        assert.deepEqual(rep.data, {
          foo: 'thingone',
          bar: 'thingtwo'
        });
        assert.deepEqual(rep.state, 'active');
        test.finish();
      }
  );
};

exports['test_serial_array_xml'] = function(test, assert) {
  var blahnode = new Node();
  var blahnode2 = new Node();
  blahnode2.hash_id = '444';
  blahnode2.agent_name = 'your mom';
  var blaharr = [blahnode, blahnode2];
  var sw = new swiz.Swiz(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, blaharr,
      function(err, results)
      {

        assert.deepEqual(results, '<?xml version="1.0" encoding="UTF-8"?>' +
            '<group><Node><id>15245</id><is_active>true</' +
            'is_active><name>gggggg</name><agent_name>gl<ah</' +
            'agent_name><ipaddress>123.33.22.1</ipaddress>' +
            '<public_ips>123.45.55.44</public_ips>' +
            '<public_ips>122.123.32.2</public_ips>' +
            '<state>active</state>' +
            '<opts><NodeOpts>' +
            '<option1>defaultval</option1><option2>defaultval</option2>' +
            '<option3>something</option3></NodeOpts></opts>' +
            '<data><foo>thingone</foo><bar>thingtwo</bar></data></Node>' +
            '<Node><id>444</id><is_active>true</' +
            'is_active><name>gggggg</name><agent_name>your mom</' +
            'agent_name><ipaddress>123.33.22.1</ipaddress>' +
            '<public_ips>123.45.55.44</public_ips>' +
            '<public_ips>122.123.32.2</public_ips>' +
            '<state>active</state>' +
            '<opts><NodeOpts>' +
            '<option1>defaultval</option1><option2>defaultval</option2>' +
            '<option3>something</option3></NodeOpts></opts>' +
            '<data><foo>thingone</foo><bar>thingtwo</bar></data></Node>' +
            '</group>');

        test.finish();
      }
  );
};

exports['test_error_type'] = function(test, assert) {
  var blah = { };
  var sw = new swiz.Swiz(def);
  blah.getSerializerType = function() {return 'monito';};
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, blah,
      function(err, results)
      {
        assert.ok(err instanceof Error);

        test.finish();
      }
  );
};

exports['test_serial_array_json'] = function(test, assert) {
  var blahnode = new Node();
  var blahnode2 = new Node();
  blahnode2.hash_id = '444';
  blahnode2.agent_name = 'your mom';
  var blaharr = [blahnode, blahnode2];
  var sw = new swiz.Swiz(def);
  sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, blaharr,
      function(err, results)
      {
        var rep = JSON.parse(results);
        assert.deepEqual(rep[0].id, 15245);
        assert.deepEqual(rep[0].is_active, true);
        assert.deepEqual(rep[0].name, 'gggggg');
        assert.deepEqual(rep[0].agent_name, 'gl<ah');
        assert.deepEqual(rep[0].ipaddress, '123.33.22.1');
        assert.deepEqual(rep[0].public_ips,
            ['123.45.55.44', '122.123.32.2']);
        assert.deepEqual(rep[0].opts, {
          option1: 'defaultval',
          option2: 'defaultval',
          option3: 'something'
        });
        assert.deepEqual(rep[0].data, {
          foo: 'thingone',
          bar: 'thingtwo'
        });
        assert.deepEqual(rep[0].state, 'active');
        assert.deepEqual(rep[1].id, 444);
        assert.deepEqual(rep[1].is_active, true);
        assert.deepEqual(rep[1].name, 'gggggg');
        assert.deepEqual(rep[1].agent_name, 'your mom');
        assert.deepEqual(rep[1].ipaddress, '123.33.22.1');
        assert.deepEqual(rep[1].public_ips,
            ['123.45.55.44', '122.123.32.2']);
        assert.deepEqual(rep[1].opts, {
          option1: 'defaultval',
          option2: 'defaultval',
          option3: 'something'
        });
        assert.deepEqual(rep[1].data, {
          foo: 'thingone',
          bar: 'thingtwo'
        });
        assert.deepEqual(rep[1].state, 'active');
        test.finish();
      }
  );
};
<|endoftext|>


<commit_before>function setUpApp(bootstrapApp) {
	bootstrapApp();
}<commit_msg>appConfig to testSetup to pass tests.<commit_after>var appConfig = {

	'version': 'TAMU UI Seed',

	'allowAnonymous': true,

	// Set this to the webService if mocking AuthService

	'authService': 'https://labs.library.tamu.edu/authservice-dev',
	'webService': 'http://localhost:9000',

	'storageType': 'session',

	'logging': {
		'log': true,
		'info': true,
		'warn': true,
		'error': true,
		'debug': true
	},

	'stompDebug': false,

	/*
	Determines the type of connection stomp will attempt to make with the service.
	TYPES:  websocket, xhr-streaming, xdr-streaming, eventsource, iframe-eventsource,
			htmlfile, iframe-htmlfile, xhr-polling, xdr-polling, iframe-xhr-polling,
			jsonp-polling
	*/
	'sockJsConnectionType': ['websocket', 'iframe-eventsource',  'iframe-htmlfile', 'jsonp-polling'],

	// Set this to 'admin' or 'user' if using mock AuthService
	// otherwise set to null or false

	'mockRole': null
};

function setUpApp(bootstrapApp) {
	bootstrapApp();
}<|endoftext|>


<commit_before>// loosely adapted & updated from the example here:
// http://www.gethugames.in/blog/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html

var OAUTHURL    =   'https://accounts.google.com/o/oauth2/auth?';
var SCOPE       =   'https://www.googleapis.com/auth/userinfo.email';
var TYPE        =   'code';

function oauth2Login() {
  // construct redirect URI
  var REDIRECT = window.location.href;
  REDIRECT = REDIRECT.substring(0, REDIRECT.lastIndexOf("/"));
  REDIRECT += "/googleauth_callback.php";

  // get state (anti-forgery token) from session via CDash API
  $.get('api/getState.php', function(securityToken) {
    // overload state to contain both the URL that the user is attempting to
    // access, as well as the anti-forgery token.  slice is used here to remove
    // the trailing "#" from the currently URL
    var STATE = encodeURIComponent(document.URL.slice(0, -1)) + "_AND_STATE_IS_" + securityToken;

    // construct Google authentication URL with the query string all filled out
    var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID +
      '&redirect_uri=' + REDIRECT + '&state=' + STATE + '&response_type=' + TYPE;

    // redirect to the Google authentication page
    window.location = _url;
  });
}

<commit_msg>BUG: more reliable method of constructing redirect_uri for Google login<commit_after>// loosely adapted & updated from the example here:
// http://www.gethugames.in/blog/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html

var OAUTHURL    =   'https://accounts.google.com/o/oauth2/auth?';
var SCOPE       =   'https://www.googleapis.com/auth/userinfo.email';
var TYPE        =   'code';

function oauth2Login() {
  // construct redirect URI
  var REDIRECT = window.location.href;
  REDIRECT = REDIRECT.substring(0, REDIRECT.lastIndexOf(window.location.pathname));
  REDIRECT += "/googleauth_callback.php";

  // get state (anti-forgery token) from session via CDash API
  $.get('api/getState.php', function(securityToken) {
    // overload state to contain both the URL that the user is attempting to
    // access, as well as the anti-forgery token.  slice is used here to remove
    // the trailing "#" from the currently URL
    var STATE = encodeURIComponent(document.URL.slice(0, -1)) + "_AND_STATE_IS_" + securityToken;

    // construct Google authentication URL with the query string all filled out
    var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID +
      '&redirect_uri=' + REDIRECT + '&state=' + STATE + '&response_type=' + TYPE;

    // redirect to the Google authentication page
    window.location = _url;
  });
}

<|endoftext|>


<commit_before>// ==========================================================================
//                      DG.userEntryController
//
//  The controller for managing the user entry dialog.
//
//  Author:   Aaron Unger
//
//  Copyright (c) 2015 by The Concord Consortium, Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

sc_require('utilities/storage/codap_common_storage');

/** @class

  @extends SC.Object
*/
DG.userEntryController = SC.Object.create( DG.CODAPCommonStorage, (function() {
/** @scope DG.userEntryController.prototype */

  return {
    _dialog: null,

    _statusBinding: SC.Binding.oneWay('DG.authorizationController.currLogin.status'),
    _isPlaceholder: false,

    setup: function() {
      if (SC.none(this.get('_dialog'))) {
        this.set('_dialog', DG.UserEntryDialog.create());
      }

      // this binding gets initialized too early if specified alongside _status, so set it up here.
      SC.Binding.oneWay('DG.currDocumentController*content._isPlaceholder').to('DG.userEntryController._isPlaceholder').connect();
    },

    updateDialog: function() {
      var d = this.get('_dialog');
      if (!SC.none(d)) {
        if (this.get('_status') !== 0 && this.get('_isPlaceholder')) {
          if (!d.get('isAppended')) {
            d.append();
            d.setPath('contentView.choiceButtons.value', ['new']);
          }
        } else {
          d.remove();
        }
      }
    }.observes('_status', '_isPlaceholder', '_dialog'),

    openNewDocument: function() {
      var title = this._dialog.getPath('contentView.choiceViews.contentView.titleField.value');
      if (SC.none(title) || title.length === 0) {
        title = SC.String.loc('DG.Document.defaultDocumentName');
      }
      DG.currDocumentController().set('documentName', title);
      this._dialog.setPath('contentView.choiceViews.contentView.titleField.value', null);
      DG.currDocumentController().setPath('content._isPlaceholder', false);
      DG.dirtyCurrentDocument();
    },

    openExistingDocument: function() {
      var dialog = this._dialog.getPath('contentView.choiceViews.contentView');
      DG.appController.openSaveDialog = dialog;
      DG.appController.openDocumentFromDialog();
    },

    openExample: function() {
      var selected = this._dialog.getPath('contentView.choiceViews.contentView.selected');

      this._urlForGetRequests( selected.location )
      .notify(this, '_handleResponse',
        function(body) { DG.appController.receivedOpenDocumentSuccess(body, false); },
        function(errorCode) { DG.appController.receivedOpenDocumentFailure(errorCode, false); })
      .send();

      DG.logUser("openExample: '%@'", selected.location);
    },

    openFile: function() {
      var dialog = this._dialog.getPath('contentView.choiceViews.contentView'),
          fileList = dialog.get('value'),
          file = fileList && fileList[0];

      if (file) {
        if ((file.type && file.type === 'application/json')
          || (file.name && file.name.match( /.*\.json/i))) {
          DG.appController.importFileWithConfirmation( file, 'JSON', dialog);
        } else {
          dialog.showAlert('File, ' + file.name + ' is not of type JSON');
        }
      }
    }

  }; // return from function closure
}())); // function closure
<commit_msg>Wrap showAlert argument in an Error object and properly open a new document.<commit_after>// ==========================================================================
//                      DG.userEntryController
//
//  The controller for managing the user entry dialog.
//
//  Author:   Aaron Unger
//
//  Copyright (c) 2015 by The Concord Consortium, Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

sc_require('utilities/storage/codap_common_storage');

/** @class

  @extends SC.Object
*/
DG.userEntryController = SC.Object.create( DG.CODAPCommonStorage, (function() {
/** @scope DG.userEntryController.prototype */

  return {
    _dialog: null,

    _statusBinding: SC.Binding.oneWay('DG.authorizationController.currLogin.status'),
    _isPlaceholder: false,

    setup: function() {
      if (SC.none(this.get('_dialog'))) {
        this.set('_dialog', DG.UserEntryDialog.create());
      }

      // this binding gets initialized too early if specified alongside _status, so set it up here.
      SC.Binding.oneWay('DG.currDocumentController*content._isPlaceholder').to('DG.userEntryController._isPlaceholder').connect();
    },

    updateDialog: function() {
      var d = this.get('_dialog');
      if (!SC.none(d)) {
        if (this.get('_status') !== 0 && this.get('_isPlaceholder')) {
          if (!d.get('isAppended')) {
            d.append();
            d.setPath('contentView.choiceButtons.value', ['new']);
          }
        } else {
          d.remove();
        }
      }
    }.observes('_status', '_isPlaceholder', '_dialog'),

    openNewDocument: function() {
      DG.appController.closeAndNewDocument();
      var title = this._dialog.getPath('contentView.choiceViews.contentView.titleField.value');
      if (SC.none(title) || title.length === 0) {
        title = SC.String.loc('DG.Document.defaultDocumentName');
      }
      DG.currDocumentController().set('documentName', title);
      this._dialog.setPath('contentView.choiceViews.contentView.titleField.value', null);
      DG.currDocumentController().setPath('content._isPlaceholder', false);
      DG.dirtyCurrentDocument();
    },

    openExistingDocument: function() {
      var dialog = this._dialog.getPath('contentView.choiceViews.contentView');
      DG.appController.openSaveDialog = dialog;
      DG.appController.openDocumentFromDialog();
    },

    openExample: function() {
      var selected = this._dialog.getPath('contentView.choiceViews.contentView.selected');

      this._urlForGetRequests( selected.location )
      .notify(this, '_handleResponse',
        function(body) { DG.appController.receivedOpenDocumentSuccess(body, false); },
        function(errorCode) { DG.appController.receivedOpenDocumentFailure(errorCode, false); })
      .send();

      DG.logUser("openExample: '%@'", selected.location);
    },

    openFile: function() {
      var dialog = this._dialog.getPath('contentView.choiceViews.contentView'),
          fileList = dialog.get('value'),
          file = fileList && fileList[0];

      if (file) {
        if ((file.type && file.type === 'application/json')
          || (file.name && file.name.match( /.*\.json/i))) {
          DG.appController.importFileWithConfirmation( file, 'JSON', dialog);
        } else {
          dialog.showAlert(new Error('File, ' + file.name + ' is not of type JSON'));
        }
      }
    }

  }; // return from function closure
}())); // function closure
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules;

var DockerfileHighlightRules = function() {
    ShHighlightRules.call(this);

    var startRules = this.$rules.start;
    for (var i = 0; i < startRules.length; i++) {
        if (startRules[i].token == "variable.language") {
            startRules.splice(i, 0, {
                token: "variable.language",
                regex: "(?:^(?:FROM|MAINTAINER|RUN|CMD|EXPOSE|ENV|ADD|ENTRYPOINT|VOLUME|USER|WORKDIR|ONBUILD)\\b)",
                caseInsensitive: true
            });
            break;
        }
    }

};

oop.inherits(DockerfileHighlightRules, ShHighlightRules);

exports.DockerfileHighlightRules = DockerfileHighlightRules;
});
<commit_msg>Updated Dockerfile highlighter<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules;

var DockerfileHighlightRules = function() {
    ShHighlightRules.call(this);

    var startRules = this.$rules.start;
    for (var i = 0; i < startRules.length; i++) {
        if (startRules[i].token == "constant.language") {
            startRules.splice(i, 0, {
                token: "variable.language",
                regex: "(?:^(?:FROM|MAINTAINER|RUN|CMD|EXPOSE|ENV|ADD|ENTRYPOINT|VOLUME|USER|WORKDIR|ONBUILD)\\b)",
                caseInsensitive: true
            });
            break;
        }
    }

};

oop.inherits(DockerfileHighlightRules, ShHighlightRules);

exports.DockerfileHighlightRules = DockerfileHighlightRules;
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {

var oop = require("pilot/oop");
var lang = require("pilot/lang");
var DocCommentHighlightRules = require("ace/mode/doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;

var PowershellHighlightRules = function() {

    var keywords = lang.arrayToMap(
      ("function|if|else|elseif|switch|while|default|for|do|until|break|continue|foreach|return|filter|in|trap|throw|param|begin|process|end").split("|")
    );

    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [
            {
                token : "comment",
                regex : "#.*$"
            }, {
                token : "string", // single line
                regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
            }, {
                token : "string", // single line
                regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
            }, {
                token : "constant.numeric", // hex
                regex : "0[xX][0-9a-fA-F]+\\b"
            }, {
                token : "constant.numeric", // float
                regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
            }, {
                token : "constant.language.boolean",
                regex : "[$](?:[Tt]rue|[Ff]alse)\\b"
            }, {
                token : "constant.language.boolean",
                regex : "[$][Nn]ull\\b"
            }, {
                token : function(value) {
                    if (keywords.hasOwnProperty(value))
                        return "keyword";
                    else
                        return "identifier";
                },
                // TODO: Unicode escape sequences
                // TODO: Unicode identifiers
                regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
            }, {
                token : "keyword.operator",
                regex : "eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace"
            }, {
                token : "lparen",
                regex : "[[({]"
            }, {
                token : "rparen",
                regex : "[\\])}]"
            }, {
                token : "text",
                regex : "\\s+"
            }
        ],
        "comment" : [
            {
                token : "comment", // closing comment
                regex : ".*?\\*\\/",
                next : "start"
            }, {
                token : "comment", // comment spanning whole line
                merge : true,
                regex : ".+"
            }
        ]
    };

    this.embedRules(DocCommentHighlightRules, "doc-",
        [ new DocCommentHighlightRules().getEndRule("start") ]);
};

oop.inherits(PowershellHighlightRules, TextHighlightRules);

exports.PowershellHighlightRules = PowershellHighlightRules;
});
<commit_msg>Added in supportfor variables.<commit_after>define(function(require, exports, module) {

var oop = require("pilot/oop");
var lang = require("pilot/lang");
var DocCommentHighlightRules = require("ace/mode/doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;

var PowershellHighlightRules = function() {

    var keywords = lang.arrayToMap(
      ("function|if|else|elseif|switch|while|default|for|do|until|break|continue|foreach|return|filter|in|trap|throw|param|begin|process|end").split("|")
    );

    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [
            {
                token : "comment",
                regex : "#.*$"
            }, {
                token : "string", // single line
                regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
            }, {
                token : "string", // single line
                regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
            }, {
                token : "constant.numeric", // hex
                regex : "0[xX][0-9a-fA-F]+\\b"
            }, {
                token : "constant.numeric", // float
                regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
            }, {
                token : "constant.language.boolean",
                regex : "[$](?:[Tt]rue|[Ff]alse)\\b"
            }, {
                token : "constant.language",
                regex : "[$][Nn]ull\\b"
            }, {
                token : "variable.instance",
                regex : "[$][a-zA-Z][a-zA-Z0-9_]*\\b"
            }, {
                token : function(value) {
                    if (keywords.hasOwnProperty(value))
                        return "keyword";
                    else
                        return "identifier";
                },
                // TODO: Unicode escape sequences
                // TODO: Unicode identifiers
                regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
            }, {
                token : "keyword.operator",
                regex : "eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace"
            }, {
                token : "lparen",
                regex : "[[({]"
            }, {
                token : "rparen",
                regex : "[\\])}]"
            }, {
                token : "text",
                regex : "\\s+"
            }
        ],
        "comment" : [
            {
                token : "comment", // closing comment
                regex : ".*?\\*\\/",
                next : "start"
            }, {
                token : "comment", // comment spanning whole line
                merge : true,
                regex : ".+"
            }
        ]
    };

    this.embedRules(DocCommentHighlightRules, "doc-",
        [ new DocCommentHighlightRules().getEndRule("start") ]);
};

oop.inherits(PowershellHighlightRules, TextHighlightRules);

exports.PowershellHighlightRules = PowershellHighlightRules;
});
<|endoftext|>