<commit_before>let should = require('should');
let Parser = require('../dist/parser').Parser;
let http = require('http');
let qs = require('querystring');

describe('Parser', function () {
    describe('新建parser测试', function () {
        let globalParser;

        beforeEach(function () {
            globalParser = new Parser();
        });

        it('should return parser', function () {
            globalParser.should.be.instanceof(Parser);
        });

        it('should parser.trim is true', function () {
            let parser = new Parser(true);
            parser.trim.should.be.true();
        });

        it('should parser.errCb return undefined', function () {
            should(globalParser.errCb()).be.an.Undefined();
        });

        it('should parser.errCn return 1', function () {
            let parser = new Parser(function () {
                return 1;
            });

            should(parser.errCb()).be.equal(1);
        });
    });

    describe('addParams 方法测试', function () {
        it('should throw name Typerror', function () {
            should.throws(function () {
                let parser = new Parser();
                parser.addParam({
                    name: 1,
                });
            });
        });

        it('should throw name exists Error', function () {
            should.throws(function () {
                let parser = new Parser();
                parser.addParam({
                    name: 'name',
                });
                parser.addParam({
                    name: 'name',
                });
            });
        });

        it('should have params', function () {
            let parser = new Parser();
            parser.addParam({
                name: 'sex',
                required: true,
            });

            let params = parser.params['sex'];

            params.should.have.property('name');
            params.should.have.property('required').with.be.true();

        });
    });

    describe('removeParams 测试', function () {
        it('should throw typerror', function () {
            let parser = new Parser();
            should.throws(function () {
                parser.removeParams(1);
            });
        });

        it('should work with string', function () {
            let parser = new Parser();
            parser.addParam({
                name: 'sex',
            });
            parser.removeParams('sex');

            let params = parser.params;
            should(params['sex']).be.Undefined();
        });

        it('should work with string array', function () {
            let parser = new Parser();
            parser.addParam({
                name: 'sex',
            });
            parser.addParam({
                name: 'age',
            });

            let params = parser.params;

            parser.removeParams(['sex', 'age']);
            should(params['sex']).be.Undefined();
            should(params['age']).be.Undefined();
        });
    });

    describe('parse 方法测试', function () {
        let server;

        before(function () {
            server = http.createServer(function (req, res) {
                let parser = new Parser();
                parser.parse(req, res).on('end', function (data) {
                    res.writeHead(200, {
                        'Content-type': 'application/json',
                    });
                    res.end(JSON.stringify(data));
                });
            }).listen(5052);
        });

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

        describe('get请求处理', function () {
            it('should return {data: ""}', function (done) {
                http.get({
                    port: 5052,
                }, function (res) {
                    let data = [];
                    res.on('data', function (chunk) {
                        data.push(chunk);
                    }).on('end', function () {
                        data = JSON.parse(data.toString());
                        data.should.have.property('data');
                        console.log(data);
                        done();
                    });

                }).on('error', function (err) {
                    throw err;
                });
            });

            it('should return {data: {name: "lleohao"}}', function (done) {
                http.get({
                    port: 5052,
                    path: '/?name=lleohao',
                }, function (res) {
                    let data = [];
                    res.on('data', function (chunk) {
                        data.push(chunk);
                    }).on('end', function () {
                        data = JSON.parse(data.toString()).data;
                        data.should.have.property('name');
                        data['name'].should.be.equal('lleohao');
                        done();
                    });
                }).on('error', function (err) {
                    throw err;
                });
            });
        });

        // describe('post put delete 等带有请求数据的请求处理', function () {
        //     it('should return {data: ""}', (done) => {
        //         let postData = '';

        //         let request = http.request({
        //             port: 5052,
        //             method: 'POST',
        //             headers: {
        //                 'Content-Type': 'application/x-www-form-urlencoded',
        //                 'Content-Length': Buffer.byteLength(postData)
        //             }
        //         }, function (res) {
        //             let data = [];
        //             res.on('data', function (chunk) {
        //                 data.push(chunk);
        //             }).on('end', function () {
        //                 data = JSON.parse(data.toString());
        //                 data.should.have.property('data');
        //                 done();
        //             });
        //         });

        //         request.write(postData);
        //         request.end();
        //     });
        // });
    });
});<commit_msg>test: 增加测试内容<commit_after>let should = require('should');
let Parser = require('../dist/parser').Parser;
let http = require('http');
let qs = require('querystring');

describe('Parser', function () {
    describe('新建parser测试', function () {
        let globalParser;

        beforeEach(function () {
            globalParser = new Parser();
        });

        it('should return parser', function () {
            globalParser.should.be.instanceof(Parser);
        });

        it('should parser.trim is true', function () {
            let parser = new Parser(true);
            parser.trim.should.be.true();
        });

        it('should parser.errCb return undefined', function () {
            should(globalParser.errCb()).be.an.Undefined();
        });

        it('should parser.errCn return 1', function () {
            let parser = new Parser(function () {
                return 1;
            });

            should(parser.errCb()).be.equal(1);
        });
    });

    describe('addParams 方法测试', function () {
        it('should throw name Typerror', function () {
            should.throws(function () {
                let parser = new Parser();
                parser.addParam({
                    name: 1,
                });
            });
        });

        it('should throw name exists Error', function () {
            should.throws(function () {
                let parser = new Parser();
                parser.addParam({
                    name: 'name',
                });
                parser.addParam({
                    name: 'name',
                });
            });
        });

        it('should have params', function () {
            let parser = new Parser();
            parser.addParam({
                name: 'sex',
                required: true,
            });

            let params = parser.params['sex'];

            params.should.have.property('name');
            params.should.have.property('required').with.be.true();

        });
    });

    describe('removeParams 测试', function () {
        it('should throw typerror', function () {
            let parser = new Parser();
            should.throws(function () {
                parser.removeParams(1);
            });
        });

        it('should work with string', function () {
            let parser = new Parser();
            parser.addParam({
                name: 'sex',
            });
            parser.removeParams('sex');

            let params = parser.params;
            should(params['sex']).be.Undefined();
        });

        it('should work with string array', function () {
            let parser = new Parser();
            parser.addParam({
                name: 'sex',
            });
            parser.addParam({
                name: 'age',
            });

            let params = parser.params;

            parser.removeParams(['sex', 'age']);
            should(params['sex']).be.Undefined();
            should(params['age']).be.Undefined();
        });
    });

    describe('parse 方法测试', function () {
        let server;

        before(function () {
            server = http.createServer(function (req, res) {
                let parser = new Parser();
                parser.parse(req, res).on('end', function (data) {
                    res.writeHead(200, {
                        'Content-type': 'application/json',
                    });
                    res.end(JSON.stringify(data));
                });
            }).listen(5052);
        });

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

        describe('get请求处理', function () {
            it('should return {data: ""}', function (done) {
                http.get({
                    port: 5052,
                }, function (res) {
                    let data = [];
                    res.on('data', function (chunk) {
                        data.push(chunk);
                    }).on('end', function () {
                        data = JSON.parse(data.toString());
                        data.should.have.property('data');
                        console.log(data);
                        done();
                    });

                }).on('error', function (err) {
                    throw err;
                });
            });

            it('should return {data: {name: "lleohao"}}', function (done) {
                http.get({
                    port: 5052,
                    path: '/?name=lleohao',
                }, function (res) {
                    let data = [];
                    res.on('data', function (chunk) {
                        data.push(chunk);
                    }).on('end', function () {
                        data = JSON.parse(data.toString()).data;
                        data.should.have.property('name');
                        data['name'].should.be.equal('lleohao');
                        done();
                    });
                }).on('error', function (err) {
                    throw err;
                });
            });
        });

        describe('post put delete 等带有请求数据的请求处理', function () {
            it('should return {data: ""}', (done) => {
                let postData = '';

                let request = http.request({
                    port: 5052,
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Content-Length': Buffer.byteLength(postData)
                    }
                }, function (res) {
                    let data = [];
                    res.on('data', function (chunk) {
                        data.push(chunk);
                    }).on('end', function () {
                        data = JSON.parse(data.toString());
                        data.should.have.property('data');
                        done();
                    });
                });

                request.write(postData);
                request.end();
            });

            it('should return error message', (done) => {
                let postData = '';

                let request = http.request({
                    port: 5052,
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain',
                        'Content-Length': Buffer.byteLength(postData)
                    }
                }, function (res) {
                    let data = [];
                    res.on('data', function (chunk) {
                        data.push(chunk);
                    }).on('end', function () {
                        data = JSON.parse(data.toString()).data;
                        data.should.have.property('error');
                        done();
                    });
                });

                request.write(postData);
                request.end();
            });

            it('should return {data: {name: "lleohao"}}', (done) => {
                let postData = JSON.stringify({name: 'lleohao'});

                let request = http.request({
                    port: 5052,
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Content-Length': Buffer.byteLength(postData)
                    }
                }, function (res) {
                    let data = [];
                    res.on('data', function (chunk) {
                        data.push(chunk);
                    }).on('end', function () {
                        data = JSON.parse(data.toString()).data;
                        data.should.have.property('name');
                        data['name'].should.be.equal('lleohao')
                        done();
                    });
                });

                request.write(postData);
                request.end();
            });
        });
    });
});<|endoftext|>


<commit_before>/**
 * Created by lja on 2015/11/20.
 */

var type = (function () {
    'use strict';

    var class2type = {},
        toString = class2type.toString;

    ('Boolean Number String Function Array Date RegExp Object Error').split(' ').forEach(function (name) {
        class2type['[object ' + name + ']'] = name.toLowerCase();
    });

    function isWindow(obj) {
        return obj !== null && obj.window && obj === obj.window;
    }

    function isFunction(obj) {
        return class2type[toString.call(obj)] === 'function';
    }

    function isDocument(obj) {
        return obj && obj.nodeType === obj.DOCUMENT_NODE;
    }

    function isObject(obj) {
        return class2type[toString.call(obj)] === 'object';
    }

    function isArray(obj) {
        return class2type[toString.call(obj)] === 'array';
    }

    function isNumber(obj) {
        return class2type[toString.call(obj)] === 'number';
    }

    function isPlainObject(obj) {
        return isObject(obj) && !isWindow(obj) &&
            Object.getPrototypeOf(obj) === Object.prototype;
    }

    return {
        isWindow: isWindow,
        isFunction: isFunction,
        isDocument: isDocument,
        isObject: isObject,
        isPlainObject: isPlainObject,
        isArray: isArray,
        isNumber: isNumber
    };
})();

var Jackey8 = (function (type) {
    'use strict';

    var J8,
        emptyArray = [],
        slice = emptyArray.slice,
        jackey8 = {},
        table = document.createElement('table'),
        tableRow = document.createElement('tr'),
        containers = {
            'tr': document.createElement('tbody'),
            'tbody': table, 'thead': table, 'tfoot': table,
            'td': tableRow, 'th': tableRow,
            '*': document.createElement('div')
        },
    //special attributes that should be get/set via method calls
        methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
        simpleSelectorRE = /^[\w-]*$/,//字母 数字 或者下划线，不包括空格
        tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,//tag reg
        readyRE = /complete|loaded|interactive/,
        htmlFragmentRE = /^\s*<(\w+|!)[^>]*>/;//html片段

    //去除null的值
    function removeNullArray(array) {
        return emptyArray.filter.call(array, function (item) {
            return item !== null;
        });
    }

    //decorate the __proto__ and selector
    //todo: __proto__ not supported on IE
    jackey8.decorateDom = function (dom, selector) {
        dom = dom || [];
        dom.__proto__ = J8.fn;//jshint ignore:line
        dom.selector = selector;
        return dom;
    };

    //通过html片段创建dom节点
    jackey8.createNodeByHtmlFragment = function (html, name, properties) {
        var dom, nodes, container;

        //如果是简单的标签，则直接创建元素
        if (simpleSelectorRE.test(html)) {
            dom = J8(document.createElement(RegExp.$1));
        }

        if (!dom) {
            if (html.replace) {
                html = html.replace(tagExpanderRE, '<$1></$2>');
            }

            //正则选取出标签名称
            if (name === void 0) {
                name = htmlFragmentRE.test(html) && RegExp.$1;
            }

            //为了区别标签是否为table内的元素
            // 'tr': document.createElement('tbody'),
            //'tbody': table, 'thead': table, 'tfoot': table,
            //'td': tableRow, 'th': tableRow
            //其他标签都使用div作为parentNode
            if (!(name in containers)) {
                name = '*';
            }

            container = containers[name];
            container.innerHTML = '' + html;//添加到parentNode，并实现转换成dom的过程
            dom = J8.each(slice.call(container.childNodes), function () {
                container.removeChild(this);//从parentNode中移除，并返回childNodes
            });
        }

        //methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
        //如果属性在上面中，则直接赋值，否则通过attr方法去赋值
        if (type.isPlainObject(properties)) {
            nodes = J8(dom);
            J8.each(properties, function (key, value) {
                if (methodAttributes.indexOf(key) > -1) {
                    nodes[key](value);
                } else {
                    nodes.attr(key, value);
                }
            });
        }
    };

    /**
     * find selector in context
     * by id class and 复杂类型：ul li
     * @param context
     * @param selector
     */
    jackey8.queryDom = function (context, selector) {
        var found = [],
            maybeId = selector[0] === '#',
            maybeClass = selector[0] === '.',
            name = maybeId || maybeClass ? selector.slice(1) : selector,
            isSample = simpleSelectorRE.test(name);

        if (!type.isDocument(context)) {
            return found;
        }

        //如果不是简单类型（复杂类型ul li a），使用querySelectorAll
        if (!isSample) {
            found = slice.call(context.querySelectorAll(selector));
        } else {
            if (maybeId) {
                found = context.getElementById(name);
                if (found) {
                    return [found];
                }
                return [];
            }

            if (maybeClass) {
                found = context.getElementsByClassName(name);
            } else {
                found = context.getElementsByTagName(name);
            }
        }

        return slice.call(found);
    };

    //selector: empty string function object array and the instance of Jackey8
    jackey8.init = function (selector, context) {
        var dom;

        //if nothing given, return an empty collection
        if (!selector) {
            return jackey8.decorateDom();
        }

        if (typeof selector === 'string') {
            selector = selector.trim();

            //如果它是一个html片段，则创建一个节点
            //提示：在chrome21和Firefox15下面，
            // 如果不是<开头， 会抛错
            if (selector[0] === '<' && htmlFragmentRE.test(selector)) {
                //todo:
                dom = jackey8.createNodeByHtmlFragment(selector, RegExp.$1, context);
                selector = null;
            }
            //如果有parent，则先找到parent,然后使用find去找到selector
            else if (context !== void 0) {
                J8(context).find(selector);
            }
            else {
                // 正常的选取
                // 1 id 2 class 3 复杂选取
                // 作用域为document，因为如果存在context，则执行$(conetxt).find(selector)
                dom = jackey8.queryDom(document, selector);
            }
        } else if (type.isFunction(selector)) {
            J8(document).ready(selector);
        } else if (selector instanceof jackey8.decorateDom) {
            return selector;
        } else if (type.isArray(selector)) {
            dom = removeNullArray(selector);
        } else if (type.isObject(selector)) {
            dom = [selector];
            selector = null;
        } else {
            dom = [];
        }

        return jackey8.decorateDom(dom, selector);
    };

    J8 = function (selector, context) {
        return jackey8.init(selector, context);
    };

    J8.map = function (elements, callback) {
        var value, values = [], i, key;
        if (type.isArray(elements)) {
            for (i = 0; i < elements.length; i++) {
                value = callback(elements[i], i);
                if (value !== null) {
                    values.push(value);
                }
            }
        } else {
            for (key in elements) {
                value = callback(elements[key], key);
                if (value) {
                    values.push(value);
                }
            }
        }

        return values;
    };

    /**
     * each
     * 遍历数组或者对象
     * @param elements
     * @param callback
     * @returns {*}
     */
    J8.each = function (elements, callback) {
        var i, key;
        if (type.isArray(elements)) {
            for (i = 0; i < elements.length; i++) {
                if (callback.call(elements[i], i, elements[i]) === false) {
                    return elements;
                }
            }
        } else {
            for (key in elements) {
                if (callback.call(elements[key], key, elements[key]) === false) {
                    return elements;
                }
            }
        }
        return elements;
    }

    J8.fn = {
        forEach: emptyArray.forEach,
        reduce: emptyArray.reduce,
        push: emptyArray.push,
        sort: emptyArray.sort,
        indexOf: emptyArray.indexOf,
        concat: emptyArray.concat,
        ready: function (callback) {
            //dom载入判断
            //readyRE = /complete|loaded|interactive/,
            //for IE chrome
            if (readyRE.test(document.readyState) && document.body) {
                callback(J8);
            } else {
                //for firefox
                //IE5678 not working
                document.addEventListener('DOMContentLoaded', function () {
                    callback(J8);
                }, false);
                return this;
            }
        },
        get: function (index) {
            if (!type.isNumber(index)) {
                return slice.call(this);
            }

            return index >= 0 ? this[index] : this[index + this.length];
        },
        toArray: function () {
            return slice.call(this);
        },
        size: function () {
            return this.length;
        }
    };

    return J8;

})(type);

window.Jackey8 = Jackey8;

if (window.J8 === void 0) {
    window.J8 = Jackey8;
}
<commit_msg>remove<commit_after>/**
 * Created by lja on 2015/11/20.
 */

var type = (function () {
    'use strict';

    var class2type = {},
        toString = class2type.toString;

    ('Boolean Number String Function Array Date RegExp Object Error').split(' ').forEach(function (name) {
        class2type['[object ' + name + ']'] = name.toLowerCase();
    });

    function isWindow(obj) {
        return obj !== null && obj.window && obj === obj.window;
    }

    function isFunction(obj) {
        return class2type[toString.call(obj)] === 'function';
    }

    function isDocument(obj) {
        return obj && obj.nodeType === obj.DOCUMENT_NODE;
    }

    function isObject(obj) {
        return class2type[toString.call(obj)] === 'object';
    }

    function isArray(obj) {
        return class2type[toString.call(obj)] === 'array';
    }

    function isNumber(obj) {
        return class2type[toString.call(obj)] === 'number';
    }

    function isPlainObject(obj) {
        return isObject(obj) && !isWindow(obj) &&
            Object.getPrototypeOf(obj) === Object.prototype;
    }

    return {
        isWindow: isWindow,
        isFunction: isFunction,
        isDocument: isDocument,
        isObject: isObject,
        isPlainObject: isPlainObject,
        isArray: isArray,
        isNumber: isNumber
    };
})();

var Jackey8 = (function (type) {
    'use strict';

    var J8,
        emptyArray = [],
        slice = emptyArray.slice,
        jackey8 = {},
        table = document.createElement('table'),
        tableRow = document.createElement('tr'),
        containers = {
            'tr': document.createElement('tbody'),
            'tbody': table, 'thead': table, 'tfoot': table,
            'td': tableRow, 'th': tableRow,
            '*': document.createElement('div')
        },
    //special attributes that should be get/set via method calls
        methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
        simpleSelectorRE = /^[\w-]*$/,//字母 数字 或者下划线，不包括空格
        tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,//tag reg
        readyRE = /complete|loaded|interactive/,
        htmlFragmentRE = /^\s*<(\w+|!)[^>]*>/;//html片段

    //去除null的值
    function removeNullArray(array) {
        return emptyArray.filter.call(array, function (item) {
            return item !== null;
        });
    }

    //decorate the __proto__ and selector
    //todo: __proto__ not supported on IE
    jackey8.decorateDom = function (dom, selector) {
        dom = dom || [];
        dom.__proto__ = J8.fn;//jshint ignore:line
        dom.selector = selector;
        return dom;
    };

    //通过html片段创建dom节点
    jackey8.createNodeByHtmlFragment = function (html, name, properties) {
        var dom, nodes, container;

        //如果是简单的标签，则直接创建元素
        if (simpleSelectorRE.test(html)) {
            dom = J8(document.createElement(RegExp.$1));
        }

        if (!dom) {
            if (html.replace) {
                html = html.replace(tagExpanderRE, '<$1></$2>');
            }

            //正则选取出标签名称
            if (name === void 0) {
                name = htmlFragmentRE.test(html) && RegExp.$1;
            }

            //为了区别标签是否为table内的元素
            // 'tr': document.createElement('tbody'),
            //'tbody': table, 'thead': table, 'tfoot': table,
            //'td': tableRow, 'th': tableRow
            //其他标签都使用div作为parentNode
            if (!(name in containers)) {
                name = '*';
            }

            container = containers[name];
            container.innerHTML = '' + html;//添加到parentNode，并实现转换成dom的过程
            dom = J8.each(slice.call(container.childNodes), function () {
                container.removeChild(this);//从parentNode中移除，并返回childNodes
            });
        }

        //methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
        //如果属性在上面中，则直接赋值，否则通过attr方法去赋值
        if (type.isPlainObject(properties)) {
            nodes = J8(dom);
            J8.each(properties, function (key, value) {
                if (methodAttributes.indexOf(key) > -1) {
                    nodes[key](value);
                } else {
                    nodes.attr(key, value);
                }
            });
        }
    };

    /**
     * find selector in context
     * by id class and 复杂类型：ul li
     * @param context
     * @param selector
     */
    jackey8.queryDom = function (context, selector) {
        var found = [],
            maybeId = selector[0] === '#',
            maybeClass = selector[0] === '.',
            name = maybeId || maybeClass ? selector.slice(1) : selector,
            isSample = simpleSelectorRE.test(name);

        if (!type.isDocument(context)) {
            return found;
        }

        //如果不是简单类型（复杂类型ul li a），使用querySelectorAll
        if (!isSample) {
            found = slice.call(context.querySelectorAll(selector));
        } else {
            if (maybeId) {
                found = context.getElementById(name);
                if (found) {
                    return [found];
                }
                return [];
            }

            if (maybeClass) {
                found = context.getElementsByClassName(name);
            } else {
                found = context.getElementsByTagName(name);
            }
        }

        return slice.call(found);
    };

    //selector: empty string function object array and the instance of Jackey8
    jackey8.init = function (selector, context) {
        var dom;

        //if nothing given, return an empty collection
        if (!selector) {
            return jackey8.decorateDom();
        }

        if (typeof selector === 'string') {
            selector = selector.trim();

            //如果它是一个html片段，则创建一个节点
            //提示：在chrome21和Firefox15下面，
            // 如果不是<开头， 会抛错
            if (selector[0] === '<' && htmlFragmentRE.test(selector)) {
                //todo:
                dom = jackey8.createNodeByHtmlFragment(selector, RegExp.$1, context);
                selector = null;
            }
            //如果有parent，则先找到parent,然后使用find去找到selector
            else if (context !== void 0) {
                J8(context).find(selector);
            }
            else {
                // 正常的选取
                // 1 id 2 class 3 复杂选取
                // 作用域为document，因为如果存在context，则执行$(conetxt).find(selector)
                dom = jackey8.queryDom(document, selector);
            }
        } else if (type.isFunction(selector)) {
            J8(document).ready(selector);
        } else if (selector instanceof jackey8.decorateDom) {
            return selector;
        } else if (type.isArray(selector)) {
            dom = removeNullArray(selector);
        } else if (type.isObject(selector)) {
            dom = [selector];
            selector = null;
        } else {
            dom = [];
        }

        return jackey8.decorateDom(dom, selector);
    };

    J8 = function (selector, context) {
        return jackey8.init(selector, context);
    };

    J8.map = function (elements, callback) {
        var value, values = [], i, key;
        if (type.isArray(elements)) {
            for (i = 0; i < elements.length; i++) {
                value = callback(elements[i], i);
                if (value !== null) {
                    values.push(value);
                }
            }
        } else {
            for (key in elements) {
                value = callback(elements[key], key);
                if (value) {
                    values.push(value);
                }
            }
        }

        return values;
    };

    /**
     * each
     * 遍历数组或者对象
     * @param elements
     * @param callback
     * @returns {*}
     */
    J8.each = function (elements, callback) {
        var i, key;
        if (type.isArray(elements)) {
            for (i = 0; i < elements.length; i++) {
                if (callback.call(elements[i], i, elements[i]) === false) {
                    return elements;
                }
            }
        } else {
            for (key in elements) {
                if (callback.call(elements[key], key, elements[key]) === false) {
                    return elements;
                }
            }
        }
        return elements;
    }

    J8.fn = {
        forEach: emptyArray.forEach,
        reduce: emptyArray.reduce,
        push: emptyArray.push,
        sort: emptyArray.sort,
        indexOf: emptyArray.indexOf,
        concat: emptyArray.concat,
        ready: function (callback) {
            //dom载入判断
            //readyRE = /complete|loaded|interactive/,
            //for IE chrome
            if (readyRE.test(document.readyState) && document.body) {
                callback(J8);
            } else {
                //for firefox
                //IE5678 not working
                document.addEventListener('DOMContentLoaded', function () {
                    callback(J8);
                }, false);
                return this;
            }
        },
        get: function (index) {
            if (!type.isNumber(index)) {
                return slice.call(this);
            }

            return index >= 0 ? this[index] : this[index + this.length];
        },
        toArray: function () {
            return slice.call(this);
        },
        size: function () {
            return this.length;
        },
        remove: function () {
            return this.each(function () {
                if (this.parentNode !== null) {
                    this.parentNode.remove(this);
                }
            });
        },
        each: function (callback) {
            emptyArray.every.call(this, function (element, index) {
                return callback.call(element, index, element) !== false;
            });
            return this;
        }
    };

    return J8;

})(type);

window.Jackey8 = Jackey8;

if (window.J8 === void 0) {
    window.J8 = Jackey8;
}
<|endoftext|>


<commit_before>
var fs = require('fs');
var path = require('path');
var endpoint = require('endpoint');
var modulebox = require('../../lib/dispatch.js');

var test = require('tap').test;

var box = modulebox({
  root: path.resolve(__dirname, '..', 'localized'),

  modules: 'modules'
});

// Set mtime on /single.js and /pointer.js for consistency
var singleMtime = 1358000000;
fs.utimesSync(
  path.resolve(__dirname, '..', 'localized', 'single.js'),
  1350000000,
  singleMtime
);

var pointerMtime = 1357000000;
fs.utimesSync(
  path.resolve(__dirname, '..', 'localized', 'pointer.js'),
  1350000000,
  pointerMtime
);

test('no resources is send makes mtime null and resolved is hash', function (t) {
  var bundle = box.dispatch({
    request: '/single.js',
    acquired: ['/single.js']
  });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime, null);
    t.equal(meta.hash, 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');

    t.end();
  }));
});

test('when first resource isn\'t fetched meta is null', function (t) {
  var bundle = box.dispatch({ request: '/single.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta, null);
    t.end();
  }));
});

test('when all (one) resources is fetched meta is set', function (t) {
  var bundle = box.dispatch({ request: '/single.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime.getTime(), singleMtime * 1000);
    t.equal(meta.hash, '9e7c61311c0ad858cd4001679ca48870fbaac7cdfb52abfba4ecc936233e0a05');

    t.end();
  }));
});

test('when not all resources is fetched meta is null', function (t) {
  var bundle = box.dispatch({ request: '/pointer.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta, null);

    t.end();
  }));
});

test('when all resources is fetched meta is set', function (t) {
  var bundle = box.dispatch({ request: '/pointer.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime.getTime(), singleMtime * 1000);
    t.equal(meta.hash, '948888b46487c761c981c1f36087e3e0b5059b2aef1a92d3c0e126df77cdcde5');

    t.end();
  }));
});

test('mtime and hash depends on the acquired files', function (t) {
  var bundle = box.dispatch({
    request: '/pointer.js',
    acquired: ['/single.js']
  });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime.getTime(), pointerMtime * 1000);
    t.equal(meta.hash, 'a8417aa246cf8621c1fa06c6f56f3c743dab5e88d869fd3a8a3ca2858a695722');

    t.end();
  }));
});
<commit_msg>[test] meta fetching in faulty require<commit_after>
var fs = require('fs');
var path = require('path');
var endpoint = require('endpoint');
var modulebox = require('../../lib/dispatch.js');

var test = require('tap').test;

var box = modulebox({
  root: path.resolve(__dirname, '..', 'localized'),

  modules: 'modules'
});

// Set mtime on /single.js and /pointer.js for consistency
var singleMtime = 1358000000;
fs.utimesSync(
  path.resolve(__dirname, '..', 'localized', 'single.js'),
  1350000000,
  singleMtime
);

var pointerMtime = 1357000000;
fs.utimesSync(
  path.resolve(__dirname, '..', 'localized', 'pointer.js'),
  1350000000,
  pointerMtime
);

var faultyMtime = 1357000000;
fs.utimesSync(
  path.resolve(__dirname, '..', 'localized', 'faulty_require.js'),
  1350000000,
  pointerMtime
);

test('no resources is send makes mtime null and resolved is hash', function (t) {
  var bundle = box.dispatch({
    request: '/single.js',
    acquired: ['/single.js']
  });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime, null);
    t.equal(meta.hash, 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');

    t.end();
  }));
});

test('when first resource isn\'t fetched meta is null', function (t) {
  var bundle = box.dispatch({ request: '/single.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta, null);
    t.end();
  }));
});

test('when all (one) resources is fetched meta is set', function (t) {
  var bundle = box.dispatch({ request: '/single.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime.getTime(), singleMtime * 1000);
    t.equal(meta.hash, '9e7c61311c0ad858cd4001679ca48870fbaac7cdfb52abfba4ecc936233e0a05');

    t.end();
  }));
});

test('when not all resources is fetched meta is null', function (t) {
  var bundle = box.dispatch({ request: '/pointer.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta, null);

    t.end();
  }));
});

test('when all resources is fetched meta is set', function (t) {
  var bundle = box.dispatch({ request: '/pointer.js' });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime.getTime(), singleMtime * 1000);
    t.equal(meta.hash, '948888b46487c761c981c1f36087e3e0b5059b2aef1a92d3c0e126df77cdcde5');

    t.end();
  }));
});

test('mtime and hash depends on the acquired files', function (t) {
  var bundle = box.dispatch({
    request: '/pointer.js',
    acquired: ['/single.js']
  });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime.getTime(), pointerMtime * 1000);
    t.equal(meta.hash, 'a8417aa246cf8621c1fa06c6f56f3c743dab5e88d869fd3a8a3ca2858a695722');

    t.end();
  }));
});

test('loading faulty module for first time should send null meta data', function (t) {
  var bundle = box.dispatch({
    request: '/faulty_require.js',
  });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta, null);

    t.end();
  }));
});

test('when loading faulty module that mtime and hash can be fetched', function (t) {
  var bundle = box.dispatch({
    request: '/faulty_require.js',
  });

  var meta;
  bundle.once('meta', function (data) {
    meta = data;
  });

  bundle.pipe(endpoint(function (err) {
    t.equal(err, null);
    t.equal(meta.mtime.getTime(), faultyMtime * 1000);
    t.equal(meta.hash, '12d2aff6b1b4e790468a4312a457882a73ba8ad67ab5b8afc864a67bbea03b29');

    t.end();
  }));
});
<|endoftext|>


<commit_before>const expect = require('chai').expect;
const axios = require('axios');
const request = require('supertest');
const app = require('../../server.js');  //gets the app started
req = request('http://localhost:8080');

describe('Server tests', function() {

  describe('/', function() {
    it('should return index.html on a get request', function(done) {
      axios.get('http://localhost:8080/')
        .then(function (response) {
          expect(response.data).to.contain('ng-app');
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });
  });

  describe('/auth/login', function() {
    it('should return a response on a post request', function(done) {
      axios.post('http://localhost:8080/auth/login')
        .then(function (response) {
          expect(response.data).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });

    it('should return a json web token', function(done) {
      axios.post('http://localhost:8080/auth/signup')
        .then(function (response) {
          expect(response.data.token).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });
  });

  describe('/signup', function() {
    it('should return a response on a post request', function(done) {
      axios.post('http://localhost:8080/auth/signup')
        .then(function (response) {
          expect(response.data).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });

    it('should return a json web token', function(done) {
      axios.post('http://localhost:8080/auth/signup')
        .then(function (response) {
          expect(response.data.token).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });
  });

  describe('authentication', function() {

    describe('json web token', function() {
      it('should reject access', function(done) {
        req.post('/testAuth')
          .expect(401, done);
      });

      it('should grant access', function(done) {
        let token;

        req.post('/auth/login')
          .then(function (response) {
            console.log(response);
            expect(response.body.token).to.exist;
            req.post('/testAuth')
              .set('Authorization', `Bearer ${response.body.token}`)
              .expect(200, done);
          });
      });
    });
  });
});
<commit_msg>Fix file path for server.js<commit_after>const expect = require('chai').expect;
const axios = require('axios');
const request = require('supertest');
const app = require('../../server/server.js');  //gets the app started
req = request('http://localhost:8080');

describe('Server tests', function() {

  describe('/', function() {
    it('should return index.html on a get request', function(done) {
      axios.get('http://localhost:8080/')
        .then(function (response) {
          expect(response.data).to.contain('ng-app');
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });
  });

  describe('/auth/login', function() {
    it('should return a response on a post request', function(done) {
      axios.post('http://localhost:8080/auth/login')
        .then(function (response) {
          expect(response.data).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });

    it('should return a json web token', function(done) {
      axios.post('http://localhost:8080/auth/signup')
        .then(function (response) {
          expect(response.data.token).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });
  });

  describe('/signup', function() {
    it('should return a response on a post request', function(done) {
      axios.post('http://localhost:8080/auth/signup')
        .then(function (response) {
          expect(response.data).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });

    it('should return a json web token', function(done) {
      axios.post('http://localhost:8080/auth/signup')
        .then(function (response) {
          expect(response.data.token).to.exist;
          done();
        })
        .catch(function (error) {
          console.log(error);
          done();
        });
    });
  });

  describe('authentication', function() {

    describe('json web token', function() {
      it('should reject access', function(done) {
        req.post('/testAuth')
          .expect(401, done);
      });

      it('should grant access', function(done) {
        let token;

        req.post('/auth/login')
          .then(function (response) {
            console.log(response);
            expect(response.body.token).to.exist;
            req.post('/testAuth')
              .set('Authorization', `Bearer ${response.body.token}`)
              .expect(200, done);
          });
      });
    });
  });
});
<|endoftext|>


<commit_before>// Copyright (c) 2012 Titanium I.T. LLC. All rights reserved. See LICENSE.txt for details.
/*global desc, task, jake, fail, complete, directory, require, console, process */
(function () {
	"use strict";

	var TESTED_BROWSERS = [
		// "IE 8.0 (Windows)",  // DOES NOT WORK -- no SVG support
		// "IE 9.0 (Windows)",  // DOES NOT WORK -- no Int32Array support and shim causes 'Out of memory' error
		"IE 10.0 (Windows)",
		"Firefox 21.0 (Mac)",
		"Chrome 27.0 (Mac)",
		"Safari 6.0 (Mac)",
		"Safari 6.0 (iOS)"
	];

	var NODE_VERSION = "v0.10.6";

	var lint = require("./build/util/lint_runner.js");
	var karma = require("./build/util/karma_runner.js");
	var version = require("./build/util/version_checker.js");

	desc("Lint and test");
	task("default", ["lint", "test"], function() {
		console.log("\n\nBUILD OK");
	});

	desc("Start Karma server -- run this first");
	task("karma", function() {
		karma.serve(complete, fail);
	}, {async: true});

	desc("Lint everything");
	task("lint", ["nodeVersion"], function () {
		var passed = lint.validateFileList(nodeFilesToLint(), nodeLintOptions(), {});
		passed = lint.validateFileList(browserFilesToLint(), browserLintOptions(), browserLintGlobals()) && passed;
		if (!passed) fail("Lint failed");
	});

	desc("Test browser code");
	task("test", function() {
		karma.runTests(TESTED_BROWSERS, complete, fail);
	}, {async: true});

//	desc("Ensure installed version of Node is same as known-good version");
	task("nodeVersion", [], function() {
		var installedVersion = process.version;
		version.check("Node", !process.env.loose, NODE_VERSION, installedVersion, fail);
	});

	function nodeFilesToLint() {
		var files = new jake.FileList();
		files.include("build/util/**/*.js");
		files.include("Jakefile.js");
		return files.toArray();
	}

	function browserFilesToLint() {
		var files = new jake.FileList();
		files.include("src/*.js");
		return files.toArray();
	}

	function sharedLintOptions() {
		return {
			bitwise:true,
			curly:false,
			eqeqeq:true,
			forin:true,
			immed:true,
			latedef:false,
			newcap:true,
			noarg:true,
			noempty:true,
			nonew:true,
			regexp:true,
			undef:true,
			strict:true,
			trailing:true
		};
	}

	function nodeLintOptions() {
		var options = sharedLintOptions();
		options.node = true;
		return options;
	}

	function browserLintOptions() {
		var options = sharedLintOptions();
		options.browser = true;
		return options;
	}

	function browserLintGlobals() {
		return {
			jdls: true,

			mocha: false,
			describe: false,
			it: false,
			expect: false,
			dump: false,
			beforeEach: false,
			afterEach: false
		};
	}

}());<commit_msg>Upgraded Firefox 21.0 -> 22.0; Chrome 27.0 -> 28.0<commit_after>// Copyright (c) 2012 Titanium I.T. LLC. All rights reserved. See LICENSE.txt for details.
/*global desc, task, jake, fail, complete, directory, require, console, process */
(function () {
	"use strict";

	var TESTED_BROWSERS = [
		// "IE 8.0 (Windows)",  // DOES NOT WORK -- no SVG support
		// "IE 9.0 (Windows)",  // DOES NOT WORK -- no Int32Array support and shim causes 'Out of memory' error
		"IE 10.0 (Windows)",
		"Firefox 22.0 (Mac)",
		"Chrome 28.0 (Mac)",
		"Safari 6.0 (Mac)",
		"Safari 6.0 (iOS)"
	];

	var NODE_VERSION = "v0.10.6";

	var lint = require("./build/util/lint_runner.js");
	var karma = require("./build/util/karma_runner.js");
	var version = require("./build/util/version_checker.js");

	desc("Lint and test");
	task("default", ["lint", "test"], function() {
		console.log("\n\nBUILD OK");
	});

	desc("Start Karma server -- run this first");
	task("karma", function() {
		karma.serve(complete, fail);
	}, {async: true});

	desc("Lint everything");
	task("lint", ["nodeVersion"], function () {
		var passed = lint.validateFileList(nodeFilesToLint(), nodeLintOptions(), {});
		passed = lint.validateFileList(browserFilesToLint(), browserLintOptions(), browserLintGlobals()) && passed;
		if (!passed) fail("Lint failed");
	});

	desc("Test browser code");
	task("test", function() {
		karma.runTests(TESTED_BROWSERS, complete, fail);
	}, {async: true});

//	desc("Ensure installed version of Node is same as known-good version");
	task("nodeVersion", [], function() {
		var installedVersion = process.version;
		version.check("Node", !process.env.loose, NODE_VERSION, installedVersion, fail);
	});

	function nodeFilesToLint() {
		var files = new jake.FileList();
		files.include("build/util/**/*.js");
		files.include("Jakefile.js");
		return files.toArray();
	}

	function browserFilesToLint() {
		var files = new jake.FileList();
		files.include("src/*.js");
		return files.toArray();
	}

	function sharedLintOptions() {
		return {
			bitwise:true,
			curly:false,
			eqeqeq:true,
			forin:true,
			immed:true,
			latedef:false,
			newcap:true,
			noarg:true,
			noempty:true,
			nonew:true,
			regexp:true,
			undef:true,
			strict:true,
			trailing:true
		};
	}

	function nodeLintOptions() {
		var options = sharedLintOptions();
		options.node = true;
		return options;
	}

	function browserLintOptions() {
		var options = sharedLintOptions();
		options.browser = true;
		return options;
	}

	function browserLintGlobals() {
		return {
			jdls: true,

			mocha: false,
			describe: false,
			it: false,
			expect: false,
			dump: false,
			beforeEach: false,
			afterEach: false
		};
	}

}());<|endoftext|>


<commit_before>var fs = require('fs')
  , VERSION = fs.readFileSync('VERSION', 'utf-8')

function concat(fileList, destPath) {
  var out = fileList.map(function (filePath) {
    var file = fs.readFileSync(filePath, 'utf-8')
    file = file.replace(/@VERSION/g, VERSION)
    return file
  })
  fs.writeFileSync(destPath, out.join('\n'))
}

function colorize(str, color) {
  var colors =
    { 'blue': '34m'
    , 'cyan': '36m'
    , 'green': '01;32m'
    , 'magenta': '35m'
    , 'red': '31m'
    , 'yellow': '33m'
    }

  return colors[color] ? '\033[' + colors[color] + str + '\033[39m' : str
}

desc('Lint all js files')
task('lint', [], function () {
  jake.Task['lint:all'].invoke()
}, {async: true})

namespace('lint', function () {
  var jakefile = 'Jakefile.js'
    , jshintrc = '.jshintrc'
    , editor = 'src/editor.js'
    , tests = 'test'
    , docs = 'docs/js/main.js'

  task('all', ['lint:editor', 'lint:docs', 'lint:tests', 'lint:util'], function () {
    complete()
  }, {async: true})

  desc('Lint core EpicEditor: src/editor.js')
  task('editor', [], function () {
    console.log(colorize('--> Linting editor', 'yellow'))
    var files = [ editor ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})

  desc('Lint doc related js: docs/js/main.js')
  task('docs', [], function () {
    console.log(colorize('--> Linting docs', 'yellow'))
    var files = [ docs ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})

  desc('Lint test related js: test/*')
  task('tests', [], function () {
    console.log(colorize('--> Linting tests', 'yellow'))
    var files = [ tests ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})

  desc('Lint utility and config js files')
  task('util', [], function () {
    console.log(colorize('--> Linting utils', 'yellow'))
    var files = [ jshintrc, jakefile ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc --extra-ext .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})
})

desc('Build epiceditor.js and minify to epiceditor.min.js')
task('build', ['build:init', 'lint:editor'], function () {
  console.log(colorize('--> Building', 'yellow'))
  var destDir = 'epiceditor/js/'
    , srcDir = 'src/'
    , parser = process.env.parser ? process.env.parser : srcDir + 'marked/lib/marked.js'
    , srcPaths =
      [ srcDir + 'editor.js'
      , parser
      ]
    , destPath = destDir + 'epiceditor.js'
    , destPathMin = destDir + 'epiceditor.min.js'
    , cmds = ['uglifyjs ' + destPath + ' > ' + destPathMin]

  // If the destination directory does not exist, create it
  jake.mkdirP('epiceditor/js')

  if (!fs.existsSync(parser)) {
    fail("Parser path not found.")
  }

  concat(srcPaths, destPath)

  // Minify
  jake.exec(cmds, function () {
    console.log(colorize('  √ ok', 'green'))
    complete()
  }, {stdout: true})
}, {async: true})

namespace('build', function () {
  desc('Force build epiceditor.js and epiceditor.min.js skipping pre-reqs')
  task('force', [], function () {
    console.log(colorize('--> Warning: Force build skips build pre-reqs. This build should not be commited.', 'magenta'))
    jake.Task['build'].execute()
  })

  task('init', [], function () {
    jake.exec(['git submodule update --init'], function () {
      complete()
    }, {stdout: true})
  }, {async: true})
})

desc('Build index.html from the README')
task('docs', ['lint:docs'], function () {
  console.log(colorize('--> Building docs', 'yellow'))
  var destDir = './'
    , srcDir = 'docs/'
    , readmePath = destDir + 'README.md'
    , tempPath = srcDir + 'README.html'
    , destPath = destDir + 'index.html'
    , srcPaths =
      [ srcDir + 'header.html'
      , tempPath
      , srcDir + 'footer.html'
      ]
    , cmds = ['marked -o ' + tempPath + ' -i ' + readmePath + ' --gfm']

  jake.exec(cmds, function () {
    concat(srcPaths, destPath)
    // remove temporary README.html
    fs.unlink(tempPath)
    console.log(colorize('  √ ok', 'green'))
    complete()
  }, {stdout: true})
}, {async: true})

desc('Test code against tests')
task('test', ['lint:tests'], function () {
  console.log(colorize('--> Test suite is now running (CTRL+C to quit)', 'magenta'))
  console.log(colorize('--> http://localhost:8888/tests/tests.html', 'yellow'))
  jake.exec(['node test/server.js'], function () {
    complete()
  }, {stdout: false})
}, {async: true})

var pkg = new jake.PackageTask('EpicEditor', 'v' + VERSION, function () {
  var fileList = [ 'epiceditor']
  this.packageDir = "docs/downloads"
  this.packageFiles.include(fileList)
  this.needZip = true
})

desc('Kick out some ascii')
task('ascii', [], function () {
  var epicAscii = "" +
      "                                           \n" +
      "                               ',          \n" +
      "                    .eee.     .'           \n" +
      "                  .eeEEEEEe.               \n" +
      " EEEEEEEEEEEE'  .E'   `eEE'  .EEEEEEEEEEE  \n" +
      " EE           .E'    eEE`  .E          EE  \n" +
      " EE         .E'    eEE`    EE          EE  \n" +
      " EE       .E'    eEE`      EE              \n" +
      " EE     .E'    eEE`        EEEEEEEEEE      \n" +
      " EE          eEE`          EE              \n" +
      " EE   .    `eE`            EE              \n" +
      " EE   Ee'                  EE          EE  \n" +
      " EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE  \n"
  console.log(colorize(epicAscii, 'yellow'))
  console.log(colorize('EpicEditor - An Embeddable JavaScript Markdown Editor', 'yellow'))
})
<commit_msg>stop Jake from lying<commit_after>var fs = require('fs')
  , VERSION = fs.readFileSync('VERSION', 'utf-8')

function concat(fileList, destPath) {
  var out = fileList.map(function (filePath) {
    var file = fs.readFileSync(filePath, 'utf-8')
    file = file.replace(/@VERSION/g, VERSION)
    return file
  })
  fs.writeFileSync(destPath, out.join('\n'))
}

function colorize(str, color) {
  var colors =
    { 'blue': '34m'
    , 'cyan': '36m'
    , 'green': '01;32m'
    , 'magenta': '35m'
    , 'red': '31m'
    , 'yellow': '33m'
    }

  return colors[color] ? '\033[' + colors[color] + str + '\033[39m' : str
}

desc('Lint all js files')
task('lint', [], function () {
  jake.Task['lint:all'].invoke()
}, {async: true})

namespace('lint', function () {
  var jakefile = 'Jakefile.js'
    , jshintrc = '.jshintrc'
    , editor = 'src/editor.js'
    , tests = 'test'
    , docs = 'docs/js/main.js'

  task('all', ['lint:editor', 'lint:docs', 'lint:tests', 'lint:util'], function () {
    complete()
  }, {async: true})

  desc('Lint core EpicEditor: src/editor.js')
  task('editor', [], function () {
    console.log(colorize('--> Linting editor', 'yellow'))
    var files = [ editor ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})

  desc('Lint doc related js: docs/js/main.js')
  task('docs', [], function () {
    console.log(colorize('--> Linting docs', 'yellow'))
    var files = [ docs ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})

  desc('Lint test related js: test/*')
  task('tests', [], function () {
    console.log(colorize('--> Linting tests', 'yellow'))
    var files = [ tests ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})

  desc('Lint utility and config js files')
  task('util', [], function () {
    console.log(colorize('--> Linting utils', 'yellow'))
    var files = [ jshintrc, jakefile ]
      , cmds = ['jshint ' + files.join(' ') + ' --config .jshintrc --extra-ext .jshintrc']

    jake.exec(cmds, function () {
      console.log(colorize('  √ ok', 'green'))
      complete()
    }, {stdout: true})
  }, {async: true})
})

desc('Build epiceditor.js and minify to epiceditor.min.js')
task('build', ['build:init', 'lint:editor'], function () {
  console.log(colorize('--> Building', 'yellow'))
  var destDir = 'epiceditor/js/'
    , srcDir = 'src/'
    , parser = process.env.parser ? process.env.parser : srcDir + 'marked/lib/marked.js'
    , srcPaths =
      [ srcDir + 'editor.js'
      , parser
      ]
    , destPath = destDir + 'epiceditor.js'
    , destPathMin = destDir + 'epiceditor.min.js'
    , cmds = ['uglifyjs ' + destPath + ' > ' + destPathMin]

  // If the destination directory does not exist, create it
  jake.mkdirP('epiceditor/js')

  if (!fs.existsSync(parser)) {
    fail("Parser path not found.")
  }

  concat(srcPaths, destPath)

  // Minify
  jake.exec(cmds, function () {
    console.log(colorize('  √ ok', 'green'))
    complete()
  }, {stdout: true})
}, {async: true})

namespace('build', function () {
  desc('Force build epiceditor.js and epiceditor.min.js skipping pre-reqs')
  task('force', [], function () {
    console.log(colorize('--> Warning: Force build skips build pre-reqs. This build should not be commited.', 'magenta'))
    jake.Task['build'].execute()
  })

  task('init', [], function () {
    jake.exec(['git submodule update --init'], function () {
      complete()
    }, {stdout: true})
  }, {async: true})
})

desc('Build index.html from the README')
task('docs', ['lint:docs'], function () {
  console.log(colorize('--> Building docs', 'yellow'))
  var destDir = './'
    , srcDir = 'docs/'
    , readmePath = destDir + 'README.md'
    , tempPath = srcDir + 'README.html'
    , destPath = destDir + 'index.html'
    , srcPaths =
      [ srcDir + 'header.html'
      , tempPath
      , srcDir + 'footer.html'
      ]
    , cmds = ['marked -o ' + tempPath + ' -i ' + readmePath + ' --gfm']

  jake.exec(cmds, function () {
    concat(srcPaths, destPath)
    // remove temporary README.html
    fs.unlink(tempPath)
    console.log(colorize('  √ ok', 'green'))
    complete()
  }, {stdout: true})
}, {async: true})

desc('Test code against tests')
task('test', ['lint:tests'], function () {
  console.log(colorize('--> Test suite is now running (CTRL+C to quit)', 'magenta'))
  console.log(colorize('--> http://localhost:8888/test/tests.html', 'yellow'))
  jake.exec(['node test/server.js'], function () {
    complete()
  }, {stdout: false})
}, {async: true})

var pkg = new jake.PackageTask('EpicEditor', 'v' + VERSION, function () {
  var fileList = [ 'epiceditor']
  this.packageDir = "docs/downloads"
  this.packageFiles.include(fileList)
  this.needZip = true
})

desc('Kick out some ascii')
task('ascii', [], function () {
  var epicAscii = "" +
      "                                           \n" +
      "                               ',          \n" +
      "                    .eee.     .'           \n" +
      "                  .eeEEEEEe.               \n" +
      " EEEEEEEEEEEE'  .E'   `eEE'  .EEEEEEEEEEE  \n" +
      " EE           .E'    eEE`  .E          EE  \n" +
      " EE         .E'    eEE`    EE          EE  \n" +
      " EE       .E'    eEE`      EE              \n" +
      " EE     .E'    eEE`        EEEEEEEEEE      \n" +
      " EE          eEE`          EE              \n" +
      " EE   .    `eE`            EE              \n" +
      " EE   Ee'                  EE          EE  \n" +
      " EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE  \n"
  console.log(colorize(epicAscii, 'yellow'))
  console.log(colorize('EpicEditor - An Embeddable JavaScript Markdown Editor', 'yellow'))
})
<|endoftext|>


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

module.exports = {
  css: {
    extract: false,
  },

  outputDir: 'lib',

  configureWebpack: {
    resolve: {
      alias: {
        '@': path.resolve('src'),
      },
    },
  },

  lintOnSave: undefined,
};
<commit_msg>Format `vue-config.js`<commit_after>const path = require('path');

module.exports = {
  css: {
    extract: false,
  },
  outputDir: 'lib',
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.resolve('src'),
      },
    },
  },
  lintOnSave: undefined,
};
<|endoftext|>


<commit_before>var config = require('./config/config');
var amqp = require('amqplib/callback_api');
var fs = require('fs');
var path = require('path');
var celllog = require('./celllog');
var logger = require('./utils/logger');
var zlib = require('zlib');
var i_cell = 0;
var i_wifi = 0;
var i = 0;
var split = require('split');

var watchFolder = __dirname + '/' + config.watch.folder;
var processedFolder = __dirname + '/' + config.watch.processed;
var files = [];
var amqpConnection;
var channel;

// method that starts this processed
// 0. connect to RabbitMQ
// 1. reads current
// 2. start watch folder
// 3. start processNext method
function startup() {
	connectToRabbitMQ();
	logger.log('status', 'CellData parser is started');

	// read current files in dir
	fs.readdir(watchFolder, function(err, newFiles) {
		files = files.concat(newFiles);
	});

	// start watching dir for new files
	logger.log('status', 'Watching folder ' + watchFolder);
	fs.watch(watchFolder, function(event, filename) {
		if (filename) {
			if (event === 'rename') {
				files.push(filename);
			}
		}
	});

}

function mkCallback(i) {

	return function(err) {
		if (err !== null) {
			logger.log('error', 'Message' + i + 'failed');
		}
	}

}

// processFile opens the given filename, split it, parse it and send to
// the WIFI or cell queue.
function processFile(filename) {
	var readStream = fs.createReadStream(watchFolder + filename);

	readStream.on('open', function() {
		logger.log('info', 'Open file: ' + filename);
		clparser = celllog.createCellog();

		var cl = readStream.pipe(split()).pipe(clparser);

		cl.on('data', function(chunk) {
			i++;
			var send = JSON.stringify(chunk);
			if (chunk.bssid) {
				i_wifi++;
				sendToQueue('WIFI', send);
			} else {
				i_cell++;
				sendToQueue('cell', send);
			}

		});
		cl.on('end', function() {
			logger.log('status', 'FINISHED PROCESSING ' + filename);
			processNext();
		});

	});

	readStream.on('end', function() {
		logger.log('info', 'Messages processed:' + i + ' total (' + i_cell + ' cells, ' + i_wifi + ' wifi)');

		fs.rename(watchFolder + filename, processedFolder + filename, function(err) {
			if (err) {
				logger.log(err);
			}
		});
	})
}

function processZippedFile(filename) {
	logger.log('status', 'Unzipping file ' + filename);
	const gunzip = zlib.createGunzip();
	const inp = fs.createReadStream(watchFolder + filename);

	clparser = celllog.createCellog();

	var cl = inp.pipe(gunzip).pipe(split()).pipe(clparser);

	cl.on('data', function(chunk) {
		i++;
		var send = JSON.stringify(chunk);
		if (chunk.bssid) {
			i_wifi++;
			sendToQueue('WIFI', send);
		} else {
			i_cell++;
			sendToQueue('cell', send);
		}

	});
	cl.on('end', function() {
		logger.log('status', 'FINISHED PROCESSING ' + filename);
		logger.log('info', 'Messages processed:' + i + ' total (' + i_cell + ' cells, ' + i_wifi + ' wifi)');

		fs.rename(watchFolder + filename, processedFolder + filename, function(err) {
			if (err) {
				logger.log(err);
			}
		});
		processNext();
	});
}

function connectToRabbitMQ() {
	logger.log('status', "[AMQP] start connect");
	amqp.connect(config.amqp.server, function(err, conn) {
		if (err) {
      logger.log('error', "[AMQP] couldn't connect to RabbitMQ " + err.message);
			// retry in 1 second
      return setTimeout(connectToRabbitMQ, 1000);
    }
		conn.on("error", function(err) {
			if (err.message !== "Connection closing") {
				 logger.log('error', "[AMQP] conn error " + err.message);
			}
	 	});
	 	conn.on("close", function() {
			 logger.log('error', "[AMQP] reconnecting");
			 // retry in 1 second
			 return setTimeout(connectToRabbitMQ, 1000);
	 	});
	 	logger.log('status', "[AMQP] connected");
	 	amqpConnection = conn;

		createConfirmChannel();
	});
}

// closing connection when there is an error
function closeOnErr(err) {
  if (!err) return false;
  logger.log('error', "[AMQP] error " + err);
  amqpConnection.close();
  return true;
}

function createConfirmChannel() {
	amqpConnection.createConfirmChannel(function(err, ch) {
		if (closeOnErr(err)) return;
    ch.on("error", function(err) {
      logger.log('error', "[AMQP] channel error", err.message);
    });
    ch.on("close", function() {
      logger.log('status', "[AMQP] channel closed");
			setTimeout(createConfirmChannel, 1000);
    });
		channel = ch;
		logger.log('status', "[AMQP] channel created");
		setTimeout(processNext, 1000);
	});
}

// send data to queue name, makes a connection first and closes it afterwards.
function sendToQueue(routingKey, data) {
	channel.publish(config.amqp.queue, routingKey, new Buffer(data), {}, mkCallback(i));
}

function processNext() {
	var file = files.pop();
	if (typeof file !== 'undefined' && file) {
		logger.log('status', 'processNext file: ' + file);
		fs.stat(watchFolder + file, function(err, stats) {
			if (err) {
				// File does not exist
				processNext();
			} else if (stats.isFile() && path.extname(file) === '.log') {
				processFile(file);
			} else if (stats.isFile() && path.extname(file) === '.gz') {
				processZippedFile(file);
			} else {
				processNext();
			}
		});
	} else {
		setTimeout(processNext, 10000);
	}
}

// End yes we're up and running
startup();
<commit_msg>Enable persistent publishing to handle restarts<commit_after>var config = require('./config/config');
var amqp = require('amqplib/callback_api');
var fs = require('fs');
var path = require('path');
var celllog = require('./celllog');
var logger = require('./utils/logger');
var zlib = require('zlib');
var i_cell = 0;
var i_wifi = 0;
var i = 0;
var split = require('split');

var watchFolder = __dirname + '/' + config.watch.folder;
var processedFolder = __dirname + '/' + config.watch.processed;
var files = [];
var amqpConnection;
var channel;

// method that starts this processed
// 0. connect to RabbitMQ
// 1. reads current
// 2. start watch folder
// 3. start processNext method
function startup() {
	connectToRabbitMQ();
	logger.log('status', 'CellData parser is started');

	// read current files in dir
	fs.readdir(watchFolder, function(err, newFiles) {
		files = files.concat(newFiles);
	});

	// start watching dir for new files
	logger.log('status', 'Watching folder ' + watchFolder);
	fs.watch(watchFolder, function(event, filename) {
		if (filename) {
			if (event === 'rename') {
				files.push(filename);
			}
		}
	});

}

function mkCallback(i) {

	return function(err) {
		if (err !== null) {
			logger.log('error', 'Message' + i + 'failed');
		}
	}

}

// processFile opens the given filename, split it, parse it and send to
// the WIFI or cell queue.
function processFile(filename) {
	var readStream = fs.createReadStream(watchFolder + filename);

	readStream.on('open', function() {
		logger.log('info', 'Open file: ' + filename);
		clparser = celllog.createCellog();

		var cl = readStream.pipe(split()).pipe(clparser);

		cl.on('data', function(chunk) {
			i++;
			var send = JSON.stringify(chunk);
			if (chunk.bssid) {
				i_wifi++;
				sendToQueue('WIFI', send);
			} else {
				i_cell++;
				sendToQueue('cell', send);
			}

		});
		cl.on('end', function() {
			logger.log('status', 'FINISHED PROCESSING ' + filename);
			processNext();
		});

	});

	readStream.on('end', function() {
		logger.log('info', 'Messages processed:' + i + ' total (' + i_cell + ' cells, ' + i_wifi + ' wifi)');

		fs.rename(watchFolder + filename, processedFolder + filename, function(err) {
			if (err) {
				logger.log(err);
			}
		});
	})
}

function processZippedFile(filename) {
	logger.log('status', 'Unzipping file ' + filename);
	const gunzip = zlib.createGunzip();
	const inp = fs.createReadStream(watchFolder + filename);

	clparser = celllog.createCellog();

	var cl = inp.pipe(gunzip).pipe(split()).pipe(clparser);

	cl.on('data', function(chunk) {
		i++;
		var send = JSON.stringify(chunk);
		if (chunk.bssid) {
			i_wifi++;
			sendToQueue('WIFI', send);
		} else {
			i_cell++;
			sendToQueue('cell', send);
		}

	});
	cl.on('end', function() {
		logger.log('status', 'FINISHED PROCESSING ' + filename);
		logger.log('info', 'Messages processed:' + i + ' total (' + i_cell + ' cells, ' + i_wifi + ' wifi)');

		fs.rename(watchFolder + filename, processedFolder + filename, function(err) {
			if (err) {
				logger.log(err);
			}
		});
		processNext();
	});
}

function connectToRabbitMQ() {
	logger.log('status', "[AMQP] start connect");
	amqp.connect(config.amqp.server, function(err, conn) {
		if (err) {
      logger.log('error', "[AMQP] couldn't connect to RabbitMQ " + err.message);
			// retry in 1 second
      return setTimeout(connectToRabbitMQ, 1000);
    }
		conn.on("error", function(err) {
			if (err.message !== "Connection closing") {
				 logger.log('error', "[AMQP] conn error " + err.message);
			}
	 	});
	 	conn.on("close", function() {
			 logger.log('error', "[AMQP] reconnecting");
			 // retry in 1 second
			 return setTimeout(connectToRabbitMQ, 1000);
	 	});
	 	logger.log('status', "[AMQP] connected");
	 	amqpConnection = conn;

		createConfirmChannel();
	});
}

// closing connection when there is an error
function closeOnErr(err) {
  if (!err) return false;
  logger.log('error', "[AMQP] error " + err);
  amqpConnection.close();
  return true;
}

function createConfirmChannel() {
	amqpConnection.createConfirmChannel(function(err, ch) {
		if (closeOnErr(err)) return;
    ch.on("error", function(err) {
      logger.log('error', "[AMQP] channel error", err.message);
    });
    ch.on("close", function() {
      logger.log('status', "[AMQP] channel closed");
			setTimeout(createConfirmChannel, 1000);
    });
		channel = ch;
		logger.log('status', "[AMQP] channel created");
		setTimeout(processNext, 1000);
	});
}

// send data to queue name, makes a connection first and closes it afterwards.
function sendToQueue(routingKey, data) {
	channel.publish(config.amqp.queue, routingKey, new Buffer(data), {persistent: true}, mkCallback(i));
}

function processNext() {
	var file = files.pop();
	if (typeof file !== 'undefined' && file) {
		logger.log('status', 'processNext file: ' + file);
		fs.stat(watchFolder + file, function(err, stats) {
			if (err) {
				// File does not exist
				processNext();
			} else if (stats.isFile() && path.extname(file) === '.log') {
				processFile(file);
			} else if (stats.isFile() && path.extname(file) === '.gz') {
				processZippedFile(file);
			} else {
				processNext();
			}
		});
	} else {
		setTimeout(processNext, 10000);
	}
}

// End yes we're up and running
startup();
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert')
  , _ = require('lodash')
  , resource = 'test'
  , baseurl = '/api/v1/' + resource
  , model = 'name'
  , resources = [{id:1,name:'foo'}, {id:2,name:'bar'}, {id:3,name:'baz'}]
  , mock = {
        findAll: function(shouldIncludeDocs, next) {
            if (shouldIncludeDocs) {
                next(null, resources);
            } else {
                next(null, _.pluck(resources, 'id'));
            }
        },
        findById: function(id, next) {
            next(null, _.filter(resources, function(r) { return r.id === id; })[0] || {id: id, name: 'foo'});
        },
        filter: function(shouldIncludeDocs, filters, next) {
            var filtered = _.filter(resources, function(r) { return _.every(filters, function(f) { return r[f.property] == f.filter; }); });
            next(null, (shouldIncludeDocs) ? filtered : _.map(filtered, function(f) { return f.id; }));
        },
        save: function(data, next) {
            next(null, data.id || 7);
        }
    }
  , router = require('../src/router')(mock, { view: resource, fields: model });

function withJsonFormatter(res) {
    return _.extend(res, { format: function(e) { e.json(); } });
}

function withCommonProperties(req) {
    return _.extend(req, {
        baseUrl: baseurl,
        get: function() { return 'application/json'; }
    });
}

function resourceToUrl(resource) {
    return baseurl + '/' + resource.id;
}

describe('router', function() {
    describe('#error(res,err,next)', function() {
        it('should respond with a "500 internal server error" on errors', function(done) {
            var err = 'this is an error' // creating an error here would make mocha fail
              , res = withJsonFormatter({
                    status: function(code) {
                        assert.equal(500, code);
                        return res;
                    },
                    send: function(e) {
                        assert.equal(err, e);
                        return res;
                    }
                });

            router.error(res, err, function() {
                // mocha would fail when done being called with error
                // => make sure it is called without parameters
                done();
            });
        });
    });

    describe('#list(req,res,next)', function() {
        it('should respond with a list of urls relative to /', function(done) {
            var req = withCommonProperties({})
              , res = withJsonFormatter({
                    send: function(e) {
                        assert.deepEqual(_.map(resources, resourceToUrl), e);
                    }
                });

            router.list(req, res, done);
        });

        it('should respond with a list of docs when ?include_docs is set', function(done) {
            var req = withCommonProperties({
                    query: {include_docs: true}
                })
              , res = withJsonFormatter({
                    send: function(e) {
                        assert.deepEqual(resources, e);
                    }
                });

            router.list(req, res, done);
        });

        it('should respond with a exact-match filtered list when ?<field>=<filter> is set', function(done) {
            var req = withCommonProperties({
                    query: {name: 'foo'}
                })
              , res = withJsonFormatter({
                    send: function(e) {
                        assert.deepEqual(_.chain(resources)
                                         .filter(function(r) { return r.name === 'foo'; })
                                         .map(resourceToUrl)
                                         .value(), e);
                    }
                });

            router.list(req, res, done);
        });
    });

    describe('#create(req,res,next)', function() {
        it('should respond with the url of the newly created entry', function(done) {
            var req = withCommonProperties({
                    body: {foo: 'bar'}
                })
              , res = withJsonFormatter({
                    send: function(e) {
                        assert.equal(baseurl + '/7', e);
                    }
                });

            router.create(req, res, done);
        });
    });

    describe('#read(req,res,next)', function() {
        it('should respond with the entry specified by id', function(done) {
            var req = withCommonProperties({
                    params: {id: 5}
                })
              , res = withJsonFormatter({
                    send: function(e) {
                        assert.deepEqual({id: 5, name: 'foo'}, e);
                    }
                });

            router.read(req, res, done);
        });
    });

    describe('#update(req,res,next)', function() {
        it('should respond with the url of the updated entry', function(done) {
            var req = withCommonProperties({
                    body: {goo: 'gle'},
                    params: {id: 5}
                })
              , res = withJsonFormatter({
                    send: function(e) {
                        assert.equal(baseurl + '/5', e);
                    }
                });

            router.update(req, res, done);
        });
    });
});<commit_msg>added .json methods to res mocks<commit_after>'use strict';

var assert = require('assert')
  , _ = require('lodash')
  , resource = 'test'
  , baseurl = '/api/v1/' + resource
  , model = 'name'
  , resources = [{id:1,name:'foo'}, {id:2,name:'bar'}, {id:3,name:'baz'}]
  , mock = {
        findAll: function(shouldIncludeDocs, next) {
            if (shouldIncludeDocs) {
                next(null, resources);
            } else {
                next(null, _.pluck(resources, 'id'));
            }
        },
        findById: function(id, next) {
            next(null, _.filter(resources, function(r) { return r.id === id; })[0] || {id: id, name: 'foo'});
        },
        filter: function(shouldIncludeDocs, filters, next) {
            var filtered = _.filter(resources, function(r) { return _.every(filters, function(f) { return r[f.property] == f.filter; }); });
            next(null, (shouldIncludeDocs) ? filtered : _.map(filtered, function(f) { return f.id; }));
        },
        save: function(data, next) {
            next(null, data.id || 7);
        }
    }
  , router = require('../src/router')(mock, { view: resource, fields: model });

function withJsonFormatter(res) {
    return _.extend(res, { format: function(e) { e.json(); } });
}

function withCommonProperties(req) {
    return _.extend(req, {
        baseUrl: baseurl,
        get: function() { return 'application/json'; }
    });
}

function resourceToUrl(resource) {
    return baseurl + '/' + resource.id;
}

describe('router', function() {
    describe('#error(res,err,next)', function() {
        it('should respond with a "500 internal server error" on errors', function(done) {
            var err = 'this is an error' // creating an error here would make mocha fail
              , res = withJsonFormatter({
                    status: function(code) {
                        assert.equal(500, code);
                        return res;
                    },
                    json: function(e) {
                        assert.equal(err, e);
                        return res;
                    }
                });

            router.error(res, err, function() {
                // mocha would fail when done being called with error
                // => make sure it is called without parameters
                done();
            });
        });
    });

    describe('#list(req,res,next)', function() {
        it('should respond with a list of urls relative to /', function(done) {
            var req = withCommonProperties({})
              , res = withJsonFormatter({
                    json: function(e) {
                        assert.deepEqual(_.map(resources, resourceToUrl), e);
                    }
                });

            router.list(req, res, done);
        });

        it('should respond with a list of docs when ?include_docs is set', function(done) {
            var req = withCommonProperties({
                    query: {include_docs: true}
                })
              , res = withJsonFormatter({
                    json: function(e) {
                        assert.deepEqual(resources, e);
                    }
                });

            router.list(req, res, done);
        });

        it('should respond with a exact-match filtered list when ?<field>=<filter> is set', function(done) {
            var req = withCommonProperties({
                    query: {name: 'foo'}
                })
              , res = withJsonFormatter({
                    json: function(e) {
                        assert.deepEqual(_.chain(resources)
                                         .filter(function(r) { return r.name === 'foo'; })
                                         .map(resourceToUrl)
                                         .value(), e);
                    }
                });

            router.list(req, res, done);
        });
    });

    describe('#create(req,res,next)', function() {
        it('should respond with the url of the newly created entry', function(done) {
            var req = withCommonProperties({
                    body: {foo: 'bar'}
                })
              , res = withJsonFormatter({
                    json: function(e) {
                        assert.equal(baseurl + '/7', e);
                    }
                });

            router.create(req, res, done);
        });
    });

    describe('#read(req,res,next)', function() {
        it('should respond with the entry specified by id', function(done) {
            var req = withCommonProperties({
                    params: {id: 5}
                })
              , res = withJsonFormatter({
                    json: function(e) {
                        assert.deepEqual({id: 5, name: 'foo'}, e);
                    }
                });

            router.read(req, res, done);
        });
    });

    describe('#update(req,res,next)', function() {
        it('should respond with the url of the updated entry', function(done) {
            var req = withCommonProperties({
                    body: {goo: 'gle'},
                    params: {id: 5}
                })
              , res = withJsonFormatter({
                    json: function(e) {
                        assert.equal(baseurl + '/5', e);
                    }
                });

            router.update(req, res, done);
        });
    });
});<|endoftext|>


<commit_before>/* global jake:true, desc:true, task:true, complete:true, require:true, console:true, process:true */
/* jshint unused:false */
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;

var tools = require('./src/moxie/build/tools');
var utils = require('./src/moxie/build/utils');
var wiki = require('./src/moxie/build/wiki');

var copyright = [
	"/**",
	" * Plupload - multi-runtime File Uploader",
	" * v@@version@@",
	" *",
	" * Copyright 2013, Moxiecode Systems AB",
	" * Released under GPL License.",
	" *",
	" * License: http://www.plupload.com/license",
	" * Contributing: http://www.plupload.com/contributing",
	" *",
	" * Date: @@releasedate@@",
	" */"
].join("\n");

desc("Default build task");
task("default", ["moxie", "mkjs", "docs"], function (params) {});

desc("Build release package");
task("release", ["default", "package"], function (params) {});

desc("Build mOxie");
task("moxie", [], function (params) {
	var moxieDir = "./src/moxie";
	var currentDir = process.cwd();

	process.chdir(moxieDir);
	exec("jake", function(error, stdout, stderr) {
		if (error) {
			console.info(error);
		}
		process.chdir(currentDir);
		complete();
	});
}, true);

desc("Minify JS files");
task("mkjs", [], function (params) {
	var Instrument = require('coverjs').Instrument;
	var uglify = tools.uglify;

	var targetDir = "./js", moxieDir = "src/moxie";

	// Clear previous versions
	if (fs.existsSync(targetDir)) {
		jake.rmRf(targetDir);
	}
	fs.mkdirSync(targetDir, 0755);

	// Include Plupload source
	tools.copySync('./src/plupload.js', "js/plupload.dev.js");

	// Instrument Plupload code
	fs.writeFileSync(targetDir + '/plupload.cov.js', new Instrument(fs.readFileSync('./src/plupload.js').toString(), {
		name: 'Plupload'
	}).instrument());

	// Copy compiled moxie files
	tools.copySync(moxieDir + "/bin/flash/Moxie.swf", "js/Moxie.swf");
	tools.copySync(moxieDir + "/bin/silverlight/Moxie.xap", "js/Moxie.xap");
	tools.copySync(moxieDir + "/bin/js/moxie.min.js", "js/moxie.min.js");
	tools.copySync(moxieDir + "/bin/js/moxie.js", "js/moxie.js");

	// Copy UI Plupload
	jake.cpR("./src/jquery.ui.plupload", targetDir + "/jquery.ui.plupload", {});

	uglify([
		'jquery.ui.plupload.js'
	], targetDir + "/jquery.ui.plupload/jquery.ui.plupload.min.js", {
		sourceBase: targetDir + "/jquery.ui.plupload/"
	});

	// Copy Queue Plupload
	jake.cpR("./src/jquery.plupload.queue", targetDir + "/jquery.plupload.queue", {});

	uglify([
		'jquery.plupload.queue.js'
	], targetDir + "/jquery.plupload.queue/jquery.plupload.queue.min.js", {
		sourceBase: targetDir + "/jquery.plupload.queue/"
	});

	// Minify Plupload and combine with mOxie
	uglify([
		'plupload.js'
	], targetDir + "/plupload.min.js", {
		sourceBase: 'src/'
	});

	var info = require("./package.json");
	info.copyright = copyright;
	tools.addReleaseDetailsTo(targetDir + "/plupload.dev.js", info);
	tools.addReleaseDetailsTo(targetDir + "/plupload.min.js", info);

	var code = "";
	code += fs.readFileSync(targetDir + "/moxie.min.js") + "\n";
	code += fs.readFileSync(targetDir + "/plupload.min.js");

	fs.writeFileSync(targetDir + "/plupload.full.min.js", code);

	// Add I18n files
	process.env.auth = "moxieuser:12345";
	process.env.to = "./js/i18n";
	jake.Task['i18n'].invoke();
});

desc("Language tools");
task("i18n", [], function(params) {
	var i18n = require('./build/i18n');

	switch (params) {
		case 'extract':
			var from = process.env.from || ['./src/plupload.js', './src/jquery.ui.plupload/jquery.ui.plupload.js', './src/jquery.plupload.queue/jquery.plupload.queue.js'];
			var to = process.env.to || './tmp/en.po';
			i18n.extract(from, to);
			break;

		case 'toPO':
			// srcLang is required here, e.g.: jake i18n[toPO] srcLang=tmp/en.pot from=js/i18n/*.js
			var from = process.env.from;
			var to = process.env.to || './tmp/i18n';
			i18n.toPot(from, to);
			break;

		case 'pull':
		default:
			var auth = (process.env.auth || "moxieuser:12345").split(':');
			var to = process.env.to || './tmp/i18n';
			i18n.pull(utils.format("https://%s:%s@www.transifex.com/api/2/project/plupload/resource/core/", auth[0], auth[1]), to, complete);
			return;
	}

	complete(); // call complete manually
}, true);

desc("Generate documentation using YUIDoc");
task("docs", [], function (params) {
	var yuidoc = tools.yuidoc;
	yuidoc(["src", "src/jquery.plupload.queue", "src/jquery.ui.plupload"], "docs", {
		norecurse: true
	});
}, true);

desc("Generate wiki pages");
task("wiki", ["docs"], function() {
	wiki("git@github.com:moxiecode/plupload.wiki.git", "wiki", "docs");
});

desc("Runs JSHint on source files");
task("jshint", [], function (params) {
	var jshint = tools.jshint;
	jshint("src", {
		curly: true
	});
});

desc("Package library");
task("package", [], function (params) {
	var zip = tools.zip;
	var info = require("./package.json");

	var tmpDir = "./tmp";
	if (fs.existsSync(tmpDir)) {
		jake.rmRf(tmpDir);
	}
	fs.mkdirSync(tmpDir, 0755);

	var suffix = info.version.replace(/\./g, '_');
	if (/(?:beta|alpha)/.test(suffix)) {
		var dateFormat = require('dateformat');
		// If some public test build, append build number
		suffix += "." + dateFormat(new Date(), "yymmddHHMM", true);
	}

	zip([
		"js/**/*",
		"examples/**/*",
		"README.md",
		"LICENSE.txt"
	], path.join(tmpDir, utils.format("plupload_%s.zip", suffix)), complete);
}, true);

<commit_msg>Build: Do not fetch i18n files unless explicitly requested.<commit_after>/* global jake:true, desc:true, task:true, complete:true, require:true, console:true, process:true */
/* jshint unused:false */
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;

var tools = require('./src/moxie/build/tools');
var utils = require('./src/moxie/build/utils');
var wiki = require('./src/moxie/build/wiki');

var copyright = [
	"/**",
	" * Plupload - multi-runtime File Uploader",
	" * v@@version@@",
	" *",
	" * Copyright 2013, Moxiecode Systems AB",
	" * Released under GPL License.",
	" *",
	" * License: http://www.plupload.com/license",
	" * Contributing: http://www.plupload.com/contributing",
	" *",
	" * Date: @@releasedate@@",
	" */"
].join("\n");

desc("Default build task");
task("default", ["moxie", "mkjs", "docs"], function (params) {});

desc("Build release package");
task("release", ["default", "package"], function (params) {});

desc("Build mOxie");
task("moxie", [], function (params) {
	var moxieDir = "./src/moxie";
	var currentDir = process.cwd();

	process.chdir(moxieDir);
	exec("jake", function(error, stdout, stderr) {
		if (error) {
			console.info(error);
		}
		process.chdir(currentDir);
		complete();
	});
}, true);

desc("Minify JS files");
task("mkjs", [], function (i18n) {
	var Instrument = require('coverjs').Instrument;
	var uglify = tools.uglify;

	var targetDir = "./js", moxieDir = "src/moxie";

	// Clear previous versions
	if (fs.existsSync(targetDir)) {
		jake.rmRf(targetDir);
	}
	fs.mkdirSync(targetDir, 0755);

	// Include Plupload source
	tools.copySync('./src/plupload.js', "js/plupload.dev.js");

	// Instrument Plupload code
	fs.writeFileSync(targetDir + '/plupload.cov.js', new Instrument(fs.readFileSync('./src/plupload.js').toString(), {
		name: 'Plupload'
	}).instrument());

	// Copy compiled moxie files
	tools.copySync(moxieDir + "/bin/flash/Moxie.swf", "js/Moxie.swf");
	tools.copySync(moxieDir + "/bin/silverlight/Moxie.xap", "js/Moxie.xap");
	tools.copySync(moxieDir + "/bin/js/moxie.min.js", "js/moxie.min.js");
	tools.copySync(moxieDir + "/bin/js/moxie.js", "js/moxie.js");

	// Copy UI Plupload
	jake.cpR("./src/jquery.ui.plupload", targetDir + "/jquery.ui.plupload", {});

	uglify([
		'jquery.ui.plupload.js'
	], targetDir + "/jquery.ui.plupload/jquery.ui.plupload.min.js", {
		sourceBase: targetDir + "/jquery.ui.plupload/"
	});

	// Copy Queue Plupload
	jake.cpR("./src/jquery.plupload.queue", targetDir + "/jquery.plupload.queue", {});

	uglify([
		'jquery.plupload.queue.js'
	], targetDir + "/jquery.plupload.queue/jquery.plupload.queue.min.js", {
		sourceBase: targetDir + "/jquery.plupload.queue/"
	});

	// Minify Plupload and combine with mOxie
	uglify([
		'plupload.js'
	], targetDir + "/plupload.min.js", {
		sourceBase: 'src/'
	});

	var info = require("./package.json");
	info.copyright = copyright;
	tools.addReleaseDetailsTo(targetDir + "/plupload.dev.js", info);
	tools.addReleaseDetailsTo(targetDir + "/plupload.min.js", info);

	var code = "";
	code += fs.readFileSync(targetDir + "/moxie.min.js") + "\n";
	code += fs.readFileSync(targetDir + "/plupload.min.js");

	fs.writeFileSync(targetDir + "/plupload.full.min.js", code);

	// Add I18n files
	if (i18n) {
		process.env.auth = "moxieuser:12345";
		process.env.to = "./js/i18n";
		jake.Task['i18n'].invoke();
	}
});

desc("Language tools");
task("i18n", [], function(params) {
	var i18n = require('./build/i18n');

	switch (params) {
		case 'extract':
			var from = process.env.from || ['./src/plupload.js', './src/jquery.ui.plupload/jquery.ui.plupload.js', './src/jquery.plupload.queue/jquery.plupload.queue.js'];
			var to = process.env.to || './tmp/en.po';
			i18n.extract(from, to);
			break;

		case 'toPO':
			// srcLang is required here, e.g.: jake i18n[toPO] srcLang=tmp/en.pot from=js/i18n/*.js
			var from = process.env.from;
			var to = process.env.to || './tmp/i18n';
			i18n.toPot(from, to);
			break;

		case 'pull':
		default:
			var auth = (process.env.auth || "moxieuser:12345").split(':');
			var to = process.env.to || './tmp/i18n';
			i18n.pull(utils.format("https://%s:%s@www.transifex.com/api/2/project/plupload/resource/core/", auth[0], auth[1]), to, complete);
			return;
	}

	complete(); // call complete manually
}, true);

desc("Generate documentation using YUIDoc");
task("docs", [], function (params) {
	var yuidoc = tools.yuidoc;
	yuidoc(["src", "src/jquery.plupload.queue", "src/jquery.ui.plupload"], "docs", {
		norecurse: true
	});
}, true);

desc("Generate wiki pages");
task("wiki", ["docs"], function() {
	wiki("git@github.com:moxiecode/plupload.wiki.git", "wiki", "docs");
});

desc("Runs JSHint on source files");
task("jshint", [], function (params) {
	var jshint = tools.jshint;
	jshint("src", {
		curly: true
	});
});

desc("Package library");
task("package", [], function (params) {
	var zip = tools.zip;
	var info = require("./package.json");

	var tmpDir = "./tmp";
	if (fs.existsSync(tmpDir)) {
		jake.rmRf(tmpDir);
	}
	fs.mkdirSync(tmpDir, 0755);

	var suffix = info.version.replace(/\./g, '_');
	if (/(?:beta|alpha)/.test(suffix)) {
		var dateFormat = require('dateformat');
		// If some public test build, append build number
		suffix += "." + dateFormat(new Date(), "yymmddHHMM", true);
	}

	zip([
		"js/**/*",
		"examples/**/*",
		"README.md",
		"LICENSE.txt"
	], path.join(tmpDir, utils.format("plupload_%s.zip", suffix)), complete);
}, true);

<|endoftext|>