<commit_before>'use strict';

var categoriesRouter = require('../../../src/routes/categories'),
    assert = require('assert'),
    connection = require('../../db_common'),
    User = require('../../../src/models/user'),
    Category = require('../../../src/models/category'),
    HttpStatus = require('http-status'),
    mongoose = require('mongoose');

describe('Categories Routes', function () {

    var db, user, category, req, res;

    before(function (done) {
        //TODO: use callback
        db = connection();

        User.create({ name: 'Iliyan Trifonov' }, function (err, doc) {
            assert.ifError(err);
            assert.ok(doc !== null);

            user = doc;

            Category.create({
                name: 'Sample Category',
                user: doc._id
            }, function (err, cat) {
                assert.ifError(err);
                assert.ok(cat !== null);

                category = cat;

                done();
            });
        });
    });

    after(function () {
        db.close();
    });

    beforeEach(function () {
        req = res = {};
        req.user = user;
    });

    describe('GET /categories', function () {
        it('should return status 200 and response type json with categories body', function (done) {
            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.OK);
                return this;
            };

            res.json = function (cats) {
                assert.ok(cats);
                assert.strictEqual(cats.length, 1);
                assert.ok(cats[0]._id.equals(category._id));
                assert.strictEqual(cats[0].name, category.name);
                assert.strictEqual(cats[0].notepadsCount, category.notepadsCount);
                done();
            };

            categoriesRouter.getHandler(req, res);
        });
    });

    describe('POST /categories', function () {
        it('should add new Category and assign it to the user', function (done) {
            var testCat = { name: 'Test cat ' + (+new Date()) };

            req.body = { name: testCat.name };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.OK);
                return this;
            };

            res.json = function (cat) {
                assert.ok(cat);
                assert.strictEqual(cat.name, testCat.name);
                User.find({ category: cat._id }, function (err, user) {
                    assert.ifError(err);
                    assert.ok(user !== null);

                    done();
                });
            };

            categoriesRouter.postHandler(req, res);
        });
    });

    describe('GET /categories/:id', function () {
        it('should return status 200 and the required Category', function (done) {
            req = {
                params : { id: category._id },
                user: { id: user._id }
            };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.OK);
                return this;
            };

            res.json = function (cat) {
                assert.ok(cat._id.equals(category._id));
                assert.strictEqual(cat.name, category.name);

                done();
            };

            categoriesRouter.getIdHandler(req, res);
        });

        it('should return status 204 and an empty object result for a given non-existent id', function (done) {
            req = {
                params : { id: mongoose.Schema.ObjectId() },
                user: { id: user._id }
            };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.NO_CONTENT);
                return this;
            };

            res.json = function (cat) {
                assert.deepEqual(cat, {});

                done();
            };

            categoriesRouter.getIdHandler(req, res);
        });

        it('should return status 500 and a json error object result for a wrong cat id format given', function (done) {
            req = {
                params : { id: 123 },
                user: { id: user._id }
            };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.INTERNAL_SERVER_ERROR);
                return this;
            };

            res.json = function (err) {
                assert.strictEqual(err.name, 'CastError');
                assert.strictEqual(err.kind, 'ObjectId');
                assert.strictEqual(err.path, '_id');

                done();
            };

            categoriesRouter.getIdHandler(req, res);
        });
    });

    describe('PUT /categories/:id', function () {
        it('should update a Category\'s name given its id, uid and name', function (done) {
            var newCatName = 'New Cat Name';
            req = {
                params: { id: category._id },
                user: { id: user._id },
                body: { name: newCatName }
            };
            res = {
                status: function (status) {
                    assert.strictEqual(status, HttpStatus.OK);
                    return this;
                },
                json: function (cat) {
                    assert.strictEqual(cat.name, newCatName);
                    category = cat;
                    done();
                }
            };
            categoriesRouter.putIdHandler(req, res);
        });

        it('should not update given a non-existent cat id', function (done) {
            req = {
                params: { id: mongoose.Schema.ObjectId(123123123123) },
                user: { id: user._id },
                body: { name: 'asdasdasd' }
            };
            res = {
                status: function (status) {
                    assert.strictEqual(status, HttpStatus.NO_CONTENT);
                    return this;
                },
                json: function (cat) {
                    assert.deepEqual(cat, {});
                    done();
                }
            };
            categoriesRouter.putIdHandler(req, res);
        });
    });

});
<commit_msg>WIP: defined delete category handler tests<commit_after>'use strict';

var categoriesRouter = require('../../../src/routes/categories'),
    assert = require('assert'),
    connection = require('../../db_common'),
    User = require('../../../src/models/user'),
    Category = require('../../../src/models/category'),
    HttpStatus = require('http-status'),
    mongoose = require('mongoose');

describe('Categories Routes', function () {

    var db, user, category, req, res;

    before(function (done) {
        //TODO: use callback
        db = connection();

        User.create({ name: 'Iliyan Trifonov' }, function (err, doc) {
            assert.ifError(err);
            assert.ok(doc !== null);

            user = doc;

            Category.create({
                name: 'Sample Category',
                user: doc._id
            }, function (err, cat) {
                assert.ifError(err);
                assert.ok(cat !== null);

                category = cat;

                done();
            });
        });
    });

    after(function () {
        db.close();
    });

    beforeEach(function () {
        req = res = {};
        req.user = user;
    });

    describe('GET /categories', function () {
        it('should return status 200 and response type json with categories body', function (done) {
            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.OK);
                return this;
            };

            res.json = function (cats) {
                assert.ok(cats);
                assert.strictEqual(cats.length, 1);
                assert.ok(cats[0]._id.equals(category._id));
                assert.strictEqual(cats[0].name, category.name);
                assert.strictEqual(cats[0].notepadsCount, category.notepadsCount);
                done();
            };

            categoriesRouter.getHandler(req, res);
        });
    });

    describe('POST /categories', function () {
        it('should add new Category and assign it to the user', function (done) {
            var testCat = { name: 'Test cat ' + (+new Date()) };

            req.body = { name: testCat.name };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.OK);
                return this;
            };

            res.json = function (cat) {
                assert.ok(cat);
                assert.strictEqual(cat.name, testCat.name);
                User.find({ category: cat._id }, function (err, user) {
                    assert.ifError(err);
                    assert.ok(user !== null);

                    done();
                });
            };

            categoriesRouter.postHandler(req, res);
        });
    });

    describe('GET /categories/:id', function () {
        it('should return status 200 and the required Category', function (done) {
            req = {
                params : { id: category._id },
                user: { id: user._id }
            };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.OK);
                return this;
            };

            res.json = function (cat) {
                assert.ok(cat._id.equals(category._id));
                assert.strictEqual(cat.name, category.name);

                done();
            };

            categoriesRouter.getIdHandler(req, res);
        });

        it('should return status 204 and an empty object result for a given non-existent id', function (done) {
            req = {
                params : { id: mongoose.Schema.ObjectId() },
                user: { id: user._id }
            };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.NO_CONTENT);
                return this;
            };

            res.json = function (cat) {
                assert.deepEqual(cat, {});

                done();
            };

            categoriesRouter.getIdHandler(req, res);
        });

        it('should return status 500 and a json error object result for a wrong cat id format given', function (done) {
            req = {
                params : { id: 123 },
                user: { id: user._id }
            };

            res.status = function (status) {
                assert.strictEqual(status, HttpStatus.INTERNAL_SERVER_ERROR);
                return this;
            };

            res.json = function (err) {
                assert.strictEqual(err.name, 'CastError');
                assert.strictEqual(err.kind, 'ObjectId');
                assert.strictEqual(err.path, '_id');

                done();
            };

            categoriesRouter.getIdHandler(req, res);
        });
    });

    describe('PUT /categories/:id', function () {
        it('should update a Category\'s name given its id, uid and name', function (done) {
            var newCatName = 'New Cat Name';
            req = {
                params: { id: category._id },
                user: { id: user._id },
                body: { name: newCatName }
            };
            res = {
                status: function (status) {
                    assert.strictEqual(status, HttpStatus.OK);
                    return this;
                },
                json: function (cat) {
                    assert.strictEqual(cat.name, newCatName);
                    category = cat;
                    done();
                }
            };
            categoriesRouter.putIdHandler(req, res);
        });

        it('should not update given a non-existent cat id', function (done) {
            req = {
                params: { id: mongoose.Schema.ObjectId(123123123123) },
                user: { id: user._id },
                body: { name: 'asdasdasd' }
            };
            res = {
                status: function (status) {
                    assert.strictEqual(status, HttpStatus.NO_CONTENT);
                    return this;
                },
                json: function (cat) {
                    assert.deepEqual(cat, {});
                    done();
                }
            };
            categoriesRouter.putIdHandler(req, res);
        });
    });

    describe('DELETE /categories/:id', function () {
        it('should return NO CONTENT given a non-existent category id');
        it('should delete a category, update categories in user and delete all notepads belonging to that category');
    });

});
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * String output engine.
 *
 * Ultra fast string rendering.
 * Ommits all dom specific stuffs, obviously doesn't produce DOM node, doesn't apply bindings, etc.
 * Only constructs directly the needed string result.
 *
 * That allows really FAST execution of template server side.
 * (on my dev machine :  under nodejs, for a full page with 1250 nodes it takes approximatly 0.250 ms to output ;)
 * That IS smart isomorphism :
 * Templates are kept as descriptive as needed
 * to have multiple output engines
 * that loop through arrays of descriptors
 * and execute associated pure dedicated functions.
 *
 * This output engine needs stabilised context. (see context stabilisation in docs).
 *
 * There is a third output engine that manage contexts tree loads and stabilisation before applying string output. (aka twopass engine)
 */
var utils = require('../utils'),
	openTags = require('../parsers/open-tags'),
	strictTags = /span|script|meta|div|i/,
	Context = require('../context').Context,
	Template = require('../template');

// String Output Descriptor
function SOD() {
	this.attributes = '';
	this.classes = '';
	this.children = '';
	this.style = '';
}

function tagOutput(descriptor, innerDescriptor, name) {
	var out = '<' + name + innerDescriptor.attributes;
	if (innerDescriptor.style)
		out += ' style="' + innerDescriptor.style + '"';
	if (innerDescriptor.classes)
		out += ' class="' + innerDescriptor.classes + '"';
	if (innerDescriptor.children)
		descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
	else if (openTags.test(name))
		descriptor.children += out + '>';
	else if (strictTags.test(name))
		descriptor.children += out + '></' + name + '>';
	else
		descriptor.children += out + '/>';
}
utils.tagOutput = tagOutput;

var methods = {
	SOD: SOD,
	//_________________________________ local context management
	newContext: function(context, descriptor, args) {
		var data = args[0],
			parent = args[1] || context,
			path = args[2];
		descriptor.context = new Context(data, parent, path);
	},
	//_________________________________________ EACH
	each: function(context, descriptor, args) {
		var path = args[0],
			values = (typeof path === 'string') ? context.get(path) : path;
		if (values && values.length) {
			var template = args[1];
			for (var i = 0, len = values.length; i < len; ++i)
				template.toHTMLString(new Context(values[i], context), descriptor);
		} else if (args[2])
			args[2].toHTMLString(context, descriptor);
	},
	eachTemplates: function(context, descriptor, args) {
		var templates = args[0],
			handler = args[1];
		templates.forEach(function(templ) {
			(handler ? handler(templ) : templ).toHTMLString(context, descriptor);
		});
	},
	// ____________________________________ WITH
	with: function(context, descriptor, args) {
		var path = args[0],
			template = args[1];
		var ctx = new Context(typeof path === 'string' ? context.get(path) : path, context, path);
		template.toHTMLString(ctx, descriptor);
	},
	//______________________________________________
	mountIf: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		var sod = new SOD();
		if (ok)
			successTempl.toHTMLString(context, sod);
		else if (failTempl)
			failTempl.toHTMLString(context, sod);
		if (sod.children)
			descriptor.children += sod.children;
	},
	agoraView: function(context, args) {
		// var channel = args[0],
		// template = args[1];
		// console.warn('agoraView has not been implemented yet for string engine.');
	},
	//______________________________________________
	if: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		if (ok)
			successTempl.toHTMLString(context, descriptor);
		else if (failTempl)
			failTempl.toHTMLString(context, descriptor);
	},
	switch: function(context, descriptor, args) {
		var xpr = args[0],
			dico = args[1],
			value = xpr.output(context),
			templ = dico[value] || dico['default'];
		if (templ) {
			var sod = new SOD();
			templ.toHTMLString(context, sod);
			if (sod.children)
				descriptor.children += sod.children;
		}
	},
	//________________________________ TAGS
	tag: function(context, descriptor, originalArgs) {
		var name = originalArgs[0],
			template = originalArgs[1];
		var newDescriptor = new SOD();
		template.toHTMLString(context, newDescriptor);
		tagOutput(descriptor, newDescriptor, name);
	},
	text: function(context, descriptor, args) {
		var value = args[0];
		descriptor.children += value.__interpolable__ ? value.output(context) : value;
	},
	raw: function(context, descriptor, args) {
		descriptor.children += args[0];
	},
	br: function(context, descriptor) {
		descriptor.children += '
';
	},
	//______________________________________________ ATTRIBUTES
	attr: function(context, descriptor, args) {
		var name = args[0],
			value = args[1];
		descriptor.attributes += ' ' + name + (value ? ('="' + (value.__interpolable__ ? value.output(context) : value) + '"') : '');
	},
	disabled: function(context, descriptor, args) {
		var value = args[0];
		if (value === undefined || context.get(value))
			descriptor.attributes += ' disabled';
	},
	val: function(context, descriptor, args) {
		var path = args[0],
			value = args[1];
		descriptor.attributes += ' value="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	contentEditable: function(context, descriptor, args) {
		var value = args[1];
		descriptor.attributes += ' contenteditable';
		descriptor.children = value.output(context);
	},
	setClass: function(context, descriptor, args) {
		var name = args[0],
			flag = args[1];
		if ((flag.__interpolable__ && flag.output(context)) || flag)
			descriptor.classes += (descriptor.classes ? ' ' : '') + (name.__interpolable__ ? name.output(context) : name);
	},
	css: function(context, descriptor, args) {
		var prop = args[0],
			value = args[1];
		descriptor.style += prop + ':' + (value.__interpolable__ ? value.output(context) : value);
	},
	visible: function(context, descriptor, args) {
		var flag = args[0],
			val = flag.__interpolable__ ? flag.output(context) : flag;
		if (!val)
			descriptor.style += 'display:none;';
	},
	//_________________________________ EVENTS
	on: function() {},
	once: function() {},
	off: function() {},
	//_________________________________ CLIENT/SERVER
	client: function(context, descriptor, args) {
		if (context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	server: function(context, descriptor, args) {
		if (!context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	//_______________________________ SUSPEND RENDER
	suspendUntil: function(context, descriptor, args) {
		var xpr = args[0],
			index = args[1],
			templ = args[2],
			val = xpr.__interpolable__ ? xpr.output(context) : xpr,
			rest = new Template(templ._queue.slice(index));
		if (val)
			rest.toHTMLString(context, descriptor);
	},
	container: function(context, descriptor, args) {
		var sod = new SOD(),
			opt = args[0],
			template = args[1];
		template.toHTMLString(context, sod);
		descriptor.children += sod.children;
	}
};

Template.prototype.toHTMLString = function(context, descriptor) {
	context = context || new Context();
	descriptor = descriptor ||  new SOD();
	var handler = this._queue[0],
		index = 0,
		f;
	while (handler) {
		f = null;
		switch (handler.type) {
			case '*':
				f = methods[handler.handler];
				break;
			case 'string':
			case 'context':
				f = handler.handler;
				break;
			case 'custom':
				f = handler.handler.string;
				break;
		}
		if (!f) {
			handler = this._queue[++index];
			continue;
		}
		if (f.__yTemplate__)
			f.toHTMLString(descriptor.context || context, descriptor);
		else
			f(descriptor.context || context, descriptor, handler.args);
		if (handler.suspendAfter)
			break;
		handler = this._queue[++index];
	}
	return descriptor.children;
};

module.exports = methods;
<commit_msg>clean string engine .visible flag management<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * String output engine.
 *
 * Ultra fast string rendering.
 * Ommits all dom specific stuffs, obviously doesn't produce DOM node, doesn't apply bindings, etc.
 * Only constructs directly the needed string result.
 *
 * That allows really FAST execution of template server side.
 * (on my dev machine :  under nodejs, for a full page with 1250 nodes it takes approximatly 0.250 ms to output ;)
 * That IS smart isomorphism :
 * Templates are kept as descriptive as needed
 * to have multiple output engines
 * that loop through arrays of descriptors
 * and execute associated pure dedicated functions.
 *
 * This output engine needs stabilised context. (see context stabilisation in docs).
 *
 * There is a third output engine that manage contexts tree loads and stabilisation before applying string output. (aka twopass engine)
 */
var utils = require('../utils'),
	openTags = require('../parsers/open-tags'),
	strictTags = /span|script|meta|div|i/,
	Context = require('../context').Context,
	Template = require('../template');

// String Output Descriptor
function SOD() {
	this.attributes = '';
	this.classes = '';
	this.children = '';
	this.style = '';
}

function tagOutput(descriptor, innerDescriptor, name) {
	var out = '<' + name + innerDescriptor.attributes;
	if (innerDescriptor.style)
		out += ' style="' + innerDescriptor.style + '"';
	if (innerDescriptor.classes)
		out += ' class="' + innerDescriptor.classes + '"';
	if (innerDescriptor.children)
		descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
	else if (openTags.test(name))
		descriptor.children += out + '>';
	else if (strictTags.test(name))
		descriptor.children += out + '></' + name + '>';
	else
		descriptor.children += out + '/>';
}
utils.tagOutput = tagOutput;

var methods = {
	SOD: SOD,
	//_________________________________ local context management
	newContext: function(context, descriptor, args) {
		var data = args[0],
			parent = args[1] || context,
			path = args[2];
		descriptor.context = new Context(data, parent, path);
	},
	//_________________________________________ EACH
	each: function(context, descriptor, args) {
		var path = args[0],
			values = (typeof path === 'string') ? context.get(path) : path;
		if (values && values.length) {
			var template = args[1];
			for (var i = 0, len = values.length; i < len; ++i)
				template.toHTMLString(new Context(values[i], context), descriptor);
		} else if (args[2])
			args[2].toHTMLString(context, descriptor);
	},
	eachTemplates: function(context, descriptor, args) {
		var templates = args[0],
			handler = args[1];
		templates.forEach(function(templ) {
			(handler ? handler(templ) : templ).toHTMLString(context, descriptor);
		});
	},
	// ____________________________________ WITH
	with: function(context, descriptor, args) {
		var path = args[0],
			template = args[1];
		var ctx = new Context(typeof path === 'string' ? context.get(path) : path, context, path);
		template.toHTMLString(ctx, descriptor);
	},
	//______________________________________________
	mountIf: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		var sod = new SOD();
		if (ok)
			successTempl.toHTMLString(context, sod);
		else if (failTempl)
			failTempl.toHTMLString(context, sod);
		if (sod.children)
			descriptor.children += sod.children;
	},
	agoraView: function(context, args) {
		// var channel = args[0],
		// template = args[1];
		// console.warn('agoraView has not been implemented yet for string engine.');
	},
	//______________________________________________
	if: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		if (ok)
			successTempl.toHTMLString(context, descriptor);
		else if (failTempl)
			failTempl.toHTMLString(context, descriptor);
	},
	switch: function(context, descriptor, args) {
		var xpr = args[0],
			dico = args[1],
			value = xpr.output(context),
			templ = dico[value] || dico['default'];
		if (templ) {
			var sod = new SOD();
			templ.toHTMLString(context, sod);
			if (sod.children)
				descriptor.children += sod.children;
		}
	},
	//________________________________ TAGS
	tag: function(context, descriptor, originalArgs) {
		var name = originalArgs[0],
			template = originalArgs[1];
		var newDescriptor = new SOD();
		template.toHTMLString(context, newDescriptor);
		tagOutput(descriptor, newDescriptor, name);
	},
	text: function(context, descriptor, args) {
		var value = args[0];
		descriptor.children += value.__interpolable__ ? value.output(context) : value;
	},
	raw: function(context, descriptor, args) {
		descriptor.children += args[0];
	},
	br: function(context, descriptor) {
		descriptor.children += '
';
	},
	//______________________________________________ ATTRIBUTES
	attr: function(context, descriptor, args) {
		var name = args[0],
			value = args[1];
		descriptor.attributes += ' ' + name + (value ? ('="' + (value.__interpolable__ ? value.output(context) : value) + '"') : '');
	},
	disabled: function(context, descriptor, args) {
		var value = args[0];
		if (value === undefined || context.get(value))
			descriptor.attributes += ' disabled';
	},
	val: function(context, descriptor, args) {
		var path = args[0],
			value = args[1];
		descriptor.attributes += ' value="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	contentEditable: function(context, descriptor, args) {
		var value = args[1];
		descriptor.attributes += ' contenteditable';
		descriptor.children = value.output(context);
	},
	setClass: function(context, descriptor, args) {
		var name = args[0],
			flag = args[1];
		if ((flag.__interpolable__ && flag.output(context)) || flag)
			descriptor.classes += (descriptor.classes ? ' ' : '') + (name.__interpolable__ ? name.output(context) : name);
	},
	css: function(context, descriptor, args) {
		var prop = args[0],
			value = args[1];
		descriptor.style += prop + ':' + (value.__interpolable__ ? value.output(context) : value);
	},
	visible: function(context, descriptor, args) {
		var flag = args[0],
			val = (flag && flag.__interpolable__) ? flag.output(context) : flag;
		if (!val)
			descriptor.style += 'display:none;';
	},
	//_________________________________ EVENTS
	on: function() {},
	once: function() {},
	off: function() {},
	//_________________________________ CLIENT/SERVER
	client: function(context, descriptor, args) {
		if (context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	server: function(context, descriptor, args) {
		if (!context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	//_______________________________ SUSPEND RENDER
	suspendUntil: function(context, descriptor, args) {
		var xpr = args[0],
			index = args[1],
			templ = args[2],
			val = xpr.__interpolable__ ? xpr.output(context) : xpr,
			rest = new Template(templ._queue.slice(index));
		if (val)
			rest.toHTMLString(context, descriptor);
	},
	container: function(context, descriptor, args) {
		var sod = new SOD(),
			opt = args[0],
			template = args[1];
		template.toHTMLString(context, sod);
		descriptor.children += sod.children;
	}
};

Template.prototype.toHTMLString = function(context, descriptor) {
	context = context || new Context();
	descriptor = descriptor ||  new SOD();
	var handler = this._queue[0],
		index = 0,
		f;
	while (handler) {
		f = null;
		switch (handler.type) {
			case '*':
				f = methods[handler.handler];
				break;
			case 'string':
			case 'context':
				f = handler.handler;
				break;
			case 'custom':
				f = handler.handler.string;
				break;
		}
		if (!f) {
			handler = this._queue[++index];
			continue;
		}
		if (f.__yTemplate__)
			f.toHTMLString(descriptor.context || context, descriptor);
		else
			f(descriptor.context || context, descriptor, handler.args);
		if (handler.suspendAfter)
			break;
		handler = this._queue[++index];
	}
	return descriptor.children;
};

module.exports = methods;
<|endoftext|>


<commit_before>module.exports = QuadTree;

var Pool = require('./Pool.js');
var Vec2 = require('./Vec2.js');

/**
 * Effectively store positional and sized objects. Each tree has a position and
 * size, as well as up to 4 child nodes (other trees) and an array of entries.
 * @constructor
 */
function QuadTree()
{
  this.level = 0;
  this.position = new Vec2();
  this.size = new Vec2();

  /**
   * @type {Array.<QuadTree>}
   */
  this.nodes = [];

  /**
   * @type {Array.<Entry>}
   */
  this.entries = [];
}

/**
 * Max number of entries in a node before it splits
 * @const
 */
QuadTree.MAX_ENTRIES = 15;

/**
 * Max depth the tree will split
 * @const
 */
QuadTree.MAX_LEVELS = 6;

/**
 * A single item in the tree, contiains a pointer back to the node its in as
 * well as the spatial information of where its at.
 * @constructor
 */
QuadTree.Entry = Entry;
function Entry()
{
  this.obj      = null;
  this.node     = null;
  this.position = new Vec2();
  this.hwidth   = new Vec2();
}

// Static Pools
QuadTree.pool = new Pool(QuadTree);
Entry.pool = new Pool(Entry);

QuadTree.prototype.__init = function()
{
  this.level = 0;
  this.position.clear();
  this.size.clear();
  this.nodes.length = 0;
  this.entries.length = 0;
};

Entry.prototype.__init = function()
{
  this.obj = null;
  this.node = null;
  this.position.clear();
  this.hwidth.clear();
};

/**
 * Pack an object into an entry and add it to the tree.
 * @param {Object} object
 * @param {Vec2} position
 * @param {Vec2} hwidth
 */
QuadTree.prototype.insert = function(object, position, hwidth)
{
  var entry = Entry.pool.aquire();
  entry.obj = object;
  entry.position.assign(position);
  entry.hwidth.assign(hwidth);
  return this.insertEntry(entry);
};

/**
 * Add item to tree that is already packed into an entry.
 * @param {Entry} entry
 */
QuadTree.prototype.insertEntry = function(entry)
{
  // Delegate insertion to a child node if we can
  if (this.nodes.length) {
    var index = this.getIndex(entry.position, entry.hwidth);
    if (~index) return this.nodes[index].insertEntry(entry);
  }

  this.entries.push(entry);
  entry.node = this;

  this.splitAndRedistrubuteIfNeeded();
  return entry;
};

/**
 * Return which of the 4 quandrants an object would go into. Object's are
 * defined by their size vector which defines a rectangle where position is the
 * TOP LEFT point (non-offset).
 * @param {Vec2} position
 * @param {Vec2} hwidth
 * @return {Number} Which quandrant, or -1 if won't fit.
 */
QuadTree.prototype.getIndex = function(position, hwidth)
{
  var midX = this.position.x + this.size.x / 2;
  var midY = this.position.y + this.size.y / 2;

  var left   = position.x - hwidth.x < midX && position.x + hwidth.x < midX;
  var right  = position.x - hwidth.x > midX && position.x + hwidth.x > midX;
  var top    = position.y - hwidth.y < midY && position.y + hwidth.y < midY;
  var bottom = position.y - hwidth.y > midY && position.y + hwidth.y > midY;

  if (top && right) return 0;
  if (top && left) return 1;
  if (bottom && left) return 2;
  if (bottom && right) return 3;

  return -1;
};

/**
 * If we've overpacked this tree, then split into 4 smaller trees (if we
 * haven't already) and redistribute.
 */
QuadTree.prototype.splitAndRedistributeIfNeeded = function()
{
  if (this.entries.length > QuadTree.MAX_ENTRIES &&
    this.level < QuadTree.MAX_LEVELS)
  {
    this.split();
    this.redistribute();
  }
};

/**
 * Create 4 sub nodes for the tree (does not populate tho)
 */
QuadTree.prototype.split = function()
{
  if (this.nodes.length) return;

  var x = this.position.x;
  var y = this.position.y;

  var w = this.size.x / 2;
  var h = this.size.y / 2;

  // Create the seperate nodes
  for (var n = 0; n < 4; n++) {
    var node = QuadTree.pool.aquire();
    node.level = this.level + 1;
    node.size.set(w, h);

    switch(n) {
      case 0:
        node.position.set(x + w, y);
        break;
      case 1:
        node.position.set(x, y);
        break;
      case 2:
        node.position.set(x, y + h);
        break;
      case 3:
        node.position.set(x + w, y + h);
        break;
    }

    this.nodes.push(node);
  }
};

/**
 * Distrubute all entrys into child nodes if we can.
 */
QuadTree.prototype.redistribute = function()
{
  // Loop through all of our entries and if they can fit into a child node,
  // move them there
  var i = 0;
  while (i < this.entries.length) {
    var entry = this.entries[i];
    var index = this.getIndex(entry.position, entry.hwidth);

    // Insert into child, remove from our array if they belong in another node
    if (~index) {
      this.nodes[index].insertEntry(entry);
      this.entries.splice(i, 1);
    } else {
      i++;
    }
  }
};

/**
 * Removes an entry from the tree (but does NOT release it back to the pool!!)
 * @param {Entry} entry
 */
QuadTree.prototype.removeEntry = function(entry)
{

};

/**
 * Re-insert an entry in order to get it to the right place in the tree.
 */
QuadTree.prototype.reinsertEntry = function(entry)
{

};

/**
 * Returns true if the passed entry is still okay where its at. Returning false
 * means would she re-insert it into the tree in order to put it in its correct
 * place.
 * @param {Entry} param
 */
QuadTree.prototype.isEntryStillGood = function(entry)
{

};

/**
 * @param {Vec2} position
 * @param {Vec2} size
 * @param {Array.<Entry>=} out__objects Return objects.
 */
QuadTree.prototype.getEntries = function(position, size, out__objects)
{

};

/**
 * Empty the tree recursively.
 */
QuadTree.prototype.clear = function()
{

};

/**
 * Unwinds this node. Move all child nodes into this node and remove child
 * nodes.
 */
QuadTree.prototype.combine = function()
{

};

<commit_msg>Spelling lol<commit_after>module.exports = QuadTree;

var Pool = require('./Pool.js');
var Vec2 = require('./Vec2.js');

/**
 * Effectively store positional and sized objects. Each tree has a position and
 * size, as well as up to 4 child nodes (other trees) and an array of entries.
 * @constructor
 */
function QuadTree()
{
  this.level = 0;
  this.position = new Vec2();
  this.size = new Vec2();

  /**
   * @type {Array.<QuadTree>}
   */
  this.nodes = [];

  /**
   * @type {Array.<Entry>}
   */
  this.entries = [];
}

/**
 * Max number of entries in a node before it splits
 * @const
 */
QuadTree.MAX_ENTRIES = 15;

/**
 * Max depth the tree will split
 * @const
 */
QuadTree.MAX_LEVELS = 6;

/**
 * A single item in the tree, contiains a pointer back to the node its in as
 * well as the spatial information of where its at.
 * @constructor
 */
QuadTree.Entry = Entry;
function Entry()
{
  this.obj      = null;
  this.node     = null;
  this.position = new Vec2();
  this.hwidth   = new Vec2();
}

// Static Pools
QuadTree.pool = new Pool(QuadTree);
Entry.pool = new Pool(Entry);

QuadTree.prototype.__init = function()
{
  this.level = 0;
  this.position.clear();
  this.size.clear();
  this.nodes.length = 0;
  this.entries.length = 0;
};

Entry.prototype.__init = function()
{
  this.obj = null;
  this.node = null;
  this.position.clear();
  this.hwidth.clear();
};

/**
 * Pack an object into an entry and add it to the tree.
 * @param {Object} object
 * @param {Vec2} position
 * @param {Vec2} hwidth
 */
QuadTree.prototype.insert = function(object, position, hwidth)
{
  var entry = Entry.pool.aquire();
  entry.obj = object;
  entry.position.assign(position);
  entry.hwidth.assign(hwidth);
  return this.insertEntry(entry);
};

/**
 * Add item to tree that is already packed into an entry.
 * @param {Entry} entry
 */
QuadTree.prototype.insertEntry = function(entry)
{
  // Delegate insertion to a child node if we can
  if (this.nodes.length) {
    var index = this.getIndex(entry.position, entry.hwidth);
    if (~index) return this.nodes[index].insertEntry(entry);
  }

  this.entries.push(entry);
  entry.node = this;

  this.splitAndRedistributeIfNeeded();
  return entry;
};

/**
 * Return which of the 4 quandrants an object would go into. Object's are
 * defined by their size vector which defines a rectangle where position is the
 * TOP LEFT point (non-offset).
 * @param {Vec2} position
 * @param {Vec2} hwidth
 * @return {Number} Which quandrant, or -1 if won't fit.
 */
QuadTree.prototype.getIndex = function(position, hwidth)
{
  var midX = this.position.x + this.size.x / 2;
  var midY = this.position.y + this.size.y / 2;

  var left   = position.x - hwidth.x < midX && position.x + hwidth.x < midX;
  var right  = position.x - hwidth.x > midX && position.x + hwidth.x > midX;
  var top    = position.y - hwidth.y < midY && position.y + hwidth.y < midY;
  var bottom = position.y - hwidth.y > midY && position.y + hwidth.y > midY;

  if (top && right) return 0;
  if (top && left) return 1;
  if (bottom && left) return 2;
  if (bottom && right) return 3;

  return -1;
};

/**
 * If we've overpacked this tree, then split into 4 smaller trees (if we
 * haven't already) and redistribute.
 */
QuadTree.prototype.splitAndRedistributeIfNeeded = function()
{
  if (this.entries.length > QuadTree.MAX_ENTRIES &&
    this.level < QuadTree.MAX_LEVELS)
  {
    this.split();
    this.redistribute();
  }
};

/**
 * Create 4 sub nodes for the tree (does not populate tho)
 */
QuadTree.prototype.split = function()
{
  if (this.nodes.length) return;

  var x = this.position.x;
  var y = this.position.y;

  var w = this.size.x / 2;
  var h = this.size.y / 2;

  // Create the seperate nodes
  for (var n = 0; n < 4; n++) {
    var node = QuadTree.pool.aquire();
    node.level = this.level + 1;
    node.size.set(w, h);

    switch(n) {
      case 0:
        node.position.set(x + w, y);
        break;
      case 1:
        node.position.set(x, y);
        break;
      case 2:
        node.position.set(x, y + h);
        break;
      case 3:
        node.position.set(x + w, y + h);
        break;
    }

    this.nodes.push(node);
  }
};

/**
 * Distrubute all entrys into child nodes if we can.
 */
QuadTree.prototype.redistribute = function()
{
  // Loop through all of our entries and if they can fit into a child node,
  // move them there
  var i = 0;
  while (i < this.entries.length) {
    var entry = this.entries[i];
    var index = this.getIndex(entry.position, entry.hwidth);

    // Insert into child, remove from our array if they belong in another node
    if (~index) {
      this.nodes[index].insertEntry(entry);
      this.entries.splice(i, 1);
    } else {
      i++;
    }
  }
};

/**
 * Removes an entry from the tree (but does NOT release it back to the pool!!)
 * @param {Entry} entry
 */
QuadTree.prototype.removeEntry = function(entry)
{

};

/**
 * Re-insert an entry in order to get it to the right place in the tree.
 */
QuadTree.prototype.reinsertEntry = function(entry)
{

};

/**
 * Returns true if the passed entry is still okay where its at. Returning false
 * means would she re-insert it into the tree in order to put it in its correct
 * place.
 * @param {Entry} param
 */
QuadTree.prototype.isEntryStillGood = function(entry)
{

};

/**
 * @param {Vec2} position
 * @param {Vec2} size
 * @param {Array.<Entry>=} out__objects Return objects.
 */
QuadTree.prototype.getEntries = function(position, size, out__objects)
{

};

/**
 * Empty the tree recursively.
 */
QuadTree.prototype.clear = function()
{

};

/**
 * Unwinds this node. Move all child nodes into this node and remove child
 * nodes.
 */
QuadTree.prototype.combine = function()
{

};

<|endoftext|>


<commit_before>module.exports = {
    beforeSend: function(req, res, next) {
        var statusMatch = /<meta name=['"]prerender-status-code['"] content=['"]([0-9]{3})['"] ?\/?>/i,
            headerMatch = /<meta name=['"]prerender-header['"] content=['"](.*?): ?(.*?)['"] ?\/?>/gi,
            head = req.prerender.documentHTML.split('', 1).pop(),
            statusCode = 200,
            match;

        if (match = statusMatch.exec(head)) {
            statusCode = match[1];
            req.prerender.documentHTML = req.prerender.documentHTML.replace(match[0], '');
        }

        while (match = headerMatch.exec(head)) {
            res.setHeader(match[1], match[2]);
            req.prerender.documentHTML = req.prerender.documentHTML.replace(match[0], '');
        }

        if (statusCode != 200) {
            res.send(statusCode, req.prerender.documentHTML);
        } else {
            next();
        }
    }
}
<commit_msg>Fixed a bug where the http-headers plugin would fail if theres no documentHTML<commit_after>module.exports = {
    beforeSend: function(req, res, next) {
        if(req.prerender.documentHTML) {
            var statusMatch = /<meta name=['"]prerender-status-code['"] content=['"]([0-9]{3})['"] ?\/?>/i,
                headerMatch = /<meta name=['"]prerender-header['"] content=['"](.*?): ?(.*?)['"] ?\/?>/gi,
                head = req.prerender.documentHTML.split('', 1).pop(),
                statusCode = 200,
                match;

            if (match = statusMatch.exec(head)) {
                statusCode = match[1];
                req.prerender.documentHTML = req.prerender.documentHTML.replace(match[0], '');
            }

            while (match = headerMatch.exec(head)) {
                res.setHeader(match[1], match[2]);
                req.prerender.documentHTML = req.prerender.documentHTML.replace(match[0], '');
            }

            if (statusCode != 200) {
                res.send(statusCode, req.prerender.documentHTML);
            }
        }

        next();
    }
}
<|endoftext|>


<commit_before>// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

import { Log } from '../../src/Log';
import { UserManagerSettings } from '../../src/UserManagerSettings';

import chai from 'chai';
chai.should();
let assert = chai.assert;

describe("UserManagerSettings", function () {

    beforeEach(function () {
        Log.logger = console;
        Log.level = Log.NONE;
    });

    describe("constructor", function () {

        it("should allow no settings", function () {
            let subject = new UserManagerSettings();
        });

        it("should pass settings to base class", function () {
            let subject = new UserManagerSettings({ client_id: 'client' });
            subject.client_id.should.equal('client');
        });

    });

    describe("popup_redirect_uri", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ popup_redirect_uri: 'test' });
            subject.popup_redirect_uri.should.equal('test');
        });

    });

    describe("popupWindowFeatures", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ popupWindowFeatures: 'foo' });
            subject.popupWindowFeatures.should.equal('foo');
        });

    });

    describe("popupWindowTarget", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ popupWindowTarget: 'foo' });
            subject.popupWindowTarget.should.equal('foo');
        });

    });

    describe("silent_redirect_uri", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ silent_redirect_uri: 'test' });
            subject.silent_redirect_uri.should.equal('test');
        });

    });

    describe("silentRequestTimeout", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ silentRequestTimeout: 123 });
            subject.silentRequestTimeout.should.equal(123);
        });

    });

    describe("automaticSilentRenew", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({
                silent_redirect_uri: 'test',
                automaticSilentRenew: false
            });
            subject.automaticSilentRenew.should.be.false;
        });

        it("should use default value", function () {
            let subject = new UserManagerSettings({
                silent_redirect_uri: 'test'
            });
            subject.automaticSilentRenew.should.be.false;
        });

        it("should be false if no silent redirect uri", function () {
            let subject = new UserManagerSettings({
                automaticSilentRenew: true
            });
            subject.automaticSilentRenew.should.be.false;
        });

    });

    describe("includeIdTokenInSilentRenew", function () {
        it("should return true value from initial settings", function () {
            let subject = new UserManagerSettings({
                includeIdTokenInSilentRenew: true,
            });
            subject.includeIdTokenInSilentRenew.should.be.true;
        });

        it("should return false value from initial settings", function () {
            let subject = new UserManagerSettings({
                includeIdTokenInSilentRenew: false,
            });
            subject.includeIdTokenInSilentRenew.should.be.false;
        });

        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.includeIdTokenInSilentRenew.should.be.true;
        });
    });

    describe("accessTokenExpiringNotificationTime", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({
                accessTokenExpiringNotificationTime: 10
            });
            subject.accessTokenExpiringNotificationTime.should.equal(10);
        });

        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.accessTokenExpiringNotificationTime.should.equal(60);
        });

    });

    describe("redirectNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                redirectNavigator : temp
            });
            subject.redirectNavigator.should.equal(temp);
        });
    });

    describe("popupNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                popupNavigator : temp
            });
            subject.popupNavigator.should.equal(temp);
        });
    });

    describe("iframeNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                iframeNavigator : temp
            });
            subject.iframeNavigator.should.equal(temp);
        });
    });

    describe("redirectNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                userStore : temp
            });
            subject.userStore.should.equal(temp);
        });
    });

    describe("revokeAccessTokenOnSignout", function() {
        it("should return value from initial settings", function() {
            let subject = new UserManagerSettings({
                revokeAccessTokenOnSignout : true
            });
            subject.revokeAccessTokenOnSignout.should.equal(true);
        });
    });

    describe("checkSessionInterval", function() {
        it("should return value from initial settings", function() {
            let subject = new UserManagerSettings({
                checkSessionInterval : 6000
            });
            subject.checkSessionInterval.should.equal(6000);
        });
        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.checkSessionInterval.should.equal(2000);
        });
    });

    describe("stopCheckSessionOnError", function() {
        it("should return value from initial settings", function() {
            let subject = new UserManagerSettings({
                stopCheckSessionOnError : false
            });
            subject.stopCheckSessionOnError.should.be.false;
        });
        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.stopCheckSessionOnError.should.be.true;
        });
    });
});
<commit_msg>Added Settings test.<commit_after>// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

import { Log } from '../../src/Log';
import { UserManagerSettings } from '../../src/UserManagerSettings';

import chai from 'chai';
chai.should();
let assert = chai.assert;

describe("UserManagerSettings", function () {

    beforeEach(function () {
        Log.logger = console;
        Log.level = Log.NONE;
    });

    describe("constructor", function () {

        it("should allow no settings", function () {
            let subject = new UserManagerSettings();
        });

        it("should pass settings to base class", function () {
            let subject = new UserManagerSettings({ client_id: 'client' });
            subject.client_id.should.equal('client');
        });

    });

    describe("popup_redirect_uri", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ popup_redirect_uri: 'test' });
            subject.popup_redirect_uri.should.equal('test');
        });

    });

    describe("popupWindowFeatures", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ popupWindowFeatures: 'foo' });
            subject.popupWindowFeatures.should.equal('foo');
        });

    });

    describe("popupWindowTarget", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ popupWindowTarget: 'foo' });
            subject.popupWindowTarget.should.equal('foo');
        });

    });

    describe("silent_redirect_uri", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ silent_redirect_uri: 'test' });
            subject.silent_redirect_uri.should.equal('test');
        });

    });

    describe("silentRequestTimeout", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({ silentRequestTimeout: 123 });
            subject.silentRequestTimeout.should.equal(123);
        });

    });

    describe("automaticSilentRenew", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({
                silent_redirect_uri: 'test',
                automaticSilentRenew: false
            });
            subject.automaticSilentRenew.should.be.false;
        });

        it("should use default value", function () {
            let subject = new UserManagerSettings({
                silent_redirect_uri: 'test'
            });
            subject.automaticSilentRenew.should.be.false;
        });

        it("should be false if no silent redirect uri", function () {
            let subject = new UserManagerSettings({
                automaticSilentRenew: true
            });
            subject.automaticSilentRenew.should.be.false;
        });

    });

    describe("includeIdTokenInSilentRenew", function () {
        it("should return true value from initial settings", function () {
            let subject = new UserManagerSettings({
                includeIdTokenInSilentRenew: true,
            });
            subject.includeIdTokenInSilentRenew.should.be.true;
        });

        it("should return false value from initial settings", function () {
            let subject = new UserManagerSettings({
                includeIdTokenInSilentRenew: false,
            });
            subject.includeIdTokenInSilentRenew.should.be.false;
        });

        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.includeIdTokenInSilentRenew.should.be.true;
        });
    });

    describe("accessTokenExpiringNotificationTime", function () {

        it("should return value from initial settings", function () {
            let subject = new UserManagerSettings({
                accessTokenExpiringNotificationTime: 10
            });
            subject.accessTokenExpiringNotificationTime.should.equal(10);
        });

        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.accessTokenExpiringNotificationTime.should.equal(60);
        });

    });

    describe("redirectNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                redirectNavigator : temp
            });
            subject.redirectNavigator.should.equal(temp);
        });
    });

    describe("popupNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                popupNavigator : temp
            });
            subject.popupNavigator.should.equal(temp);
        });
    });

    describe("iframeNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                iframeNavigator : temp
            });
            subject.iframeNavigator.should.equal(temp);
        });
    });

    describe("redirectNavigator", function() {
        it("should return value from initial settings", function() {
            let temp = {};
            let subject = new UserManagerSettings({
                userStore : temp
            });
            subject.userStore.should.equal(temp);
        });
    });

    describe("revokeAccessTokenOnSignout", function() {
        it("should return value from initial settings", function() {
            let subject = new UserManagerSettings({
                revokeAccessTokenOnSignout : true
            });
            subject.revokeAccessTokenOnSignout.should.equal(true);
        });
    });

    describe("checkSessionInterval", function() {
        it("should return value from initial settings", function() {
            let subject = new UserManagerSettings({
                checkSessionInterval : 6000
            });
            subject.checkSessionInterval.should.equal(6000);
        });
        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.checkSessionInterval.should.equal(2000);
        });
    });

    describe("query_status_response_type", function() {
        it("should return value from initial settings", function() {
            let temp = 'type';
            let subject = new UserManagerSettings({
                query_status_response_type : temp
            });
            subject.query_status_response_type.should.equal(temp);
        });
        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.query_status_response_type.should.equal("id_token");
        });
    });

    describe("stopCheckSessionOnError", function() {
        it("should return value from initial settings", function() {
            let subject = new UserManagerSettings({
                stopCheckSessionOnError : false
            });
            subject.stopCheckSessionOnError.should.be.false;
        });
        it("should use default value", function () {
            let subject = new UserManagerSettings({
            });
            subject.stopCheckSessionOnError.should.be.true;
        });
    });
});
<|endoftext|>


<commit_before>var chai = require('chai');
var expect = chai.expect;
var LayoutGenerator = require('./../../app/content_push/cp-layout-generator');

describe('LayoutGenerator', function () {

  var layoutGenerator = new LayoutGenerator();

  /* test situation where the following tile sequence:

     width=4,height=4
     width=4,height=2
     width=4,height=2

     results in the 4x4 tile being underneath both 4x2 tiles
  */
  it('should choose lay out large square tiles correctly with landscape tiles', function () {
    var testShapes = [
      {width: 4, height: 4},
      {width: 4, height: 2},
      {width: 4, height: 2}
    ];

    var gridWidth = 4;

    var expectedPlacements = [
      {
        shape: testShapes[0],
        position: {
          rows: [0,1,2,3], columns: [0,1,2,3]
        }
      },
      {
        shape: testShapes[1],
        position: {
          rows: [4,5], columns: [0,1,2,3]
        }
      },
      {
        shape: testShapes[2],
        position: {
          rows: [6,7], columns: [0,1,2,3]
        }
      }
    ];

    var actual = layoutGenerator.generate(testShapes, gridWidth);

    actual.placements.should.eql(expectedPlacements);
  });

});
<commit_msg>[cp-layout-generator] Add test for simplest layout case<commit_after>var chai = require('chai');
var expect = chai.expect;
var LayoutGenerator = require('./../../app/content_push/cp-layout-generator');

describe('LayoutGenerator', function () {

  var layoutGenerator = new LayoutGenerator();

  /* test situation where the following tile sequence:

     width=4,height=4
     width=4,height=2
     width=4,height=2

     results in the 4x4 tile being underneath both 4x2 tiles
  */
  it('should lay out large square tiles correctly with landscape tiles', function () {
    var testShapes = [
      {width: 4, height: 4},
      {width: 4, height: 2},
      {width: 4, height: 2}
    ];

    var gridWidth = 4;

    var expectedPlacements = [
      {
        shape: testShapes[0],
        position: {
          rows: [0,1,2,3], columns: [0,1,2,3]
        }
      },
      {
        shape: testShapes[1],
        position: {
          rows: [4,5], columns: [0,1,2,3]
        }
      },
      {
        shape: testShapes[2],
        position: {
          rows: [6,7], columns: [0,1,2,3]
        }
      }
    ];

    var actual = layoutGenerator.generate(testShapes, gridWidth);

    actual.placements.should.eql(expectedPlacements);
  });

  it('should lay out a single shape', function () {
    var testShape = {width: 4, height: 4};

    var gridWidth = 4;

    var expectedPlacements = [
      {
        shape: testShape,
        position: {
          rows: [0,1,2,3], columns: [0,1,2,3]
        }
      }
    ];

    var actual = layoutGenerator.generate([testShape], gridWidth);

    actual.placements.should.eql(expectedPlacements);
  });

});
<|endoftext|>


<commit_before>const nunjucks = require('nunjucks');
const path = require('path');
const fs = require('fs');
const minimatch = require('minimatch');
const async = require('async');
const _ = require('lodash');
const glob = require('glob');
const MarkdownIt = require('markdown-it');
const hljs = require('highlight.js');
const normalizeNewline = require('normalize-newline');
const Helper = require('./custom-tags/Helper.js');
const Block = require('./custom-tags/Block.js');
const CustomHelperError = require('./error-types/CustomHelperError.js');
const PageRenderError = require('./error-types/PageRenderError.js');
const TemplateNotFoundError = require('./error-types/TemplateNotFoundError.js');
const Logger = require('./Logger.js');
const EventEmitter = require('events');

const Loader = nunjucks.Loader.extend({
  init: function ({
    sourceDir,
    logger,
    errorHandler
  }) {
    this.sourceDir = sourceDir;
    this.logger = logger;
    this.errorHandler = errorHandler;
  },

  getSource: function (name) {
    this.logger.debug(`looking up templates ${name}, ${name}.md, ${name}.html`);

    const matches = glob.sync(`${name}?(.html|.md|)`, {
      cwd: this.sourceDir
    });

    if (!matches || !matches.length) {
      throw new TemplateNotFoundError(name);
    }

    if (matches.length > 1) {
      this.logger.warn(`Found multiple templates matching ${name}. ${matches.join(',')}`);
    }

    const fullpath = path.join(this.sourceDir, matches.sort((a, b) => a.length - b.length)[0]);

    const content = fs.readFileSync(fullpath, 'utf8');

    const template = _.trim(_.last(content.split(/^([\s\S]+)^-{3}$/m)));

    return {
      src: normalizeNewline(template),
      path: fullpath
    };
  }
});

class Renderer {
  constructor ({
    sourceDir = path.join(process.cwd(), 'src'),
    log = 'info',
    emitter = new EventEmitter(),
    logger
  } = {}) {
    this.sourceDir = sourceDir;
    this.logger = logger || new Logger({level: log});
    this.emitter = emitter;
    this.reset();
  }

  _createPrerenderFunction (pattern, prerenderer) {
    return function (page, done) {
      if (minimatch(page.src, pattern)) {
        try {
          prerenderer(page, done);
        } catch (e) {
          done(e);
        }
      } else {
        done(null, page);
      }
    };
  }

  reset () {
    this._prerenderers = [];

    this.loader = new Loader({
      sourceDir: this.sourceDir,
      logger: this.logger,
      errorHandler: (error) => {
        this.emitter.emit('renderer:error', {
          error
        });
        this.logger.error(error);
      }
    });

    this.nunjucks = new nunjucks.Environment(this.loader, {
      // dev: true
    });

    this.markdown = new MarkdownIt({
      html: true,
      linkify: true,
      langPrefix: '',
      highlight: function (code, lang) {
        if (lang === 'text' || lang === 'plain') {
          return code;
        }

        return (lang) ? hljs.highlight(lang, code).value : hljs.highlightAuto(code).value;
      }
    });
  }

  prerender (pattern, prerenderer) {
    this._prerenderers.push(this._createPrerenderFunction(pattern, prerenderer));
  }

  renderPage (page) {
    var _timer = this.logger.time();
    return this._prerenderPage(page)
      .then(page => this._renderPage(page))
      .then(result => {
        this.logger.info(`Rendered ${page.url} (${page.src}) in ${this.logger.timeEnd(_timer)}`);
        return result;
      });
  }

  invalidateTemplate (name) {
    name = name.replace(path.extname(name), '');
    this.nunjucks.loaders[0].emit('update', name);
    this.nunjucks.loaders[0].emit('update', `${name}.md`);
    this.nunjucks.loaders[0].emit('update', `${name}.html`);
  }

  helper (name, handler, defaults) {
    this.nunjucks.addExtension(name, new Helper(name, handler, defaults));
  }

  block (name, handler, defaults) {
    this.nunjucks.addExtension(name, new Block(name, handler, defaults));
  }

  filter (name, handler) {
    this.nunjucks.addFilter(name, function (...args) {
      let result;

      try {
        result = handler.apply(undefined, args);
      } catch (e) {
        throw new CustomHelperError('filter', name, e);
      }

      return new nunjucks.runtime.SafeString(result);
    });
  }

  global (name, value) {
    this.nunjucks.addGlobal(name, value);
  }

  _renderPage (page) {
    if (page.__isMarkdown) {
      return this._renderMarkdown(page.template)
        .then((output) => {
          return this._renderNunjucks(page.layout, output, page);
        });
    }

    return this._renderNunjucks(page.layout, page.template, page);
  }

  _renderMarkdown (markdown) {
    return new Promise((resolve) => {
      process.nextTick(() => {
        resolve(_.trim(this.markdown.render(markdown)));
      });
    });
  }

  _renderNunjucks (layout, template, page) {
    return new Promise((resolve, reject) => {
      if (layout) {
        let [layoutTemplate, block] = layout.split(':');
        template = `{% extends '${layoutTemplate}' %}{% block ${block} %}${template}{% endblock %}`;
      }

      this.nunjucks.renderString(template, page, (error, html) => {
        if (error) {
          reject(new PageRenderError(error, page));
        }

        resolve(_.trim(html));
      });
    });
  }

  _prerenderPage (page) {
    return new Promise((resolve, reject) => {
      const iterator = (page, prerenderer, callback) => {
        prerenderer(Object.assign({}, page), callback);
      };

      const done = (error, page) => {
        if (error) {
          reject(error);
          return;
        }

        resolve(page);
      };

      async.reduce(this._prerenderers, page, iterator, done);
    });
  }
}

module.exports = Renderer;
<commit_msg>normalize paths from watcher<commit_after>const nunjucks = require('nunjucks');
const path = require('path');
const fs = require('fs');
const minimatch = require('minimatch');
const async = require('async');
const _ = require('lodash');
const glob = require('glob');
const MarkdownIt = require('markdown-it');
const hljs = require('highlight.js');
const normalizeNewline = require('normalize-newline');
const Helper = require('./custom-tags/Helper.js');
const Block = require('./custom-tags/Block.js');
const CustomHelperError = require('./error-types/CustomHelperError.js');
const PageRenderError = require('./error-types/PageRenderError.js');
const TemplateNotFoundError = require('./error-types/TemplateNotFoundError.js');
const Logger = require('./Logger.js');
const EventEmitter = require('events');

const Loader = nunjucks.Loader.extend({
  init: function ({
    sourceDir,
    logger,
    errorHandler
  }) {
    this.sourceDir = sourceDir;
    this.logger = logger;
    this.errorHandler = errorHandler;
  },

  getSource: function (name) {
    this.logger.debug(`looking up templates ${name}, ${name}.md, ${name}.html`);

    const matches = glob.sync(`${name}?(.html|.md|)`, {
      cwd: this.sourceDir
    });

    if (!matches || !matches.length) {
      throw new TemplateNotFoundError(name);
    }

    if (matches.length > 1) {
      this.logger.warn(`Found multiple templates matching ${name}. ${matches.join(',')}`);
    }

    const fullpath = path.join(this.sourceDir, matches.sort((a, b) => a.length - b.length)[0]);

    const content = fs.readFileSync(fullpath, 'utf8');

    const template = _.trim(_.last(content.split(/^([\s\S]+)^-{3}$/m)));

    return {
      src: normalizeNewline(template),
      path: fullpath
    };
  }
});

class Renderer {
  constructor ({
    sourceDir = path.join(process.cwd(), 'src'),
    log = 'info',
    emitter = new EventEmitter(),
    logger
  } = {}) {
    this.sourceDir = sourceDir;
    this.logger = logger || new Logger({level: log});
    this.emitter = emitter;
    this.reset();
  }

  _createPrerenderFunction (pattern, prerenderer) {
    return function (page, done) {
      if (minimatch(page.src, pattern)) {
        try {
          prerenderer(page, done);
        } catch (e) {
          done(e);
        }
      } else {
        done(null, page);
      }
    };
  }

  reset () {
    this._prerenderers = [];

    this.loader = new Loader({
      sourceDir: this.sourceDir,
      logger: this.logger,
      errorHandler: (error) => {
        this.emitter.emit('renderer:error', {
          error
        });
        this.logger.error(error);
      }
    });

    this.nunjucks = new nunjucks.Environment(this.loader, {
      // dev: true
    });

    this.markdown = new MarkdownIt({
      html: true,
      linkify: true,
      langPrefix: '',
      highlight: function (code, lang) {
        if (lang === 'text' || lang === 'plain') {
          return code;
        }

        return (lang) ? hljs.highlight(lang, code).value : hljs.highlightAuto(code).value;
      }
    });
  }

  prerender (pattern, prerenderer) {
    this._prerenderers.push(this._createPrerenderFunction(pattern, prerenderer));
  }

  renderPage (page) {
    var _timer = this.logger.time();
    return this._prerenderPage(page)
      .then(page => this._renderPage(page))
      .then(result => {
        this.logger.info(`Rendered ${page.url} (${page.src}) in ${this.logger.timeEnd(_timer)}`);
        return result;
      });
  }

  invalidateTemplate (name) {
    name = name.replace(path.extname(name), '');
    this.nunjucks.loaders[0].emit('update', name);
    this.nunjucks.loaders[0].emit('update', `${name}.md`);
    this.nunjucks.loaders[0].emit('update', `${name}.html`);
  }

  helper (name, handler, defaults) {
    this.nunjucks.addExtension(name, new Helper(name, handler, defaults));
  }

  block (name, handler, defaults) {
    this.nunjucks.addExtension(name, new Block(name, handler, defaults));
  }

  filter (name, handler) {
    this.nunjucks.addFilter(name, function (...args) {
      let result;

      try {
        result = handler.apply(undefined, args);
      } catch (e) {
        throw new CustomHelperError('filter', name, e);
      }

      return new nunjucks.runtime.SafeString(result);
    });
  }

  global (name, value) {
    this.nunjucks.addGlobal(name, value);
  }

  _renderPage (page) {
    if (page.__isMarkdown) {
      return this._renderMarkdown(page.template)
        .then((output) => {
          return this._renderNunjucks(page.layout, output, page);
        });
    }

    return this._renderNunjucks(page.layout, page.template, page);
  }

  _renderMarkdown (markdown) {
    return new Promise((resolve) => {
      process.nextTick(() => {
        resolve(_.trim(this.markdown.render(markdown)));
      });
    });
  }

  _renderNunjucks (layout, template, page) {
    return new Promise((resolve, reject) => {
      if (layout) {
        let [layoutTemplate, block] = layout.split(':');
        template = `{% extends '${layoutTemplate}' %}{% block ${block} %}${template}{% endblock %}`;
      }

      this.nunjucks.renderString(template, page, (error, html) => {
        if (error) {
          reject(new PageRenderError(error, page));
        }
        resolve(_.trim(html));
      });
    });
  }

  _prerenderPage (page) {
    return new Promise((resolve, reject) => {
      const iterator = (page, prerenderer, callback) => {
        prerenderer(Object.assign({}, page), callback);
      };

      const done = (error, page) => {
        if (error) {
          reject(error);
          return;
        }

        resolve(page);
      };

      async.reduce(this._prerenderers, page, iterator, done);
    });
  }
}

module.exports = Renderer;
<|endoftext|>


<commit_before>module( "Serialization" );

test( "Test Serialization (simple)", function() {

	// setup
	var editor = new Editor();

	var addObject = function () {

		// setup
		var box = aBox( 'The Box' );

		// Test Add
		var cmd = new CmdAddObject( box );
		cmd.updatable = false;

		editor.execute( cmd );

	};

	var addScript = function () {

		// setup
		var box = aBox( 'The Box' );

		// Test Add

		var cmd = new CmdAddObject( box );
		editor.execute( cmd );

		var cmd = new CmdAddScript( box, { "name":"test","source":"console.log(\"hello world\");" } );
		cmd.updatable = false;

		editor.execute( cmd );

	};

	var moveObject = function () {

		// create some objects
		var anakinsName = 'Anakin Skywalker';
		var lukesName   = 'Luke Skywalker';
		var anakinSkywalker = aSphere( anakinsName );
		var lukeSkywalker   = aBox( lukesName );

		editor.execute( new CmdAddObject( anakinSkywalker ) );
		editor.execute( new CmdAddObject( lukeSkywalker ) );

		// Tell Luke, Anakin is his father
		editor.execute( new CmdMoveObject( lukeSkywalker, anakinSkywalker ) );

	};

	var setups = [ addObject, addScript, moveObject ];

	// Forward tests

	for ( var i = 0; i < setups.length ; i++ ) {

		setups[i]();

		// Check for correct serialization

		editor.history.goToState( 0 );
		editor.history.goToState( 1000 );

		var history = JSON.stringify( editor.history.toJSON() );

		editor.history.clear();

		editor.history.fromJSON( JSON.parse( history ) );

		editor.history.goToState( 0 );
		editor.history.goToState( 1000 );

		var history2 = JSON.stringify( editor.history.toJSON() );

		ok( history == history2 , "OK, forward serializing was successful " );

		editor.clear();

	}

	// Backward tests

	for (var i = 0; i < setups.length ; i++ ) {

		setups[i]();

		editor.history.goToState( 0 );

		var history = JSON.stringify( editor.history.toJSON() );

		editor.history.clear();

		editor.history.fromJSON( JSON.parse( history ) );

		editor.history.goToState( 1000 );
		editor.history.goToState( 0 );

		var history2 = JSON.stringify( editor.history.toJSON() );

		ok( history == history2 , "OK, backward serializing was successful " );

		editor.clear();

	}

});<commit_msg>added serialization tests for all commands<commit_after>module( "Serialization" );

test( "Test Serialization (simple)", function() {

	// setup
	var editor = new Editor();

	var green   = 12581843; // bffbd3

	var addObject = function () {

		// setup
		var box = aBox( 'The Box' );

		// Test Add
		var cmd = new CmdAddObject( box );
		cmd.updatable = false;

		editor.execute( cmd );

		return "addObject";
	};

	var addScript = function () {

		// setup
		var box = aBox( 'The Box' );

		// Test Add

		var cmd = new CmdAddObject( box );
		editor.execute( cmd );

		var cmd = new CmdAddScript( box, { "name":"test","source":"console.log(\"hello world\");" } );
		cmd.updatable = false;

		editor.execute( cmd );

		return "addScript";

	};

	var moveObject = function () {

		// create some objects
		var anakinsName = 'Anakin Skywalker';
		var lukesName   = 'Luke Skywalker';
		var anakinSkywalker = aSphere( anakinsName );
		var lukeSkywalker   = aBox( lukesName );

		editor.execute( new CmdAddObject( anakinSkywalker ) );
		editor.execute( new CmdAddObject( lukeSkywalker ) );

		// Tell Luke, Anakin is his father
		editor.execute( new CmdMoveObject( lukeSkywalker, anakinSkywalker ) );

		return "moveObject";
	};

	var removeScript = function () {

		var box = aBox( 'Box with no script' );
		editor.execute( new CmdAddObject( box ) );

		var script = { "name":"test","source":"console.log(\"hello world\");" } ;
		var cmd = new CmdAddScript( box, script );
		cmd.updatable = false;

		editor.execute( cmd );

		cmd = new CmdRemoveScript( box, script );
		editor.execute( cmd );

		return "removeScript";
	};

	var setColor = function () {

		var pointLight = aPointlight( "The light Light" );

		editor.execute( new CmdAddObject( pointLight ) );
		var cmd = new CmdSetColor( pointLight, 'color', green );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setColor";
	};

	var setGeometry = function () {

		var box = aBox( 'Guinea Pig' ); // default ( 100, 100, 100, 1, 1, 1 )
		var boxGeometry = { geometry: { parameters: { width: 200, height: 201, depth: 202, widthSegments: 2, heightSegments: 3, depthSegments: 4 } } };

		editor.execute( new CmdAddObject( box ) );

		var cmd = new CmdSetGeometry( box, getGeometry( "BoxGeometry", boxGeometry ) );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setGeometry";
	};

	var setGeometryValue = function() {

		var box = aBox( 'Geometry Value Box' );
		editor.execute( new CmdAddObject( box ) );

		cmd = new CmdSetGeometryValue( box, 'uuid', THREE.Math.generateUUID() );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setGeometryValue";
	};

	var setMaterial = function () {

		var sphere = aSphere( 'The Sun' );
		editor.execute( new CmdAddObject( sphere ) );

		var material = new THREE[ 'MeshPhongMaterial' ]();
		var cmd = new CmdSetMaterial( sphere, material );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setMaterial";
	};

	var setMaterialColor = function () {

		var box = aBox( 'Box with colored material' );
		editor.execute( new CmdAddObject( box ) );

		var cmd = new CmdSetMaterialColor( box, 'color', green );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setMaterialColor";
	};

	var setMaterialMap = function () {

		var sphere = aSphere( 'Sphere with texture' );
		editor.execute( new CmdAddObject( sphere ) );

		// dirt.png
		var data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpDMjYxMEI4MzVENDMxMUU1OTdEQUY4QkNGNUVENjg4MyIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpDMjYxMEI4NDVENDMxMUU1OTdEQUY4QkNGNUVENjg4MyI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkMyNjEwQjgxNUQ0MzExRTU5N0RBRjhCQ0Y1RUQ2ODgzIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkMyNjEwQjgyNUQ0MzExRTU5N0RBRjhCQ0Y1RUQ2ODgzIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+txizaQAAABVQTFRFh4eHbGxsdFhEWT0puYVclmxKeVU6ppwr+AAAAHtJREFUeNosjgEWBCEIQplFuP+RB5h9lZn2EZxkLzC3D1YSgSlmk7i0ctzDZNBz/VSoX1KwjlFI8WmA2R7JqUa0LJJcd1rLNWRRaMyi+3Y16qMKHhdE48XLsDyHKJ0nSMazY1fxHyriXxV584tmEedcfGNrA/5cmK8AAwCT9ATehDDyzwAAAABJRU5ErkJggg==';
		var img = new Image();
		img.src = data;

		var texture = new THREE.Texture( img, 'map' );
		texture.sourceFile = 'dirt.png';

		var cmd = new CmdSetMaterialMap( sphere, 'map', texture );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setMaterialMap";
	};

	var setMaterialValue = function () {

		var box = aBox( 'Box with values' );
		editor.execute( new CmdAddObject( box ) );

		var cmd = new CmdSetMaterialValue( box, 'name', 'Bravo' );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setMaterialValue";
	};

	var setPosition = function () {

		var sphere = aSphere( 'Sphere with position' );
		editor.execute( new CmdAddObject( sphere ) );

		var newPosition = new THREE.Vector3( 101, 202, 303 );
		var cmd = new CmdSetPosition( sphere, newPosition );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setPosition";
	};

	var setRotation = function () {

		var box = aBox( 'Box with rotation' );
		editor.execute( new CmdAddObject( box ) );

		var newRotation = new THREE.Euler( 0.3, -1.7, 2 );
		var cmd = new CmdSetRotation( box, newRotation );
		cmd.updatable = false;
		editor.execute ( cmd );

		return "setRotation";

	};

	var setScale = function () {

		var sphere = aSphere( 'Sphere with scale' );
		editor.execute( new CmdAddObject( sphere) );

		var newScale = new THREE.Vector3( 1.2, 3.3, 4.6 );
		var cmd = new CmdSetScale( sphere, newScale );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setScale";
	};

	var setScriptValue = function () {

		var box = aBox( 'Box with script' );
		editor.execute( new CmdAddObject( box ) );
		var script = { name: "Alert", source: "alert( null );" };
		editor.execute( new CmdAddScript( box, script ) );

		var newScript = { name: "Console", source: "console.log( null );" };
		var cmd = new CmdSetScriptValue( box, script, 'source', newScript.source , 0 );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setScriptValue";

	};

	var setUuid = function () {

		var sphere = aSphere( 'Sphere with UUID' );
		editor.execute( new CmdAddObject( sphere ) );

		var cmd = new CmdSetUuid( sphere, THREE.Math.generateUUID() );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setUuid";
	};

	var setValue = function () {

		var box = aBox( 'Box with value' );
		editor.execute( new CmdAddObject( box ) );

		var cmd = new CmdSetValue( box, 'intensity', 2.3 );
		cmd.updatable = false;
		editor.execute( cmd );

		return "setValue";
	};

	var setups = [
		addObject,
		addScript,
		moveObject,
		removeScript,
		setColor,
		setGeometry,
		setGeometryValue,
		setMaterial,
		setMaterialColor,
		setMaterialMap,
		setMaterialValue,
		setPosition,
		setRotation,
		setScale,
		setScriptValue,
		setUuid,
		setValue
	];

	// Forward tests

	for ( var i = 0; i < setups.length ; i++ ) {

		var name = setups[i]();

		// Check for correct serialization

		editor.history.goToState( 0 );
		editor.history.goToState( 1000 );

		var history = JSON.stringify( editor.history.toJSON() );

		editor.history.clear();

		editor.history.fromJSON( JSON.parse( history ) );

		editor.history.goToState( 0 );
		editor.history.goToState( 1000 );

		var history2 = JSON.stringify( editor.history.toJSON() );

		ok( history == history2 , "OK, forward serializing was successful for " + name );

		editor.clear();

	}

	// Backward tests

	for (var i = 0; i < setups.length ; i++ ) {

		var name = setups[i]();

		editor.history.goToState( 0 );

		var history = JSON.stringify( editor.history.toJSON() );

		editor.history.clear();

		editor.history.fromJSON( JSON.parse( history ) );

		editor.history.goToState( 1000 );
		editor.history.goToState( 0 );

		var history2 = JSON.stringify( editor.history.toJSON() );

		ok( history == history2 , "OK, backward serializing was successful for " + name );

		editor.clear();

	}

});<|endoftext|>


<commit_before>var roleHarvester = {

	/** @param {Creep} creep **/
	run: function(creep) {

		if (creep.memory.harvesting) {
			var sources = creep.room.find(FIND_SOURCES);

			if (!creep.memory.source) {
				for (source in sources) {
					if (_.filter(Game.creeps, (creep) =>
							(creep.memory.role == 'harvester') &&
							(creep.memory.role source == source)
					).length != 1) {
						creep.memory.source = source;
					}
				}
			}
			if (creep.harvest(sources[creep.memory.source]) == ERR_NOT_IN_RANGE) {
				creep.moveTo(sources[creep.memory.source]);
			}
			else if (creep.carry.energy == creep.carryCapacity) {
				creep.say('Depositing');
			  creep.memory.harvesting = false;
			}
		}
		else {
			var targets = creep.pos.findInRange(FIND_STRUCTURES, 1, {
				filter: (structure) => {
					return (structure.structureType == STRUCTURE_CONTAINER);
				}
			});

			if (targets.length > 0) {
				if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
					creep.moveTo(targets[0]);
				}
			}
			if (creep.carry.energy == 0) {
				creep.say('Harvesting');
			  creep.memory.harvesting = true;
			}
		}

	} // function

}; // roleHarvester

module.exports = roleHarvester;<commit_msg>Fix typo<commit_after>var roleHarvester = {

	/** @param {Creep} creep **/
	run: function(creep) {

		if (creep.memory.harvesting) {
			var sources = creep.room.find(FIND_SOURCES);

			if (!creep.memory.source) {
				for (source in sources) {
					if (_.filter(Game.creeps, (creep) =>
							(creep.memory.role == 'harvester') &&
							(creep.memory.source == source)
					).length != 1) {
						creep.memory.source = source;
					}
				}
			}
			if (creep.harvest(sources[creep.memory.source]) == ERR_NOT_IN_RANGE) {
				creep.moveTo(sources[creep.memory.source]);
			}
			else if (creep.carry.energy == creep.carryCapacity) {
				creep.say('Depositing');
			  creep.memory.harvesting = false;
			}
		}
		else {
			var targets = creep.pos.findInRange(FIND_STRUCTURES, 1, {
				filter: (structure) => {
					return (structure.structureType == STRUCTURE_CONTAINER);
				}
			});

			if (targets.length > 0) {
				if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
					creep.moveTo(targets[0]);
				}
			}
			if (creep.carry.energy == 0) {
				creep.say('Harvesting');
			  creep.memory.harvesting = true;
			}
		}

	} // function

}; // roleHarvester

module.exports = roleHarvester;<|endoftext|>


<commit_before>/* eslint-env mocha */

"use strict";

const proclaim = require("proclaim");
const mockery = require("mockery");
const sinon = require("sinon");

sinon.assert.expose(proclaim, {
	includeFail: false,
	prefix: ""
});

describe("createCompressor", function() {
	this.timeout(30000);
	let zlib;
	let createCompressor;
	let gzipCompressor;
	let brotliCompressor;

	beforeEach(() => {
		mockery.enable({
			useCleanCache: true,
			warnOnUnregistered: false,
			warnOnReplace: false
		});

		zlib = require("../mock/zlib.mock");
		mockery.registerMock("zlib", zlib);

		gzipCompressor = {};
		zlib.createGzip.returns(gzipCompressor);
		brotliCompressor = {};
		zlib.createBrotliCompress.returns(brotliCompressor);

		createCompressor = require("../../../server/lib/create-compressor");
	});

	afterEach(() => {
		mockery.deregisterAll();
		mockery.disable();
	});

	it("exports a function", () => {
		proclaim.isFunction(createCompressor);
	});

	it("returns `PassThrough` if `compression` is not set to either `br` or `gzip`", async () => {
		const result = await createCompressor(undefined);
		proclaim.deepStrictEqual(result, require("stream").PassThrough);
	});
	it("returns `PassThrough` if `compression` is `identity`", async () => {
		const result = await createCompressor("identity");
		proclaim.deepStrictEqual(result, require("stream").PassThrough);
	});

	it("returns `gzip` compressor if `compression` is `gzip`", async () => {
		const result = createCompressor("gzip");
		proclaim.calledOnce(zlib.createGzip);
		proclaim.calledWith(zlib.createGzip, {
			level: zlib.Z_BEST_COMPRESSION
		});
		proclaim.deepStrictEqual(result, gzipCompressor);
	});

	it("brotlis `file` with best compression if `compression` is `br`", async () => {
		const result = createCompressor("br");
		proclaim.calledOnce(zlib.createBrotliCompress);
		proclaim.calledWith(zlib.createBrotliCompress, {
			params: { quality: 11 }
		});
		proclaim.deepStrictEqual(result, brotliCompressor);
	});
});
<commit_msg>Update test/unit/lib/compress-bundle.test.js<commit_after>/* eslint-env mocha */

"use strict";

const proclaim = require("proclaim");
const mockery = require("mockery");
const sinon = require("sinon");

sinon.assert.expose(proclaim, {
	includeFail: false,
	prefix: ""
});

describe("createCompressor", function() {
	this.timeout(30000);
	let zlib;
	let createCompressor;
	let gzipCompressor;
	let brotliCompressor;

	beforeEach(() => {
		mockery.enable({
			useCleanCache: true,
			warnOnUnregistered: false,
			warnOnReplace: false
		});

		zlib = require("../mock/zlib.mock");
		mockery.registerMock("zlib", zlib);

		gzipCompressor = {};
		zlib.createGzip.returns(gzipCompressor);
		brotliCompressor = {};
		zlib.createBrotliCompress.returns(brotliCompressor);

		createCompressor = require("../../../server/lib/create-compressor");
	});

	afterEach(() => {
		mockery.deregisterAll();
		mockery.disable();
	});

	it("exports a function", () => {
		proclaim.isFunction(createCompressor);
	});

	it("returns `PassThrough` if `compression` is not set to either `br` or `gzip`", async () => {
		const result = await createCompressor(undefined);
		proclaim.deepStrictEqual(result, require("stream").PassThrough);
	});
	it("returns `PassThrough` if `compression` is `identity`", async () => {
		const result = await createCompressor("identity");
		proclaim.deepStrictEqual(result, require("stream").PassThrough);
	});

	it("returns `gzip` compressor if `compression` is `gzip`", async () => {
		const result = createCompressor("gzip");
		proclaim.calledOnce(zlib.createGzip);
		proclaim.calledWith(zlib.createGzip, {
			level: zlib.Z_BEST_COMPRESSION
		});
		proclaim.deepStrictEqual(result, gzipCompressor);
	});

	it("returns brotli compressor if `compression` is `br`", async () => {
		const result = createCompressor("br");
		proclaim.calledOnce(zlib.createBrotliCompress);
		proclaim.calledWith(zlib.createBrotliCompress, {
			params: { quality: 11 }
		});
		proclaim.deepStrictEqual(result, brotliCompressor);
	});
});
<|endoftext|>