<commit_before>(function () {

    // core modules
    var path = require('path');

    // dep modules
    // var fs = require('fs-extra');

    // own modules
    var Docma = require('../../index');

    function getNavItems(routing) {
        function route(name, type) {
            name = name || '';
            type = type || 'content';
            if (routing === 'path') {
                if (type === 'api') return './api' + (name ? '/' + name : '');
                return './' + name;
            }
            return './?' + type + (name ? '=' + name : '');
        }
        return [
            {
                iconClass: 'ico-mouse-pointer',
                label: 'Guide',
                items: [
                    { label: 'Home', href: './' },
                    { label: 'Guide', href: route('guide') },
                    // { label: 'Building Documentation', href: './' },
                    // { label: 'Build Configuration', href: './' },
                    { separator: true },
                    { label: 'Docma Default Template', href: route('default-template') },
                    { separator: true },
                    { label: 'Creating Docma Templates', href: route('templates') },
                    { label: 'Docma Web Core', href: route('docma-web') },
                    { label: 'Docma Filters', href: route('docma-filters') },
                    { separator: true },
                    { label: 'HTML Page', href: route('page') },
                    { label: 'iFrame Page', href: route('iframe') }
                ]
            },
            {
                iconClass: 'ico-book',
                label: 'API Reference',
                items: [
                    { label: 'Docma (Builder) API', href: route('docma', 'api') },
                    { label: 'Docma (Web) API', href: route('docma-web', 'api') },
                    { label: 'Docma Web Utils', href: route('docma-web-utils', 'api') },
                    { label: 'Test (src)', href: route('src', 'api') },
                    { separator: true },
                    { label: 'Test (re)', href: route('re', 'api') },
                    { separator: true },
                    { label: 'API Not Found', href: route('foo', 'api') },
                    { separator: true },
                    { label: 'Default', href: route('', 'api') },
                    { label: '_def_', href: route('_def_', 'api') }
                ]
            },
            {
                iconClass: 'ico-md ico-download',
                label: 'Download',
                items: [
                    { label: 'Change Log', href: route('changelog') },
                    { label: 'Markdown Test', href: route('md-test') },
                    { separator: true },
                    { label: 'index.html', href: 'index.html' }, // or ./index.html
                    { separator: true },
                    { label: 'Content Not Found', href: route('bar') }
                ]
            },
            {
                iconClass: 'ico-md ico-github',
                label: 'GitHub',
                href: 'https://github.com/onury/docma',
                target: '_blank'
            }
        ];
    }

    describe('build', function () {
        var config = {
            debug: 16,
            jsdoc: {
                encoding: 'utf8',
                recurse: false,
                pedantic: false,
                access: ['public', 'protected'], // null, // ['private'],
                package: null,
                module: true,
                undocumented: false,
                undescribed: false,
                hierarchy: true,
                sort: true, // "grouped",
                relativePath: path.join(__dirname, '/code'),
                filter: null
            },
            // markdown options
            markdown: {
                gfm: true,
                tables: true,
                breaks: false,
                pedantic: false,
                sanitize: false,
                smartLists: true,
                smartypants: false,
                tasks: true,
                emoji: true
            },
            app: {
                title: 'Docma Documentation',
                meta: null,
                base: '/javascript/docma/test/output', // overwritten in specs
                entrance: 'content:guide',
                routing: 'path', // overwritten in specs
                server: 'apache' // overwritten in specs
            },
            template: {
                path: 'default',
                options: {
                    title: 'Docma',
                    sidebar: true,
                    collapsed: false,
                    badges: true,
                    search: true,
                    navbar: true,
                    navItems: []
                }
            },
            src: [
                './test/input/md-test.md',
                // './test/input/**/*.js',
                './test/input/code.js',
                {
                    'docma': './lib/docma.js',
                    'docma-web': [
                        './lib/web/core.js',
                        './lib/web/core.*.js',
                        '!./lib/web/core.utils.js'
                    ],
                    'docma-web-utils': './lib/web/core.utils.js'
                },
                {
                    'src': [
                        './test/input/private/core/*.js',
                        './test/input/src/lib/*.js'
                    ],
                    'priv': './test/input/private/*.js',
                    're': './test/input/private/re.js'
                },
                './doc/**/*.md',
                { 'guide': './README.md' }, // renamed markdown
                './CHANGELOG.md',
                {
                    'page': './test/input/html-test.html',
                    'iframe': './test/input/iframe-test.html'
                }
            ],
            dest: './test/output' // overwritten in specs
        };

        // beforeAll(function () {});

        it('should build with query-routing', function (done) {
            config.app.routing = 'query';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/query-routing';
            config.app.base = '/'; // '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        it('should build with path-routing (for GitHub)', function (done) {
            config.app.routing = 'path';
            config.app.server = 'github';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/path-routing';
            config.app.base = '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        xit('should build docma documentation', function (done) {
            Docma.create()
                .build('./docma.config.json')
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

    });

})();
<commit_msg>update test<commit_after>(function () {

    // core modules
    var path = require('path');

    // dep modules
    // var fs = require('fs-extra');

    // own modules
    var Docma = require('../../index');

    function getNavItems(routing) {
        function route(name, type) {
            name = name || '';
            type = type || 'content';
            if (routing === 'path') {
                if (type === 'api') return './api' + (name ? '/' + name : '');
                return './' + name;
            }
            return './?' + type + (name ? '=' + name : '');
        }
        return [
            {
                iconClass: 'ico-mouse-pointer',
                label: 'Guide',
                items: [
                    { label: 'Home', href: './' },
                    { label: 'Guide', href: route('guide') },
                    // { label: 'Building Documentation', href: './' },
                    // { label: 'Build Configuration', href: './' },
                    { separator: true },
                    { label: 'Docma Default Template', href: route('default-template') },
                    { separator: true },
                    { label: 'Creating Docma Templates', href: route('templates') },
                    { label: 'Docma Web Core', href: route('docma-web') },
                    { label: 'Docma Filters', href: route('docma-filters') },
                    { separator: true },
                    { label: 'HTML Page', href: route('page') },
                    { label: 'iFrame Page', href: route('iframe') }
                ]
            },
            {
                iconClass: 'ico-book',
                label: 'API Reference',
                items: [
                    { label: 'Docma (Builder) API', href: route('docma', 'api') },
                    { label: 'Docma (Web) API', href: route('docma-web', 'api') },
                    { label: 'Docma Web Utils', href: route('docma-web-utils', 'api') },
                    { label: 'Test (src)', href: route('src', 'api') },
                    { separator: true },
                    { label: 'Test (re)', href: route('re', 'api') },
                    { separator: true },
                    { label: 'API Not Found', href: route('foo', 'api') },
                    { separator: true },
                    { label: 'Default', href: route('', 'api') },
                    { label: '_def_', href: route('_def_', 'api') }
                ]
            },
            {
                iconClass: 'ico-md ico-download',
                label: 'Download',
                items: [
                    { label: 'Change Log', href: route('changelog') },
                    { label: 'Markdown Test', href: route('md-test') },
                    { separator: true },
                    { label: 'index.html', href: 'index.html' }, // or ./index.html
                    { separator: true },
                    { label: 'Content Not Found', href: route('bar') }
                ]
            },
            {
                iconClass: 'ico-md ico-github',
                label: 'GitHub',
                href: 'https://github.com/onury/docma',
                target: '_blank'
            }
        ];
    }

    describe('build', function () {
        var config = {
            debug: 16,
            jsdoc: {
                encoding: 'utf8',
                recurse: false,
                pedantic: false,
                access: ['public', 'protected'], // null, // ['private'],
                package: null,
                module: true,
                undocumented: false,
                undescribed: false,
                hierarchy: true,
                sort: true, // "grouped",
                relativePath: path.join(__dirname, '/code'),
                filter: null,
                allowUnknownTags: true,
                dictionaries: ['jsdoc', 'closure'],
                includePattern: '.+\\.js(doc|x)?$',
                excludePattern: '(^|\\/|\\\\)_',
                plugins: []
            },
            // markdown options
            markdown: {
                gfm: true,
                tables: true,
                breaks: false,
                pedantic: false,
                sanitize: false,
                smartLists: true,
                smartypants: false,
                tasks: true,
                emoji: true
            },
            app: {
                title: 'Docma Documentation',
                meta: null,
                base: '/javascript/docma/test/output', // overwritten in specs
                entrance: 'content:guide',
                routing: 'path', // overwritten in specs
                server: 'apache' // overwritten in specs
            },
            template: {
                path: 'default',
                options: {
                    title: 'Docma',
                    sidebar: true,
                    collapsed: false,
                    badges: true,
                    search: true,
                    navbar: true,
                    navItems: []
                }
            },
            src: [
                './test/input/md-test.md',
                // './test/input/**/*.js',
                './test/input/code.js',
                {
                    'docma': './lib/docma.js',
                    'docma-web': [
                        './lib/web/core.js',
                        './lib/web/core.*.js',
                        '!./lib/web/core.utils.js'
                    ],
                    'docma-web-utils': './lib/web/core.utils.js'
                },
                {
                    'src': [
                        './test/input/private/core/*.js',
                        './test/input/src/lib/*.js'
                    ],
                    'priv': './test/input/private/*.js',
                    're': './test/input/private/re.js'
                },
                './doc/**/*.md',
                { 'guide': './README.md' }, // renamed markdown
                './CHANGELOG.md',
                {
                    'page': './test/input/html-test.html',
                    'iframe': './test/input/iframe-test.html'
                }
            ],
            dest: './test/output' // overwritten in specs
        };

        // beforeAll(function () {});

        it('should build with query-routing', function (done) {
            config.app.routing = 'query';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/query-routing';
            config.app.base = '/'; // '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        it('should build with path-routing (for GitHub)', function (done) {
            config.app.routing = 'path';
            config.app.server = 'github';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/path-routing';
            config.app.base = '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        xit('should build docma documentation', function (done) {
            Docma.create()
                .build('./docma.config.json')
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

    });

})();
<|endoftext|>


<commit_before>'use strict';

var Framework = require('../../Framework');
var Fs = require('fs');
var Vow = require('vow');

var asker = require('asker');
var sock = require('../stuff/conf/sock');

module.exports = {

    ready: [
        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
            });

            fist.ready();

            test.deepEqual(spy, [0, 1]);

            test.done();
        },

        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
                test.deepEqual(spy, [0, 1]);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.ready();
            fist.ready();

            setTimeout(function () {
                test.done();
            }, 100);
        },

        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, null);
                }, 10);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
                test.deepEqual(spy, [0, 1]);
                test.done();
            });

            fist.ready();
        },

        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done();
                }, 10);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
                test.deepEqual(spy, [0, 1]);
                test.done();
            });

            fist.ready();
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(1);
                    done(null, null);
                }, 10);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(3);
                test.deepEqual(spy, [0, 1, 2, 3]);
                test.done();
            });

            fist.ready();

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(2);
                    done(null, null);
                }, 15);
            });

            fist.ready();
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                done(42);
            });

            fist.plug(function (done) {
                done(43);
            });

            fist.on('sys:ready', function () {
                spy.push(100500);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:error', function (err) {
                spy.push(1);
                test.strictEqual(err, 42);
                test.deepEqual(spy, [0, 1]);
            });

            fist.ready();
            fist.ready();

            setTimeout(function () {
                test.done();
            }, 0);
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.plug(function (done) {
                done(null, 42);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(42);
                }, 0);
            });

            fist.plug(function (done) {
                done(null, 42);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:error', function (err) {
                spy.push(1);
                test.strictEqual(err, 42);
                test.deepEqual(spy, [0, 1]);
                //  разрешаю ошибку и делаю sys:ready

                fist.on('sys:ready', function () {
                    spy.push(100500);
                    test.deepEqual(spy, [0, 1, 100500]);

//                    test.strictEqual(fist._state, 0);
//                    test.strictEqual(fist._pending, 0);
                });

                setTimeout(function () {
                    fist.emit('sys:ready');
                }, 0);
            });

            fist.ready();

            setTimeout(function () {
                test.done();
            }, 100);
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done(42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(43);
                }, 50);
            });

            fist.on('sys:ready', function () {
                spy.push(100500);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:error', function (err) {
                spy.push(1);
                test.strictEqual(err, 42);
                test.deepEqual(spy, [0, 1]);
            });

            fist.ready();

            setTimeout(function () {
                test.done();
            }, 100);
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(1);
                    done(null, 42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(2);
                    done(null, 43);
                }, 50);
            });

            fist.on('sys:ready', function () {
                spy.push(100500);
                test.deepEqual(spy, [0, 1, 2, 100500]);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.ready();

            setTimeout(function () {
                test.done();
            }, 100);
        }
    ],

    _call: [
        function (test) {

            var fist = new Framework();

            fist.decl('index', function (connect, errors, result, done) {
                done(null, 42);
            });

            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function (err, res) {
                test.deepEqual(res.data, new Buffer('42'));
                test.done();
            });
        },

        function (test) {

            var fist = new Framework();

            fist.decl('index', Vow.resolve(42));
            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function (err, res) {
                test.deepEqual(res.data, new Buffer('42'));
                test.done();
            });
        }
    ],

    _handle: [
        function (test) {

            var fist = new Framework();

            var d = new Date();

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, null);
                }, 100);
            });

            fist.decl('index', {});

            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function (err, res) {
                test.ok(d.getTime() <= Date.now());
                test.deepEqual(res.data, new Buffer('{}'));
                test.done();
            });

        },

        function (test) {

            var fist = new Framework();

            fist.decl('index', 42);
            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.plug(function (done) {
                done(42);
            });

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function () {});

            setTimeout(function () {
                test.done();
            }, 50);
        }
    ]
};
<commit_msg>rc-dev: сделал более честным тест с разрешением критической ошибки<commit_after>'use strict';

var Framework = require('../../Framework');
var Fs = require('fs');
var Vow = require('vow');

var asker = require('asker');
var sock = require('../stuff/conf/sock');

module.exports = {

    ready: [
        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
            });

            fist.ready();

            test.deepEqual(spy, [0, 1]);

            test.done();
        },

        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
                test.deepEqual(spy, [0, 1]);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.ready();
            fist.ready();

            setTimeout(function () {
                test.done();
            }, 100);
        },

        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, null);
                }, 10);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
                test.deepEqual(spy, [0, 1]);
                test.done();
            });

            fist.ready();
        },

        function (test) {
            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done();
                }, 10);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(1);
                test.deepEqual(spy, [0, 1]);
                test.done();
            });

            fist.ready();
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(1);
                    done(null, null);
                }, 10);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:ready', function () {
                spy.push(3);
                test.deepEqual(spy, [0, 1, 2, 3]);
                test.done();
            });

            fist.ready();

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(2);
                    done(null, null);
                }, 15);
            });

            fist.ready();
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                done(42);
            });

            fist.plug(function (done) {
                done(43);
            });

            fist.on('sys:ready', function () {
                spy.push(100500);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:error', function (err) {
                spy.push(1);
                test.strictEqual(err, 42);
                test.deepEqual(spy, [0, 1]);
            });

            fist.ready();
            fist.ready();

            setTimeout(function () {
                test.done();
            }, 0);
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.plug(function (done) {
                done(null, 42);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(42);
                }, 0);
            });

            fist.plug(function (done) {
                done(null, 42);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, 42);
                }, 0);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:error', function (err) {
                spy.push(1);
                test.strictEqual(err, 42);
                test.deepEqual(spy, [0, 1]);
                //  разрешаю ошибку и делаю sys:ready

                fist.on('sys:ready', function () {
                    spy.push(100500);
                    test.deepEqual(spy, [0, 1, 100500]);

//                    test.strictEqual(fist._state, 0);
//                    test.strictEqual(fist._pending, 0);
                });

                setTimeout(function () {
                    fist.emit('sys:ready');
                }, 0);
            });

            try {
                Fs.unlinkSync(sock);
            } catch (err) {}

            fist.decl('index', 42);
            fist.route('GET', '/', 'index');
            fist.listen(sock);

            asker({
                method: 'GET',
                socketPath: sock,
                path: '/'
            }, function (err, res) {
                test.deepEqual(res.data, new Buffer('42'));
                test.done();
            });
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    done(42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    done(43);
                }, 50);
            });

            fist.on('sys:ready', function () {
                spy.push(100500);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.on('sys:error', function (err) {
                spy.push(1);
                test.strictEqual(err, 42);
                test.deepEqual(spy, [0, 1]);
            });

            fist.ready();

            setTimeout(function () {
                test.done();
            }, 100);
        },

        function (test) {

            var fist = new Framework();
            var spy = [];

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(1);
                    done(null, 42);
                }, 0);
            });

            fist.plug(function (done) {
                setTimeout(function () {
                    spy.push(2);
                    done(null, 43);
                }, 50);
            });

            fist.on('sys:ready', function () {
                spy.push(100500);
                test.deepEqual(spy, [0, 1, 2, 100500]);
            });

            fist.on('sys:pending', function () {
                spy.push(0);
            });

            fist.ready();

            setTimeout(function () {
                test.done();
            }, 100);
        }
    ],

    _call: [
        function (test) {

            var fist = new Framework();

            fist.decl('index', function (connect, errors, result, done) {
                done(null, 42);
            });

            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function (err, res) {
                test.deepEqual(res.data, new Buffer('42'));
                test.done();
            });
        },

        function (test) {

            var fist = new Framework();

            fist.decl('index', Vow.resolve(42));
            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function (err, res) {
                test.deepEqual(res.data, new Buffer('42'));
                test.done();
            });
        }
    ],

    _handle: [
        function (test) {

            var fist = new Framework();

            var d = new Date();

            fist.plug(function (done) {
                setTimeout(function () {
                    done(null, null);
                }, 100);
            });

            fist.decl('index', {});

            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function (err, res) {
                test.ok(d.getTime() <= Date.now());
                test.deepEqual(res.data, new Buffer('{}'));
                test.done();
            });

        },

        function (test) {

            var fist = new Framework();

            fist.decl('index', 42);
            fist.route('GET', '/', 'index');

            try {
                Fs.unlinkSync(sock);
            } catch (ex) {}

            fist.plug(function (done) {
                done(42);
            });

            fist.listen(sock);

            asker({
                method: 'GET',
                path: '/',
                socketPath: sock
            }, function () {});

            setTimeout(function () {
                test.done();
            }, 50);
        }
    ]
};
<|endoftext|>


<commit_before>import chai from 'chai';
import { describe, it, afterEach } from 'mocha';
import innerDriverCore from '../dist/lib/driver-core';

const should = chai.should();
let driverCore = null;

describe('driver-core :', () => {
  afterEach(() => {
    driverCore = null;
  });

  describe('returns expected configured driver library', () => {
    it('built driver core library is a webdriver chai runner', (done) => {
      driverCore = innerDriverCore();
      should.equal(
				driverCore.constructor.name,
				'thenableWebDriverProxy',
				'library should be a thenableWebDriverProxy function'
            );
      should.equal(
				driverCore.framework,
				'chromedriver',
				'library should be configured for chromedriver'
            );
      driverCore.quit();
      done();
    });
  });

describe('framework is object with useBrowser framework prop is used', () => {
    it ('triggers the local browser on passing useBrowser attributes for chrome', (done) => {
      driverCore = innerDriverCore({
        useBrowser: true,
        capabilities: {
          browserName: 'chrome',
          resolution: '1024x768',
          args: [
            '--headless',
            '--foo',
            '--bar'
          ]
        }
      });
      should.equal(
  			driverCore.framework.useBrowser,
  			true,
  			'library should be configured for chrome browser'
          );
       done();
    })
    it ('triggers the local browser on passing useBrowser attributes for firefox', (done) => {
        driverCore = innerDriverCore({
          useBrowser: true,
          capabilities: {
            browserName: 'firefox',
            resolution: '1024x768',
            alwaysMatch: {
                'moz:firefoxOptions': {
                  args: [
                    '--headless',
                    '--foo',
                    '--bar'
                  ]
                }
              }
          }
        });
        should.equal(
                driverCore.framework.useBrowser,
                true,
                'library should be configured for chrome browser'
            );
        driverCore.quit();
        done();
      })
  })

});
<commit_msg>updated the test<commit_after>import chai from 'chai';
import { describe, it, afterEach } from 'mocha';
import innerDriverCore from '../dist/lib/driver-core';

const should = chai.should();
let driverCore = null;

describe('driver-core :', () => {
  afterEach(() => {
    driverCore = null;
  });

  describe('returns expected configured driver library', () => {
    it('validate the driver core constructor name', (done) => {
      driverCore = innerDriverCore({
        useBrowser: true,
        capabilities: {
          browserName: 'chrome',
          resolution: '1024x768',
          args: [
            '--headless',
            '--foo',
            '--bar'
          ]
        }
      });
      should.equal(
				driverCore.constructor.name,
				'thenableWebDriverProxy',
				'library should be a thenableWebDriverProxy function'
            );
      done();
    });
  });

describe('framework is object with useBrowser framework prop is used', () => {
    it ('triggers the local browser on passing useBrowser attributes for chrome', (done) => {
      driverCore = innerDriverCore({
        useBrowser: true,
        capabilities: {
          browserName: 'chrome',
          resolution: '1024x768',
          args: [
            '--headless',
            '--foo',
            '--bar'
          ]
        }
      });
      should.equal(
  			driverCore.framework.useBrowser,
  			true,
  			'library should be configured for chrome browser'
          );
       done();
    })
    it ('triggers the local browser on passing useBrowser attributes for firefox', (done) => {
        driverCore = innerDriverCore({
          useBrowser: true,
          capabilities: {
            browserName: 'firefox',
            resolution: '1024x768',
            alwaysMatch: {
                'moz:firefoxOptions': {
                  args: [
                    '--headless',
                    '--foo',
                    '--bar'
                  ]
                }
              }
          }
        });
        should.equal(
                driverCore.framework.useBrowser,
                true,
                'library should be configured for chrome browser'
            );
        driverCore.quit();
        done();
      })
  })

});
<|endoftext|>


<commit_before>/**
 * @copyright © 2015, Rick Wong. All rights reserved.
 */
var React = require("react");

var refCounter = 0;

/**
 * @module InlineCss
 */
var InlineCss = React.createClass({
	displayName: "InlineCss",
	propTypes: {
		componentName: React.PropTypes.string,
		namespace: React.PropTypes.string,
		stylesheet: React.PropTypes.string.isRequired,
		wrapper: React.PropTypes.string
	},
	_transformSheet: function (stylesheet, componentName, namespace) {
		return stylesheet.
			// Prettier output.
			replace(/}\s*/ig, '\n}\n').
			// Regular rules are namespaced.
			replace(
				/(^|{|}|;|,)\s*([&a-z0-9\-_\.:#\(\),>*\s]+)\s*(\{)/ig,
				function (matched) {
					return matched.replace(new RegExp(componentName, "g"), "#" + namespace);
				}
			);
	},
	render: function () {
		var componentName = this.props.componentName || "&";
		var namespace     = this.props.namespace || "InlineCss-" + refCounter++;
		var stylesheet    = this._transformSheet(this.props.stylesheet, componentName, namespace);
		var Wrapper       = this.props.wrapper || "div";

		return React.createElement(
			Wrapper,
			{id: namespace},
			this.props.children,
			React.createElement("style", {
				scoped:                  true,
				dangerouslySetInnerHTML: {__html: stylesheet}
			})
		);
	}
});

module.exports = InlineCss;
<commit_msg>Adds option to add className<commit_after>/**
 * @copyright © 2015, Rick Wong. All rights reserved.
 */
var React = require("react");

var refCounter = 0;

/**
 * @module InlineCss
 */
var InlineCss = React.createClass({
	displayName: "InlineCss",
	propTypes: {
		componentName: React.PropTypes.string,
		className: React.PropTypes.string,
		namespace: React.PropTypes.string,
		stylesheet: React.PropTypes.string.isRequired,
		wrapper: React.PropTypes.string
	},
	_transformSheet: function (stylesheet, componentName, namespace) {
		return stylesheet.
			// Prettier output.
			replace(/}\s*/ig, '\n}\n').
			// Regular rules are namespaced.
			replace(
				/(^|{|}|;|,)\s*([&a-z0-9\-_\.:#\(\),>*\s]+)\s*(\{)/ig,
				function (matched) {
					return matched.replace(new RegExp(componentName, "g"), "#" + namespace);
				}
			);
	},
	render: function () {
		var componentName = this.props.componentName || "&";
		var className = this.props.className;
		var namespace     = this.props.namespace || "InlineCss-" + refCounter++;
		var stylesheet    = this._transformSheet(this.props.stylesheet, componentName, namespace);
		var Wrapper       = this.props.wrapper || "div";

		return React.createElement(
			Wrapper,
			{id: namespace, className: className},
			this.props.children,
			React.createElement("style", {
				scoped:                  true,
				dangerouslySetInnerHTML: {__html: stylesheet}
			})
		);
	}
});

module.exports = InlineCss;
<|endoftext|>


<commit_before>var http = require('http');
var EventSource = require('eventsource');

var port = 20000;
function createServer(chunks, callback) {
    var responses = [];
    var server = http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/event-stream'});
        chunks.forEach(function(chunk) {
            res.write(chunk);
        });
        res.end();
        responses.push(res);
    });
    function close(closed) {
        responses.forEach(function(res) {
            res.end();
        });
        server.on('close', closed);
        server.close();
    }
    server.listen(port, function() {
        callback(close);
    });
};

exports['Messages'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'one one-line message in one chunk': function(test) {
        createServer(["data: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = function(m) {
                test.equal("Hello", m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'one one-line message in two chunks': function(test) {
        createServer(["data: Hel", "lo\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = function(m) {
                test.equal("Hello", m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'two one-line messages in one chunk': function(test) {
        createServer(["data: Hello\n\n", "data: World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Hello", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("World", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'one two-line message in one chunk': function(test) {
        createServer(["data: Hello\ndata:World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = function(m) {
                test.equal("Hello\nWorld", m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'really chopped up unicode data': function(test) {
        var chopped = "data: Aslak\n\ndata: Hellesøy\n\n".split("");
        createServer(chopped, function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Aslak", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("Hellesøy", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'accepts CRLF as separator': function(test) {
        var chopped = "data: Aslak\r\n\r\ndata: Hellesøy\r\n\r\n".split("");
        createServer(chopped, function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Aslak", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("Hellesøy", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'accepts CR as separator': function(test) {
        var chopped = "data: Aslak\r\rdata: Hellesøy\r\r".split("");
        createServer(chopped, function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Aslak", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("Hellesøy", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'delivers message with explicit event': function(test) {
        createServer(["event: greeting\ndata: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('greeting', function(m) {
                test.equal("Hello", m.data);
                es.close();
                close(test.done);
            });
        });
    },

    'comments are ignored': function(test) {
        createServer(["data: Hello\n\n:nothing to see here\n\ndata: World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Hello", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("World", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'empty comments are ignored': function(test) {
        createServer(["data: Hello\n\n:\n\ndata: World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Hello", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("World", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'empty data field causes entire event to be ignored': function(test) {
        createServer(["data:\n\ndata: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            var originalEmit = es.emit;
            es.emit = function(event) {
                test.ok(event === 'close' || event === 'message' || event === 'newListener');
                return originalEmit.apply(this, arguments);
            }
            es.onmessage = function(m) {
                test.equal('Hello', m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'empty event field causes entire event to be ignored': function(test) {
        createServer(["event:\n\ndata: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            var originalEmit = es.emit;
            es.emit = function(event) {
                test.ok(event === 'close' || event === 'message' || event === 'newListener');
                return originalEmit.apply(this, arguments);
            }
            es.onmessage = function(m) {
                test.equal('Hello', m.data);
                es.close();
                close(test.done);
            };
        });
    },
};

exports['Reconnect'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'when server is down': function(test) {
        var es = new EventSource('http://localhost:' + port);
        es.reconnectInterval = 0;
        var theClose = null;

        es.onerror = function(source) {
            es.onerror = null;
            createServer(["data: Hello\n\n"], function(close) {
                theClose = close;
            });
        };

        es.onmessage = function(m) {
            test.equal("Hello", m.data);
            es.close();
            theClose(test.done);
        };
    },

    'when server goes down after connection': function(test) {
        createServer(["data: Hello\n\n"], function(closeFirstServer) {
            var es = new EventSource('http://localhost:' + port);
            es.reconnectInterval = 0;

            es.onmessage = function(m) {
                test.equal("Hello", m.data);
                closeFirstServer(function() {
                    createServer(["data: World\n\n"], function(closeSecondServer) {
                        es.onmessage = second;

                        function second(m) {
                            test.equal("World", m.data);
                            es.close();
                            closeSecondServer(test.done);
                        }
                    });
                });
            };
        });
    }
};

exports['readyState'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'has CONNECTING constant': function(test) {
        test.equal(0, EventSource.CONNECTING);
        test.done();
    },

    'has OPEN constant': function(test) {
        test.equal(1, EventSource.OPEN);
        test.done();
    },

    'has CLOSED constant': function(test) {
        test.equal(2, EventSource.CLOSED);
        test.done();
    },

    'readyState is CONNECTING before connection has been established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            test.equal(EventSource.CONNECTING, es.readyState);
            es.onopen = function() {
                es.close();
                close(test.done);
            }
        });
    },

    'readyState is OPEN when connection has been established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                test.equal(EventSource.OPEN, es.readyState);
                es.close();
                close(test.done);
            }
        });
    },

    'readyState is CLOSED after connection has been closed': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                es.close();
            }
            es.onclose = function() {
                test.equal(EventSource.CLOSED, es.readyState);
                close(test.done);
            }
        });
    },
};

exports['Properties'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'url exposes original request url': function(test) {
        createServer([], function(close) {
            var url = 'http://localhost:' + port;
            var es = new EventSource(url);
            es.onopen = function() {
                test.equal(url, es.url);
                es.close();
                close(test.done);
            }
        });
    },
};

exports['Events'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'calls onopen when connection is established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                es.close();
                close(test.done);
            }
        });
    },

    'emits open event when connection is established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('open', function() {
                es.close();
                close(test.done);
            });
        });
    },

    'calls onclose when connection is closed': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                es.close();
            }
            es.onclose = function() {
                close(test.done);
            }
        });
    },

    'emits close event when connection is established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('open', function() {
                es.close();
            });
            es.addEventListener('close', function() {
                close(test.done);
            });
        });
    },

    'does not emit error when connection is closed by client': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('open', function() {
                es.close();
            });
            es.addEventListener('error', function() {
                throw new Error('error should not be emitted');
            });
            es.addEventListener('close', function() {
                close(test.done);
            });
        });
    },
};
<commit_msg>change test server's res.end to res.write to force response flush and correct behavior without payload<commit_after>var http = require('http');
var EventSource = require('eventsource');

var port = 20000;
function createServer(chunks, callback) {
    var responses = [];
    var server = http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/event-stream'});
        chunks.forEach(function(chunk) {
            res.write(chunk);
        });
        res.write(':'); // send a dummy comment to ensure that the response is flushed
        responses.push(res);
    });
    function close(closed) {
        responses.forEach(function(res) {
            res.end();
        });
        server.on('close', closed);
        server.close();
    }
    server.listen(port, function() {
        callback(close);
    });
};

exports['Messages'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'one one-line message in one chunk': function(test) {
        createServer(["data: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = function(m) {
                test.equal("Hello", m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'one one-line message in two chunks': function(test) {
        createServer(["data: Hel", "lo\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = function(m) {
                test.equal("Hello", m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'two one-line messages in one chunk': function(test) {
        createServer(["data: Hello\n\n", "data: World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Hello", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("World", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'one two-line message in one chunk': function(test) {
        createServer(["data: Hello\ndata:World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = function(m) {
                test.equal("Hello\nWorld", m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'really chopped up unicode data': function(test) {
        var chopped = "data: Aslak\n\ndata: Hellesøy\n\n".split("");
        createServer(chopped, function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Aslak", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("Hellesøy", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'accepts CRLF as separator': function(test) {
        var chopped = "data: Aslak\r\n\r\ndata: Hellesøy\r\n\r\n".split("");
        createServer(chopped, function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Aslak", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("Hellesøy", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'accepts CR as separator': function(test) {
        var chopped = "data: Aslak\r\rdata: Hellesøy\r\r".split("");
        createServer(chopped, function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Aslak", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("Hellesøy", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'delivers message with explicit event': function(test) {
        createServer(["event: greeting\ndata: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('greeting', function(m) {
                test.equal("Hello", m.data);
                es.close();
                close(test.done);
            });
        });
    },

    'comments are ignored': function(test) {
        createServer(["data: Hello\n\n:nothing to see here\n\ndata: World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Hello", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("World", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'empty comments are ignored': function(test) {
        createServer(["data: Hello\n\n:\n\ndata: World\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onmessage = first;

            function first(m) {
                test.equal("Hello", m.data);
                es.onmessage = second;
            }

            function second(m) {
                test.equal("World", m.data);
                es.close();
                close(test.done);
            }
        });
    },

    'empty data field causes entire event to be ignored': function(test) {
        createServer(["data:\n\ndata: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            var originalEmit = es.emit;
            es.emit = function(event) {
                test.ok(event === 'close' || event === 'message' || event === 'newListener');
                return originalEmit.apply(this, arguments);
            }
            es.onmessage = function(m) {
                test.equal('Hello', m.data);
                es.close();
                close(test.done);
            };
        });
    },

    'empty event field causes entire event to be ignored': function(test) {
        createServer(["event:\n\ndata: Hello\n\n"], function(close) {
            var es = new EventSource('http://localhost:' + port);
            var originalEmit = es.emit;
            es.emit = function(event) {
                test.ok(event === 'close' || event === 'message' || event === 'newListener');
                return originalEmit.apply(this, arguments);
            }
            es.onmessage = function(m) {
                test.equal('Hello', m.data);
                es.close();
                close(test.done);
            };
        });
    },
};

exports['Reconnect'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'when server is down': function(test) {
        var es = new EventSource('http://localhost:' + port);
        es.reconnectInterval = 0;
        var theClose = null;

        es.onerror = function(source) {
            es.onerror = null;
            createServer(["data: Hello\n\n"], function(close) {
                theClose = close;
            });
        };

        es.onmessage = function(m) {
            test.equal("Hello", m.data);
            es.close();
            theClose(test.done);
        };
    },

    'when server goes down after connection': function(test) {
        createServer(["data: Hello\n\n"], function(closeFirstServer) {
            var es = new EventSource('http://localhost:' + port);
            es.reconnectInterval = 0;

            es.onmessage = function(m) {
                test.equal("Hello", m.data);
                closeFirstServer(function() {
                    createServer(["data: World\n\n"], function(closeSecondServer) {
                        es.onmessage = second;

                        function second(m) {
                            test.equal("World", m.data);
                            es.close();
                            closeSecondServer(test.done);
                        }
                    });
                });
            };
        });
    }
};

exports['readyState'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'has CONNECTING constant': function(test) {
        test.equal(0, EventSource.CONNECTING);
        test.done();
    },

    'has OPEN constant': function(test) {
        test.equal(1, EventSource.OPEN);
        test.done();
    },

    'has CLOSED constant': function(test) {
        test.equal(2, EventSource.CLOSED);
        test.done();
    },

    'readyState is CONNECTING before connection has been established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            test.equal(EventSource.CONNECTING, es.readyState);
            es.onopen = function() {
                es.close();
                close(test.done);
            }
        });
    },

    'readyState is OPEN when connection has been established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                test.equal(EventSource.OPEN, es.readyState);
                es.close();
                close(test.done);
            }
        });
    },

    'readyState is CLOSED after connection has been closed': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                es.close();
            }
            es.onclose = function() {
                test.equal(EventSource.CLOSED, es.readyState);
                close(test.done);
            }
        });
    },
};

exports['Properties'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'url exposes original request url': function(test) {
        createServer([], function(close) {
            var url = 'http://localhost:' + port;
            var es = new EventSource(url);
            es.onopen = function() {
                test.equal(url, es.url);
                es.close();
                close(test.done);
            }
        });
    },
};

exports['Events'] = {
    setUp: function(done) {
        port++;
        done();
    },

    'calls onopen when connection is established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                es.close();
                close(test.done);
            }
        });
    },

    'emits open event when connection is established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('open', function() {
                es.close();
                close(test.done);
            });
        });
    },

    'calls onclose when connection is closed': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.onopen = function() {
                es.close();
            }
            es.onclose = function() {
                close(test.done);
            }
        });
    },

    'emits close event when connection is established': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('open', function() {
                es.close();
            });
            es.addEventListener('close', function() {
                close(test.done);
            });
        });
    },

    'does not emit error when connection is closed by client': function(test) {
        createServer([], function(close) {
            var es = new EventSource('http://localhost:' + port);
            es.addEventListener('open', function() {
                es.close();
            });
            es.addEventListener('error', function() {
                throw new Error('error should not be emitted');
            });
            es.addEventListener('close', function() {
                close(test.done);
            });
        });
    },
};
<|endoftext|>


<commit_before>'use strict';

var expect = require('chai').expect;
var utils = require('../public/javascripts/utils.js');
<commit_msg>Fix Linter<commit_after>'use strict';

var expect = require('chai').expect;
var utils = require('../public/javascripts/utils.js');

console.log(expect, utils);
<|endoftext|>


<commit_before>var ssr = require("../lib/");
var helpers = require("./helpers");
var assert = require("assert");
var path = require("path");
var Writable = require("stream").Writable;
var through = require("through2");
var noop = Function.prototype;
var chromeUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36";

describe("Incremental rendering", function(){
	this.timeout(10000);

	before(function(){
		this.oldXHR = global.XMLHttpRequest;
		global.XMLHttpRequest = helpers.mockXHR(
			'[ { "a": "a" }, { "b": "b" } ]');

		this.render = ssr({
			config: "file:" + path.join(__dirname, "tests", "package.json!npm"),
			main: "async/index.stache!done-autorender"
		}, {
			strategy: "incremental"
		});
	});

	after(function(){
		global.XMLHttpRequest = this.oldXHR;
	});

	describe("A basic asyc app", function(){
		before(function(done){
			var result = this.result = {
				html: null,
				instructions: []
			};

			var request = {
				url: "/",
				headers: {
					"user-agent": chromeUA
				}
			};

			var response = through(function(buffer, enc, done){
				result.html = buffer.toString();
			});
			response.writeHead = noop;
			response.push = function(){
				return new Writable({
					write(chunk, enc, next) {
						var json = chunk.toString();
						var instrs = JSON.parse(json);
						result.instructions.push(instrs);
						done();
						next();
					}
				});
			};

			this.render(request).pipe(response);
		});

		it("Sends the correct rendering instructions", function(){
			var instr = this.result.instructions[0][1];
			assert.equal(instr.route, "0.2.7");

			// Easier to test
			var nodeAsJson = JSON.stringify(instr.node);
			assert.ok(/ORDER-HISTORY/.test(nodeAsJson), "adds the order-history component");
		});

		it("Includes the styles as part of the initial HTML", function(){
			var dom = helpers.dom(this.result.html);
			// The script is the first element of the dom
			var doc = dom.nextSibling;
			var style = helpers.find(doc, function(el){
				return el.nodeName === "STYLE";
			});

			assert.ok(style, "Some styles were included");
		});
	});
});
<commit_msg>Update incremental rendering test<commit_after>var ssr = require("../lib/");
var helpers = require("./helpers");
var assert = require("assert");
var path = require("path");
var Writable = require("stream").Writable;
var through = require("through2");
var noop = Function.prototype;
var chromeUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36";

describe("Incremental rendering", function(){
	this.timeout(10000);

	before(function(){
		this.oldXHR = global.XMLHttpRequest;
		global.XMLHttpRequest = helpers.mockXHR(
			'[ { "a": "a" }, { "b": "b" } ]');

		this.render = ssr({
			config: "file:" + path.join(__dirname, "tests", "package.json!npm"),
			main: "async/index.stache!done-autorender"
		}, {
			strategy: "incremental"
		});
	});

	after(function(){
		global.XMLHttpRequest = this.oldXHR;
	});

	describe("A basic asyc app", function(){
		before(function(done){
			var result = this.result = {
				html: null,
				instructions: []
			};

			var request = {
				url: "/",
				headers: {
					"user-agent": chromeUA
				}
			};

			var response = through(function(buffer, enc, done){
				result.html = buffer.toString();
			});
			response.writeHead = noop;
			response.push = function(){
				return new Writable({
					write(chunk, enc, next) {
						var json = chunk.toString();
						var instrs = JSON.parse(json);
						result.instructions.push(instrs);
						done();
						next();
					}
				});
			};

			this.render(request).pipe(response);
		});

		it("Sends the correct rendering instructions", function(){
			var instr = this.result.instructions[0][0];
			assert.equal(instr.route, "0.2.7");

			// Easier to test
			var nodeAsJson = JSON.stringify(instr.node);
			assert.ok(/ORDER-HISTORY/.test(nodeAsJson), "adds the order-history component");
		});

		it("Includes the styles as part of the initial HTML", function(){
			var dom = helpers.dom(this.result.html);
			// The script is the first element of the dom
			var doc = dom.nextSibling;
			var style = helpers.find(doc, function(el){
				return el.nodeName === "STYLE";
			});

			assert.ok(style, "Some styles were included");
		});
	});
});
<|endoftext|>


<commit_before>var assert = require('assert')

var bitcoin = require('../../')
var networks = bitcoin.networks
var scripts = bitcoin.scripts

var Address = bitcoin.Address
var ECKey = bitcoin.ECKey
var TransactionBuilder = bitcoin.TransactionBuilder

var helloblock = require('helloblock-js')({
  network: 'testnet'
})

describe('Bitcoin-js', function() {
  this.timeout(10000)

  it('can spend from a 2-of-2 address', function(done) {
    var privKeys = [
      '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx',
      '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT'
    ].map(function(wif) {
      return ECKey.fromWIF(wif)
    })

    var coldAmount = 2e4
    var outputAmount = 1e4

    var pubKeys = privKeys.map(function(eck) { return eck.pub })
    var redeemScript = scripts.multisigOutput(2, pubKeys)
    var scriptPubKey = scripts.scriptHashOutput(redeemScript.getHash())

    var multisigAddress = Address.fromOutputScript(scriptPubKey, networks.testnet).toString()

    // Attempt to send funds to the source address, providing some unspents for later
    helloblock.faucet.withdraw(multisigAddress, coldAmount, function(err) {
      if (err) return done(err)
    })

    // make a random private key
    var targetAddress = ECKey.makeRandom().pub.getAddress(networks.testnet).toString()

    // get latest unspents from the multisigAddress
    helloblock.addresses.getUnspents(multisigAddress, function(err, res, unspents) {
      if (err) return done(err)

      // use the oldest unspent
      var unspent = unspents[unspents.length - 1]
      var spendAmount = Math.min(unspent.value, outputAmount)

      var txb = new TransactionBuilder()
      txb.addInput(unspent.txHash, unspent.index)
      txb.addOutput(targetAddress, spendAmount)

      privKeys.forEach(function(privKey) {
        txb.sign(0, privKey, redeemScript)
      })

      // broadcast our transaction
      helloblock.transactions.propagate(txb.build().toHex(), function(err, res) {
        // no err means that the transaction has been successfully propagated
        if (err) return done(err)

        // Check that the funds (spendAmount Satoshis) indeed arrived at the intended address
        helloblock.addresses.get(targetAddress, function(err, res, addrInfo) {
          if (err) return done(err)

          assert.equal(addrInfo.balance, spendAmount)
          done()
        })
      })
    })
  })
})
<commit_msg>tests: remove unused variable<commit_after>var assert = require('assert')

var bitcoin = require('../../')
var networks = bitcoin.networks
var scripts = bitcoin.scripts

var Address = bitcoin.Address
var ECKey = bitcoin.ECKey
var TransactionBuilder = bitcoin.TransactionBuilder

var helloblock = require('helloblock-js')({
  network: 'testnet'
})

describe('Bitcoin-js', function() {
  this.timeout(10000)

  it('can spend from a 2-of-2 address', function(done) {
    var privKeys = [
      '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx',
      '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT'
    ].map(function(wif) {
      return ECKey.fromWIF(wif)
    })

    var coldAmount = 2e4
    var outputAmount = 1e4

    var pubKeys = privKeys.map(function(eck) { return eck.pub })
    var redeemScript = scripts.multisigOutput(2, pubKeys)
    var scriptPubKey = scripts.scriptHashOutput(redeemScript.getHash())

    var multisigAddress = Address.fromOutputScript(scriptPubKey, networks.testnet).toString()

    // Attempt to send funds to the source address, providing some unspents for later
    helloblock.faucet.withdraw(multisigAddress, coldAmount, function(err) {
      if (err) return done(err)
    })

    // make a random private key
    var targetAddress = ECKey.makeRandom().pub.getAddress(networks.testnet).toString()

    // get latest unspents from the multisigAddress
    helloblock.addresses.getUnspents(multisigAddress, function(err, res, unspents) {
      if (err) return done(err)

      // use the oldest unspent
      var unspent = unspents[unspents.length - 1]
      var spendAmount = Math.min(unspent.value, outputAmount)

      var txb = new TransactionBuilder()
      txb.addInput(unspent.txHash, unspent.index)
      txb.addOutput(targetAddress, spendAmount)

      privKeys.forEach(function(privKey) {
        txb.sign(0, privKey, redeemScript)
      })

      // broadcast our transaction
      helloblock.transactions.propagate(txb.build().toHex(), function(err) {
        // no err means that the transaction has been successfully propagated
        if (err) return done(err)

        // Check that the funds (spendAmount Satoshis) indeed arrived at the intended address
        helloblock.addresses.get(targetAddress, function(err, res, addrInfo) {
          if (err) return done(err)

          assert.equal(addrInfo.balance, spendAmount)
          done()
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
const path = require('path');
const Listr = require('listr');
const tempy = require('tempy');
const execa = require('execa');
const del = require('del');
const chalk = require('chalk');

const packages = new Map([
	['ava', 'https://github.com/avajs/ava'],
	['chalk', 'https://github.com/chalk/chalk'],
	['wrap-ansi', 'https://github.com/chalk/wrap-ansi'],
	['np', 'https://github.com/sindresorhus/np'],
	['ora', 'https://github.com/sindresorhus/ora'],
	['p-map', 'https://github.com/sindresorhus/p-map'],
	['os-locale', 'https://github.com/sindresorhus/os-locale'],
	['execa', 'https://github.com/sindresorhus/execa'],
	['pify', 'https://github.com/sindresorhus/pify'],
	['boxen', 'https://github.com/sindresorhus/boxen'],
	['make-dir', 'https://github.com/sindresorhus/make-dir'],
	['listr', 'http://github.com/SamVerschueren/listr'],
	['listr-update-renderer', 'http://github.com/SamVerschueren/listr-update-renderer'],
	['bragg', 'http://github.com/SamVerschueren/bragg'],
	['bragg-router', 'http://github.com/SamVerschueren/bragg-router'],
	['dev-time', 'http://github.com/SamVerschueren/dev-time'],
	['decode-uri-component', 'https://github.com/SamVerschueren/decode-uri-component'],
	['to-ico', 'https://github.com/kevva/to-ico'],
	['download', 'https://github.com/kevva/download'],
	['brightness', 'https://github.com/kevva/brightness'],
	['decompress', 'https://github.com/kevva/decompress'],
	['npm-conf', 'https://github.com/kevva/npm-conf'],
	['imagemin', 'https://github.com/imagemin/imagemin'],
	['color-convert', 'https://github.com/qix-/color-convert'],
	['eslint-plugin-unicorn', 'https://github.com/sindresorhus/eslint-plugin-unicorn'],
	['ky', 'https://github.com/sindresorhus/ky'],
	['query-string', 'https://github.com/sindresorhus/query-string'],
	['meow', 'https://github.com/sindresorhus/meow'],
	['emittery', 'https://github.com/sindresorhus/emittery'],
	['p-queue', 'https://github.com/sindresorhus/p-queue'],
	['pretty-bytes', 'https://github.com/sindresorhus/pretty-bytes'],
	['normalize-url', 'https://github.com/sindresorhus/normalize-url'],
	['pageres', 'https://github.com/sindresorhus/pageres'],
	['got', 'https://github.com/sindresorhus/got']
]);

const typescriptPackages = new Set([
	'pageres',
	'got',
	'p-queue'
]);

const cwd = path.join(__dirname, 'eslint-config-ava-tester');

const enrichErrors = (packageName, cliArgs, f) => async (...args) => {
	try {
		return await f(...args);
	} catch (error) {
		error.packageName = packageName;
		error.cliArgs = cliArgs;
		throw error;
	}
};

const makeEslintTask = (packageName, dest, extraArgs = []) => {
	const isTypescriptPackage = typescriptPackages.has(packageName);
	const typescriptArgs = isTypescriptPackage ? ['--parser', '@typescript-eslint/parser', '--ext', '.ts'] : [];

	const args = ['eslint', '--format', 'json', '--config', path.join(cwd, 'index.js'), dest, ...typescriptArgs, ...extraArgs];

	return enrichErrors(packageName, args, async () => {
		let stdout;
		let processError;
		try {
			({stdout} = await execa('npx', args, {cwd, localDir: __dirname}));
		} catch (error) {
			({stdout} = error);
			processError = error;

			if (!stdout) {
				throw error;
			}
		}

		let files;
		try {
			files = JSON.parse(stdout);
		} catch (error) {
			console.error('Error while parsing eslint output:', error);

			if (processError) {
				throw processError;
			}

			throw error;
		}

		for (const file of files) {
			for (const message of file.messages) {
				if (message.fatal) {
					const error = new Error(message.message);
					error.eslintFile = file;
					error.eslintMessage = message;
					throw error;
				}
			}
		}
	});
};

const execute = name => {
	const dest = tempy.directory();

	return new Listr([
		{
			title: 'Cloning',
			task: () => execa('git', ['clone', packages.get(name), '--single-branch', dest])
		},
		{
			title: 'Running eslint',
			task: makeEslintTask(name, dest)
		},
		{
			title: 'Running eslint --fix',
			task: makeEslintTask(name, dest, ['--fix-dry-run'])
		},
		{
			title: 'Clean up',
			task: () => del(dest, {force: true})
		}
	], {
		exitOnError: false
	});
};

const list = new Listr([
	{
		title: 'Setup',
		task: () => execa('npm', ['install', '../../..', 'eslint', 'babel-eslint', 'typescript', '@typescript-eslint/parser'], {cwd})
	},
	{
		title: 'Integration tests',
		task: () => {
			const tests = new Listr({concurrent: true});

			for (const [name] of packages) {
				tests.add([
					{
						title: name,
						task: () => execute(name)
					}
				]);
			}

			return tests;
		}
	}
]);

list.run()
	.catch(error => {
		if (error.errors) {
			for (const error2 of error.errors) {
				console.error('\n', chalk.red.bold.underline(error2.packageName), chalk.gray('(' + error2.cliArgs.join(' ') + ')'));
				console.error(error2.message);
				if (error2.eslintMessage) {
					console.error(chalk.gray(error2.eslintFile.filePath), chalk.gray(JSON.stringify(error2.eslintMessage, null, 2)));
				}
			}
		} else {
			console.error(error);
		}

		process.exit(1);
	});
<commit_msg>Update integration test script (#282)<commit_after>#!/usr/bin/env node
'use strict';
const path = require('path');
const Listr = require('listr');
const tempy = require('tempy');
const execa = require('execa');
const del = require('del');
const chalk = require('chalk');

const packages = new Map([
	['ava', 'https://github.com/avajs/ava'],
	['chalk', 'https://github.com/chalk/chalk'],
	['wrap-ansi', 'https://github.com/chalk/wrap-ansi'],
	['np', 'https://github.com/sindresorhus/np'],
	['ora', 'https://github.com/sindresorhus/ora'],
	['p-map', 'https://github.com/sindresorhus/p-map'],
	['os-locale', 'https://github.com/sindresorhus/os-locale'],
	['execa', 'https://github.com/sindresorhus/execa'],
	['pify', 'https://github.com/sindresorhus/pify'],
	['boxen', 'https://github.com/sindresorhus/boxen'],
	['make-dir', 'https://github.com/sindresorhus/make-dir'],
	['listr', 'http://github.com/SamVerschueren/listr'],
	['listr-update-renderer', 'http://github.com/SamVerschueren/listr-update-renderer'],
	['bragg', 'http://github.com/SamVerschueren/bragg'],
	['bragg-router', 'http://github.com/SamVerschueren/bragg-router'],
	['dev-time', 'http://github.com/SamVerschueren/dev-time'],
	['decode-uri-component', 'https://github.com/SamVerschueren/decode-uri-component'],
	['to-ico', 'https://github.com/kevva/to-ico'],
	['download', 'https://github.com/kevva/download'],
	['brightness', 'https://github.com/kevva/brightness'],
	['decompress', 'https://github.com/kevva/decompress'],
	['npm-conf', 'https://github.com/kevva/npm-conf'],
	['imagemin', 'https://github.com/imagemin/imagemin'],
	['color-convert', 'https://github.com/qix-/color-convert'],
	['eslint-plugin-unicorn', 'https://github.com/sindresorhus/eslint-plugin-unicorn'],
	['ky', 'https://github.com/sindresorhus/ky'],
	['query-string', 'https://github.com/sindresorhus/query-string'],
	['meow', 'https://github.com/sindresorhus/meow'],
	['emittery', 'https://github.com/sindresorhus/emittery'],
	['p-queue', 'https://github.com/sindresorhus/p-queue'],
	['pretty-bytes', 'https://github.com/sindresorhus/pretty-bytes'],
	['normalize-url', 'https://github.com/sindresorhus/normalize-url'],
	['pageres', 'https://github.com/sindresorhus/pageres'],
	['got', 'https://github.com/sindresorhus/got']
]);

const typescriptPackages = new Set([
	'pageres',
	'got',
	'p-queue'
]);

const cwd = path.join(__dirname, 'eslint-config-ava-tester');

const enrichErrors = (packageName, cliArgs, f) => async (...args) => {
	try {
		return await f(...args);
	} catch (error) {
		error.packageName = packageName;
		error.cliArgs = cliArgs;
		throw error;
	}
};

const makeEslintTask = (packageName, dest, extraArgs = []) => {
	const isTypescriptPackage = typescriptPackages.has(packageName);
	const typescriptArgs = isTypescriptPackage ? ['--parser', '@typescript-eslint/parser', '--ext', '.ts'] : [];

	const args = ['eslint', '--format', 'json', '--config', path.join(cwd, 'index.js'), dest, ...typescriptArgs, ...extraArgs];

	return enrichErrors(packageName, args, async () => {
		let stdout;
		let processError;
		try {
			({stdout} = await execa('npx', args, {cwd, localDir: __dirname}));
		} catch (error) {
			({stdout} = error);
			processError = error;

			if (!stdout) {
				throw error;
			}
		}

		let files;
		try {
			files = JSON.parse(stdout);
		} catch (error) {
			console.error('Error while parsing eslint output:', error);

			if (processError) {
				throw processError;
			}

			throw error;
		}

		for (const file of files) {
			for (const message of file.messages) {
				if (message.fatal) {
					const error = new Error(message.message);
					error.eslintFile = file;
					error.eslintMessage = message;
					throw error;
				}
			}
		}
	});
};

const execute = name => {
	const dest = tempy.directory();

	return new Listr([
		{
			title: 'Cloning',
			task: () => execa('git', ['clone', packages.get(name), '--single-branch', dest])
		},
		{
			title: 'Running eslint',
			task: makeEslintTask(name, dest)
		},
		{
			title: 'Running eslint --fix',
			task: makeEslintTask(name, dest, ['--fix-dry-run'])
		},
		{
			title: 'Clean up',
			task: () => del(dest, {force: true})
		}
	].map(({title, task}) => ({
		title: `${name} / ${title}`,
		task
	})), {
		exitOnError: false
	});
};

const list = new Listr([
	{
		title: 'Setup',
		task: () => execa('npm', ['install', '../../..', 'eslint', 'babel-eslint', 'typescript', '@typescript-eslint/parser'], {cwd})
	},
	{
		title: 'Integration tests',
		task: () => {
			const tests = new Listr({concurrent: true});

			for (const [name] of packages) {
				tests.add([
					{
						title: name,
						task: () => execute(name)
					}
				]);
			}

			return tests;
		}
	}
], {
	renderer: process.env.INTEGRATION ? 'verbose' : 'default'
});

list.run()
	.catch(error => {
		if (error.errors) {
			for (const error2 of error.errors) {
				console.error('\n', chalk.red.bold.underline(error2.packageName), chalk.gray('(' + error2.cliArgs.join(' ') + ')'));
				console.error(error2.message);

				if (error2.stderr) {
					console.error(chalk.gray(error2.stderr));
				}

				if (error2.eslintMessage) {
					console.error(chalk.gray(error2.eslintFile.filePath), chalk.gray(JSON.stringify(error2.eslintMessage, null, 2)));
				}
			}
		} else {
			console.error(error);
		}

		process.exit(1);
	});
<|endoftext|>


<commit_before>import { execFile } from 'child_process'
import flow from 'flow-bin'
import { logError, log } from '../util/log'

const errorCodes = {
  TYPECHECK_ERROR: 2
}

export default (saguiOptions) => new Promise((resolve, reject) => {
  const commandArgs = ['check', '--color=always']

  if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) {
    commandArgs.push('--all')
  }

  execFile(flow, commandArgs, (err, stdout, stderr) => {
    if (err) {
      logError('Type check failed:\n')

      switch (err.code) {
        case errorCodes.TYPECHECK_ERROR:
          console.log(stdout)
          break

        default:
          console.log(err)
      }

      reject()
    } else {
      log('Type check completed without errors')
      resolve()
    }
  })
})
<commit_msg>Disable type checking in Windows 😞<commit_after>import { execFile } from 'child_process'
import flow from 'flow-bin'
import { logError, logWarning, log } from '../util/log'

const errorCodes = {
  TYPECHECK_ERROR: 2
}

export default (saguiOptions) => new Promise((resolve, reject) => {
  // Currently Facebook does not provide Windows builds.
  // https://github.com/flowtype/flow-bin#flow-bin-
  //
  // Instead of using `flow`, we show a warning and ignore this task
  // For further discussion, you can go to:
  // https://github.com/saguijs/sagui/issues/179
  if (process.platform === 'win32') {
    logWarning('Type checking in Windows is not currently supported')
    log('Official flow builds for Windows are not currently provided.')
    log('We are exploring options in https://github.com/saguijs/sagui/issues/179')

    return resolve()
  }

  const commandArgs = ['check', '--color=always']

  if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) {
    commandArgs.push('--all')
  }

  execFile(flow, commandArgs, (err, stdout, stderr) => {
    if (err) {
      logError('Type check failed:\n')

      switch (err.code) {
        case errorCodes.TYPECHECK_ERROR:
          console.log(stdout)
          break

        default:
          console.log(err)
      }

      reject()
    } else {
      log('Type check completed without errors')
      resolve()
    }
  })
})
<|endoftext|>