<commit_before>import React from "react";
import ReactDOM from "react-dom";
import TestUtils from "react-addons-test-utils";
import test from "tape-catch";
import sinon from "sinon";

import Tour from "../dist/index";

const onNext = sinon.stub();
const onBack = sinon.stub();
const onCancel = sinon.stub();

const props = {
	active: true,
	step: 1,
	steps: [
		{
			step: 1,
			selector: ".my-fun-website",
			title:
My Web
,
			message:
Site

		},
		{
			step: 2,
			selector: ".my-website-is-amazing",
			title:
Wow
,
			message:
so good

		},
		{
			step: 3,
			selector: ".my-website-is-amazing-yeah-it-is",
			title:
Wow
,
			message:
so good

		}
	],
	onNext: onNext,
	onBack: onBack,
	onCancel: onCancel
}

const throwNoClass = (dom, className) => {
	TestUtils.findRenderedDOMComponentWithClass(dom, className);
}

test("is React Component", (assert) => {
	const component = <Tour {...props} />

	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.isElement(component), "ReactUserTour is a react component");
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should return a single span if active is false", (assert) => {
	const component = <Tour {...props} active={false} />
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithTag(result, "span"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should have the container className if active is true", (assert) => {
	const component = <Tour {...props} />
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-container"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should have a next button but no back or done button when step is 1 and there are 3 steps", (assert) => {
	const component = <Tour {...props} />
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-next-button"));
	assert.throws(() => throwNoClass(result, "react-user-tour-back-button"), /found: 0/);
	assert.throws(() => throwNoClass(result, "react-user-tour-done-button"), /found: 0/);
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should have a next button and a back button but no done button when step is 2 and there are 3 steps", (assert) => {
	const component = <Tour {...props} step={2} />
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-next-button"));
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-back-button"));
	assert.throws(() => throwNoClass(result, "react-user-tour-done-button"), /found: 0/);
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should have a back button and a done button but no next button when step is 3 and there are 3 steps", (assert) => {
	const component = <Tour {...props} step={3} />
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-done-button"));
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-back-button"));
	assert.throws(() => throwNoClass(result, "react-user-tour-next-button"), /found: 0/);
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should return a single span if the passed in step does not exist in the steps prop", (assert) => {
	const component = <Tour {...props} step={10} />
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithTag(result, "span"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should have a default arrow that will point to selected dom class if no arrow prop is passed in", (assert) => {
	const component = <Tour {...props} step={3} />
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-arrow"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should not have a default arrow that will point to selected dom class if an arrow prop is passed in", (assert) => {
	const component = <Tour {...props} step={3} arrow={}/>
	const result = TestUtils.renderIntoDocument(component);
	assert.throws(() => throwNoClass(result, "react-user-tour-arrow"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("should not any buttons or the associated button container if hideButtons is true", (assert) => {
	const component = <Tour {...props} step={3} hideButtons={true}/>
	const result = TestUtils.renderIntoDocument(component);
	assert.throws(() => throwNoClass(result, "react-user-tour-button-container"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("onNext should be called once when the user clicks the next button", (assert) => {
	const component = <Tour {...props} />
	const result = TestUtils.renderIntoDocument(component);
	const nextButton = TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-next-button");
	TestUtils.Simulate.click(nextButton);
	assert.ok(onNext.calledOnce);
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("onBack should be called once when the user clicks the back button", (assert) => {
	const component = <Tour {...props} step={2}/>
	const result = TestUtils.renderIntoDocument(component);
	const backButton = TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-back-button");
	TestUtils.Simulate.click(backButton);
	assert.ok(onBack.calledOnce);
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("onCancel should be called once when the user clicks the done button", (assert) => {
	const component = <Tour {...props} step={3}/>
	const result = TestUtils.renderIntoDocument(component);
	const doneButton = TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-done-button");
	TestUtils.Simulate.click(doneButton);
	assert.ok(onCancel.calledOnce);
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("the close button should be there if hideClose is not true", (assert) => {
	const component = <Tour {...props} step={3}/>
	const result = TestUtils.renderIntoDocument(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-close"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
});

test("the close button should not be there if hideClose is true", (assert) => {
	const component = <Tour {...props} step={3}/>
	const result = TestUtils.renderIntoDocument(component);
	assert.throws(() => throwNoClass("react-user-tour-close"));
	ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(result));
	assert.end();
})
<commit_msg>refactor tests to remove warnings<commit_after>import React from "react";
import ReactDOM from "react-dom";
import TestUtils from "react-addons-test-utils";
import test from "tape-catch";
import sinon from "sinon";

import Tour from "../dist/index";

const onNext = sinon.stub();
const onBack = sinon.stub();
const onCancel = sinon.stub();

const props = {
	active: true,
	step: 1,
	steps: [
		{
			step: 1,
			selector: ".my-fun-website",
			title:
My Web
,
			message:
Site

		},
		{
			step: 2,
			selector: ".my-website-is-amazing",
			title:
Wow
,
			message:
so good

		},
		{
			step: 3,
			selector: ".my-website-is-amazing-yeah-it-is",
			title:
Wow
,
			message:
so good

		}
	],
	onNext: onNext,
	onBack: onBack,
	onCancel: onCancel
}

const throwNoClass = (dom, className) => {
	TestUtils.findRenderedDOMComponentWithClass(dom, className);
}

const node = document.createElement("div");
const renderComponent = (component) => ReactDOM.render(component, node);

test("is React Component", (assert) => {
	const component = <Tour {...props} />;
	assert.ok(TestUtils.isElement(component), "ReactUserTour is a react component");
	assert.end();
});

test("should return a single span if active is false", (assert) => {
	const component = <Tour {...props} active={false} />
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithTag(result, "span"), "when active is a false a span is returned");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should have the container className if active is true", (assert) => {
	const component = <Tour {...props} />
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-container"), "container element exists");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should have a next button but no back or done button when step is 1 and there are 3 steps", (assert) => {
	const component = <Tour {...props} />
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-next-button"), "nexxt button exists");
	assert.throws(() => throwNoClass(result, "react-user-tour-back-button"), /found: 0/);
	assert.throws(() => throwNoClass(result, "react-user-tour-done-button"), /found: 0/);
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should have a next button and a back button but no done button when step is 2 and there are 3 steps", (assert) => {
	const component = <Tour {...props} step={2} />
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-next-button"), "next button exists");
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-back-button"), "back button exists");
	assert.throws(() => throwNoClass(result, "react-user-tour-done-button"), /found: 0/);
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should have a back button and a done button but no next button when step is 3 and there are 3 steps", (assert) => {
	const component = <Tour {...props} step={3} />
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-done-button"), "done button exists");
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-back-button"), "back button exists");
	assert.throws(() => throwNoClass(result, "react-user-tour-next-button"), /found: 0/);
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should return a single span if the passed in step does not exist in the steps prop", (assert) => {
	const component = <Tour {...props} step={10} />
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithTag(result, "span"), "returns span");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should have a default arrow that will point to selected dom class if no arrow prop is passed in", (assert) => {
	const component = <Tour {...props} step={3} />
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-arrow"), "arrow exists");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should not have a default arrow that will point to selected dom class if an arrow prop is passed in", (assert) => {
	const component = <Tour {...props} step={3} arrow={}/>
	const result = renderComponent(component);
	assert.throws(() => throwNoClass(result, "react-user-tour-arrow"));
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("should not any buttons or the associated button container if hideButtons is true", (assert) => {
	const component = <Tour {...props} step={3} hideButtons={true}/>
	const result = renderComponent(component);
	assert.throws(() => throwNoClass(result, "react-user-tour-button-container"));
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("onNext should be called once when the user clicks the next button", (assert) => {
	const component = <Tour {...props} />
	const result = renderComponent(component);
	const nextButton = TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-next-button");
	TestUtils.Simulate.click(nextButton);
	assert.ok(onNext.calledOnce, "onNext function called once");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("onBack should be called once when the user clicks the back button", (assert) => {
	const component = <Tour {...props} step={2}/>
	const result = renderComponent(component);
	const backButton = TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-back-button");
	TestUtils.Simulate.click(backButton);
	assert.ok(onBack.calledOnce, "onBack function called once");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("onCancel should be called once when the user clicks the done button", (assert) => {
	const component = <Tour {...props} step={3}/>
	const result = renderComponent(component);
	const doneButton = TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-done-button");
	TestUtils.Simulate.click(doneButton);
	assert.ok(onCancel.calledOnce, "onCancel called once");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("the close button should be there if hideClose is not true", (assert) => {
	const component = <Tour {...props} step={3}/>
	const result = renderComponent(component);
	assert.ok(TestUtils.findRenderedDOMComponentWithClass(result, "react-user-tour-close"), "close button exists");
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
});

test("the close button should not be there if hideClose is true", (assert) => {
	const component = <Tour {...props} step={3}/>
	const result = renderComponent(component);
	assert.throws(() => throwNoClass("react-user-tour-close"));
	ReactDOM.unmountComponentAtNode(node);
	assert.end();
})
<|endoftext|>


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

var sysout = require('../util/sysout');
var subprocess = require('../subprocess');
var proxy = require('../proxy');
var Latch = require('../util/Latch');

function setupBouncyServer(config, cb){
  sysout.log();

  var server = proxy(config.getDomainPortMap());
  sysout.log(`Mapping...`);
  config.each((domain, app) => {
    sysout.log(`  \`${app.name}\` launched and listening to port ${app.port}`);
  });

  cb(server);
}

module.exports = function(config, cb){
  // countdown latch to forcefully make sure all sub-servers are launched before the bouncy server does.
  var latch = new Latch(config.getDomains().length, setupBouncyServer.bind(null, config, cb));

  // launch each sub-servers
  config.each((domain, app) => {
    freeport((err, port) => {
      if(err) throw err;

      subprocess(app).start(port, function(){
        sysout.log(`${app.name} launched and listening on port ${port}...`);
        app.port = port;
        latch.down();
      });
    });
  });
}
<commit_msg>further refactored<commit_after>var freeport = require('freeport');

var sysout = require('../util/sysout');
var subprocess = require('../subprocess');
var proxy = require('../proxy');
var Latch = require('../util/Latch');

function setupBouncyServer(config, cb){
  sysout.log();

  var server = proxy(config.getDomainPortMap());
  sysout.log(`Mapping...`);
  config.each((domain, app) => {
    sysout.log(`  \`${app.name}\` launched and listening to port ${app.port}`);
  });

  cb(server);
}

function setupForeverServers(config, cb){
  // countdown latch to forcefully make sure all sub-servers are launched before the bouncy server does.
  var latch = new Latch(config.getDomains().length, cb);

  // launch each sub-servers
  config.each((domain, app) => {
    freeport((err, port) => {
      if(err) throw err;

      subprocess(app).start(port, function(){
        sysout.log(`${app.name} launched and listening on port ${port}...`);
        app.port = port;
        latch.down();
      });
    });
  });
}

module.exports = function(config, cb){
  setupForeverServers(config, setupBouncyServer.bind(null, config, cb));
}
<|endoftext|>


<commit_before>// Load modules

var Lab = require('lab');
var Hapi = require('hapi');
var Net = require('net');
var Reptile = require('../');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var before = lab.before;
var after = lab.after;
var describe = lab.describe;
var it = lab.it;
var expect = Lab.expect;

describe('Reptile', function () {

    internals.availablePort = function (callback) {

        var server = Net.createServer();
        server.listen(0, function () {

            var port = server.address().port;
            server.close(function () {

                callback(port);
            });
        });
    };

    it('creates a REPL that a client can connect to over TCP', function (done) {

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            server.pack.register({ plugin: Reptile, options: { port: port } }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '127.0.0.1'
                    };
                };
                var sock = Net.connect(port);
                var state = 0;

                sock.on('readable', function () {

                    var buffer = sock.read();
                    if (!buffer) {
                        return;
                    }

                    var result = buffer.toString('ascii');

                    if (state === 0) {
                        expect(result.indexOf('>')).to.not.equal(-1);
                        sock.write('pack.hapi\n');
                    }
                    else if (state === 1) {
                        sock.write('.exit\n');
                    }
                    else if (state === 2) {
                        done();
                    }

                    state++;
                });
            });
        });
    });

    it('does not allow remote access by default', function (done) {

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            server.pack.register({ plugin: Reptile, options: { port: port } }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '192.168.0.1'
                    };
                };
                var sock = Net.connect(port);

                sock.once('close', function () {

                    done();
                });

                sock.on('readable', function () {

                    expect(sock.read()).to.not.exist;
                });
            });
        });
    });

    it('does allow remote access when localOnly is false', function (done) {

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            server.pack.register({ plugin: Reptile, options: { port: port, localOnly: false } }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '192.168.0.1'
                    };
                };

                var sock = Net.connect(port);
                var state = 0;

                sock.on('readable', function (size) {

                    var buffer = sock.read();
                    if (!buffer) {
                        return;
                    }

                    var result = buffer.toString('ascii');

                    if (state === 0) {
                        expect(result.indexOf('>')).to.not.equal(-1);
                        sock.write('pack.hapi\n');
                    }
                    else if (state === 1) {
                        sock.write('.exit\n');
                    }
                    else if (state === 2) {
                        done();
                    }

                    state++;
                });
            });
        });
    });

    it('allows the context of the REPL to be customized', function (done) {

        var config = {
            localOnly: false,
            context: {
                helloWorld: 'hola mundo'
            }
        };

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            config.port = port;

            server.pack.register({ plugin: Reptile, options: config }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '192.168.0.1'
                    };
                };

                var sock = Net.connect(port);
                var result = '';
                var state = 0;

                sock.on('readable', function (size) {

                    var buffer = sock.read();
                    if (!buffer) {
                        return;
                    }

                    result += buffer.toString('ascii');

                    if (state === 0) {
                        sock.write('helloWorld\n');
                    }
                    else if (state === 1) {
                        sock.write('.exit\n');
                    }
                    else {
                        expect(result).to.contain('hola mundo');
                        done();
                    }

                    state++;
                });
            });
        });
    });
});
<commit_msg>Update index.js<commit_after>// Load modules

var Lab = require('lab');
var Hapi = require('hapi');
var Net = require('net');
var Reptile = require('../');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var expect = Lab.expect;

describe('Reptile', function () {

    internals.availablePort = function (callback) {

        var server = Net.createServer();
        server.listen(0, function () {

            var port = server.address().port;
            server.close(function () {

                callback(port);
            });
        });
    };

    it('creates a REPL that a client can connect to over TCP', function (done) {

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            server.pack.register({ plugin: Reptile, options: { port: port } }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '127.0.0.1'
                    };
                };
                var sock = Net.connect(port);
                var state = 0;

                sock.on('readable', function () {

                    var buffer = sock.read();
                    if (!buffer) {
                        return;
                    }

                    var result = buffer.toString('ascii');

                    if (state === 0) {
                        expect(result.indexOf('>')).to.not.equal(-1);
                        sock.write('pack.hapi\n');
                    }
                    else if (state === 1) {
                        sock.write('.exit\n');
                    }
                    else if (state === 2) {
                        done();
                    }

                    state++;
                });
            });
        });
    });

    it('does not allow remote access by default', function (done) {

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            server.pack.register({ plugin: Reptile, options: { port: port } }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '192.168.0.1'
                    };
                };
                var sock = Net.connect(port);

                sock.once('close', function () {

                    done();
                });

                sock.on('readable', function () {

                    expect(sock.read()).to.not.exist;
                });
            });
        });
    });

    it('does allow remote access when localOnly is false', function (done) {

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            server.pack.register({ plugin: Reptile, options: { port: port, localOnly: false } }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '192.168.0.1'
                    };
                };

                var sock = Net.connect(port);
                var state = 0;

                sock.on('readable', function (size) {

                    var buffer = sock.read();
                    if (!buffer) {
                        return;
                    }

                    var result = buffer.toString('ascii');

                    if (state === 0) {
                        expect(result.indexOf('>')).to.not.equal(-1);
                        sock.write('pack.hapi\n');
                    }
                    else if (state === 1) {
                        sock.write('.exit\n');
                    }
                    else if (state === 2) {
                        done();
                    }

                    state++;
                });
            });
        });
    });

    it('allows the context of the REPL to be customized', function (done) {

        var config = {
            localOnly: false,
            context: {
                helloWorld: 'hola mundo'
            }
        };

        var server = new Hapi.Server();
        internals.availablePort(function (port) {

            config.port = port;

            server.pack.register({ plugin: Reptile, options: config }, function (err) {

                expect(err).to.not.exist;

                var address = Net.Socket.prototype.address;
                Net.Socket.prototype.address = function () {

                    Net.Socket.prototype.address = address;
                    return {
                        address: '192.168.0.1'
                    };
                };

                var sock = Net.connect(port);
                var result = '';
                var state = 0;

                sock.on('readable', function (size) {

                    var buffer = sock.read();
                    if (!buffer) {
                        return;
                    }

                    result += buffer.toString('ascii');

                    if (state === 0) {
                        sock.write('helloWorld\n');
                    }
                    else if (state === 1) {
                        sock.write('.exit\n');
                    }
                    else {
                        expect(result).to.contain('hola mundo');
                        done();
                    }

                    state++;
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>
var request = require('supertest')
var views = require('../')
var should = require('should')
var koa = require('koa')

describe('koa-views', function () {
  it('have a render method', function (done) {
    var app = koa()
    .use(views())
    .use(function *() {
      this.render.should.ok
      this.render.should.Function
    })

    request(app.listen()).get('/')
      .expect(404, done)
  })

  it('default to html', function (done) {
    var app = koa()
    .use(views(__dirname))
    .use(function *() {
      yield this.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:html/)
      .expect(200, done)
  })

  it('default to [ext] if a default engine is set', function (done) {
    var app = koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function *() {
      yield this.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('set and render state', function (done) {
    var app = koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function *() {
      this.state.engine = 'jade'
      yield this.render('./fixtures/global-state')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  // #25
  it('works with circular references in state', function (done) {
    var app = koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function *() {
      this.state = {
        a: {},
        app: app
      }

      this.state.a.a = this.state.a

      yield this.render('./fixtures/global-state', {
        app: app,
        b: this.state,
        engine: 'jade'
      })
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('`map` given `engine` to given file `ext`', function (done) {
    var app = koa()
    .use(views(__dirname, { map: {html: 'underscore'} }))
    .use(function *() {
      this.state.engine = 'underscore'
      yield this.render('./fixtures/underscore')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:underscore/)
      .expect(200, done)
  })

  it('merges global and local state ', function (done) {
    var app = koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function *() {
      this.state.engine = 'jade'

      yield this.render('./fixtures/state', {
        type: 'basic'
      })
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('yields to the next middleware if this.render is already defined', function (done) {
    var app = koa()
    .use(function *(next) {
      this.render = true
      yield next
    })
    .use(views())
    .use(function *() {
      this.body = 'hello'
    })

    request(app.listen()).get('/')
      .expect('hello')
      .expect(200, done)
  })

  // #23 && #27
  it('given a directory it should try to require index.[ext]', function (done) {
    var app = koa()
    .use(views(__dirname))
    .use(function *() {
      yield this.render('./fixtures')
    })

    request(app.listen()).get('/')
      .expect(/defaults-to-index/)
      .expect(200, done)
  })

  // #43
  it('it should not overwrite an extension when given one', function (done) {
    var app = koa()
    .use(views(__dirname))
    .use(function *() {
      yield this.render('./fixtures/basic.ejs')
    })

    request(app.listen()).get('/')
      .expect(/basic:ejs/)
      .expect(200, done)
  })
})
<commit_msg>Refactor test according Koa v2 middleware<commit_after>
var request = require('supertest')
var views = require('../')
var should = require('should')
var Koa = require('koa')

describe('koa-views', function () {
  it('have a render method', function (done) {
    var app = new Koa()
    .use(views())
    .use(function (ctx) {
      ctx.render.should.ok
      ctx.render.should.Function
    })

    request(app.listen()).get('/')
      .expect(404, done)
  })

  it('default to html', function (done) {
    var app = new Koa()
    .use(views(__dirname))
    .use(function (ctx) {
      return ctx.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:html/)
      .expect(200, done)
  })

  it('default to [ext] if a default engine is set', function (done) {
    var app = new Koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function (ctx) {
      return ctx.render('./fixtures/basic')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('set and render state', function (done) {
    var app = new Koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function (ctx) {
      ctx.state.engine = 'jade'
      return ctx.render('./fixtures/global-state')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  // #25
  it('works with circular references in state', function (done) {
    var app = new Koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function (ctx) {
      ctx.state = {
        a: {},
        app: app
      }

      ctx.state.a.a = ctx.state.a

      return ctx.render('./fixtures/global-state', {
        app: app,
        b: this.state,
        engine: 'jade'
      })
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('`map` given `engine` to given file `ext`', function (done) {
    var app = new Koa()
    .use(views(__dirname, { map: {html: 'underscore'} }))
    .use(function (ctx) {
      ctx.state.engine = 'underscore'
      return ctx.render('./fixtures/underscore')
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:underscore/)
      .expect(200, done)
  })

  it('merges global and local state ', function (done) {
    var app = new Koa()
    .use(views(__dirname, { extension: 'jade' }))
    .use(function (ctx) {
      ctx.state.engine = 'jade'

      return ctx.render('./fixtures/state', {
        type: 'basic'
      })
    })

    request(app.listen()).get('/')
      .expect('Content-Type', /html/)
      .expect(/basic:jade/)
      .expect(200, done)
  })

  it('call to the next middleware if this.render is already defined', function (done) {
    var app = new Koa()
    .use(function (ctx, next) {
      ctx.render = true
      return next()
    })
    .use(views())
    .use(function (ctx) {
      ctx.body = 'hello'
    })

    request(app.listen()).get('/')
      .expect('hello')
      .expect(200, done)
  })

  // #23 && #27
  it('given a directory it should try to require index.[ext]', function (done) {
    var app = new Koa()
    .use(views(__dirname))
    .use(function (ctx) {
      return ctx.render('./fixtures')
    })

    request(app.listen()).get('/')
      .expect(/defaults-to-index/)
      .expect(200, done)
  })

  // #43
  it('it should not overwrite an extension when given one', function (done) {
    var app = new Koa()
    .use(views(__dirname))
    .use(function (ctx) {
      return ctx.render('./fixtures/basic.ejs')
    })

    request(app.listen()).get('/')
      .expect(/basic:ejs/)
      .expect(200, done)
  })
})
<|endoftext|>


<commit_before>import test from 'tape';
import BinaryHeap from '../src';

test('should tell if empty', t => {
  t.plan(3);

  const heap = new BinaryHeap();

  t.ok(heap.isEmpty(), 'heap is empty');

  heap.push(1);

  t.notOk(heap.isEmpty(), 'heap is no longer empty');

  heap.pop();

  t.ok(heap.isEmpty(), 'heap is empty again');
});

test('should throws if trying to pop while empty', t => {
  t.plan(1);

  const heap = new BinaryHeap();

  t.throws(() => heap.pop(), Error, 'can\'t pop an empty heap');
});

test('should order values', t => {
  t.plan(1);

  const numbers = [];
  for(let i = 0; i < 100; i++) {
    numbers[i] = Math.random() * 100;
  }

  const sorted = numbers.sort((a, b) => a - b);

  const heap = new BinaryHeap();
  randomNumbers.forEach(n => heap.push(n));

  const result = [];
  while(!heap.isEmpty()) {
    result.push(heap.pop());
  }

  t.deepEqual(sorted, result);
});

test('should accept custom comparison function', t => {
  t.plan(1);

  class Node {
    constructor(weight) {
      this.weight = weight;
    }
  }

  const nodes = [];
  for(let i = 0; i < 100; i++) {
    nodes.push(new Node(Math.random() * 100));
  }

  const sorted = nodes.sort((a, b) => a.weight - b.weight);

  const heap = new BinaryHeap((a, b) => a.weight - b.weight);
  nodes.forEach(n => heap.push(n));

  const result = [];
  while(!heap.isEmpty()) {
    result.push(heap.pop());
  }

  t.deepEqual(sorted, result);
});

test('should be able to update a node', t => {
  t.plan(1);

  class Node {
    constructor(weight) {
      this.weight = weight;
    }
  }

  const heap = new BinaryHeap((a, b) => a.weight - b.weight);

  const node = new Node(100);

  heap.push(new Node(2));
  heap.push(node);
  heap.push(new Node(10));

  node.weight = 5;
  heap.update(node);

  const result = [];
  while(!heap.isEmpty()) {
    result.push(heap.pop());
  }

  const weights = result.map(n => n.weight);

  t.deepEqual(weights, [2, 5, 100], 'node was correctly updated');
});
<commit_msg>update tests<commit_after>import test from 'tape';
import BinaryHeap from '../src';

test('should tell if empty', t => {
  t.plan(3);

  const heap = new BinaryHeap();

  t.equal(heap.isEmpty(), true, 'heap is empty');

  heap.push(1);

  t.equal(heap.isEmpty(), false, 'heap is no longer empty');

  heap.pop();

  t.equal(heap.isEmpty(), true, 'heap is empty again');
});

test('should throws if trying to pop while empty', t => {
  t.plan(1);

  const heap = new BinaryHeap();

  t.throws(() => heap.pop(), Error, 'can\'t pop an empty heap');
});

test('should order values', t => {
  t.plan(1);

  const sampleSize = 10;

  const numbers = [];
  for(let i = 0; i < sampleSize; i++) {
    numbers[i] = Math.random() * 100;
  }

  const sorted = numbers.sort((a, b) => a - b);

  const heap = new BinaryHeap();
  numbers.forEach(n => heap.push(n));

  let i = 0;
  const result = [];
  while(!heap.isEmpty()) {
    if(i++ > sampleSize) break;
    result.push(heap.pop());
  }

  t.deepEqual(sorted, result);
});

test('should accept custom comparison function', t => {
  t.plan(1);

  const sampleSize = 10;

  class Node {
    constructor(weight) {
      this.weight = weight;
    }
  }

  const nodes = [];
  for(let i = 0; i < sampleSize; i++) {
    nodes.push(new Node(Math.random() * 100));
  }

  const sorted = nodes.sort((a, b) => a.weight - b.weight);

  const heap = new BinaryHeap((a, b) => a.weight - b.weight);
  nodes.forEach(n => heap.push(n));

  let i = 0;

  const result = [];
  while(!heap.isEmpty()) {
    if(i++ > sampleSize) break;
    result.push(heap.pop());
  }

  t.deepEqual(sorted, result);
});

test('should be able to update a node', t => {
  t.plan(1);

  class Node {
    constructor(weight) {
      this.weight = weight;
    }
  }

  const heap = new BinaryHeap((a, b) => a.weight - b.weight);

  const node = new Node(100);

  heap.push(new Node(2));
  heap.push(node);
  heap.push(new Node(10));

  node.weight = 5;
  heap.update(node);

  let i = 0;
  const result = [];
  while(!heap.isEmpty()) {
    if(i++ > 3) break;
    result.push(heap.pop());
  }

  const weights = result.map(n => n.weight);

  t.deepEqual(weights, [2, 5, 100], 'node was correctly updated');
});
<|endoftext|>


<commit_before>/* global describe:true, it:true, before:true, beforeEach:true, afterEach:true */
import assert from 'assert';
import Rekapi from '../src/main';
import { contains } from 'lodash';

describe('Rekapi', () => {
  const setupTestRekapi = () => new Rekapi();

  const setupTestActor = (rekapi, actorArgs) =>
    rekapi.addActor(new Rekapi.Actor(actorArgs)
  );

  let rekapi, actor;

  beforeEach(() => {
    rekapi = setupTestRekapi();
    actor = setupTestActor(rekapi);
  });

  afterEach(() => {
    rekapi = undefined;
    actor = undefined;
  });

  describe('constructor', () => {
    it('is a function', () => {
      assert.equal(typeof Rekapi, 'function');
    });
  });

  describe('#addActor', () => {
    it('adds actors', () => {
      assert.equal(rekapi._actors[actor.id], actor);
    });

    it('only adds actors once', () => {
      rekapi.addActor(actor);
      assert.equal(rekapi.getActorCount(), 1);
    });

    it('propagates arguments to instantiated actor', () => {
      const actorContext = {};
      rekapi = setupTestRekapi();
      actor = setupTestActor(rekapi, { context: actorContext });

      assert(actor instanceof Rekapi.Actor);
      assert.equal(actorContext, actor.context);
    });
  });

  describe('#getActor', () => {
    it('retrieves added actor', () => {
      assert.equal(rekapi.getActor(actor.id), actor);
    });
  });

  describe('#removeActor', () => {
    it('removes an actor', () => {
      rekapi.removeActor(actor);

      assert.equal(rekapi._actors[actor.id], undefined);

      // FIXME: This needs to be moved to canvas renderer tests
      //assert.equal(rekapi._renderOrder.indexOf(actor.id), -1);
    });
  });

  describe('removeAllActors', () => {
    it('removes all actors', () => {
      setupTestActor(rekapi);
      const removedActors = rekapi.removeAllActors();

      assert.equal(Object.keys(rekapi._actors).length, 0);
      assert.equal(
        removedActors.filter(actor => actor instanceof Rekapi.Actor).length,
        2
      );
    });
  });

  describe('#getActorIds', () => {
    it('gets actor ids', () => {
      const actor2 = setupTestActor(rekapi);
      const ids = rekapi.getActorIds();

      assert.equal(ids.length, 2);
      assert(contains(ids, actor.id));
      assert(contains(ids, actor2.id));
    });
  });
});
<commit_msg>Port getAllActorsTest<commit_after>/* global describe:true, it:true, before:true, beforeEach:true, afterEach:true */
import assert from 'assert';
import Rekapi from '../src/main';
import { contains } from 'lodash';

describe('Rekapi', () => {
  const setupTestRekapi = () => new Rekapi();

  const setupTestActor = (rekapi, actorArgs) =>
    rekapi.addActor(new Rekapi.Actor(actorArgs)
  );

  let rekapi, actor, actor2;

  beforeEach(() => {
    rekapi = setupTestRekapi();
    actor = setupTestActor(rekapi);
  });

  afterEach(() => {
    rekapi = undefined;
    actor = undefined;
  });

  describe('constructor', () => {
    it('is a function', () => {
      assert.equal(typeof Rekapi, 'function');
    });
  });

  describe('#addActor', () => {
    it('adds actors', () => {
      assert.equal(rekapi._actors[actor.id], actor);
    });

    it('only adds actors once', () => {
      rekapi.addActor(actor);
      assert.equal(rekapi.getActorCount(), 1);
    });

    it('propagates arguments to instantiated actor', () => {
      const actorContext = {};
      rekapi = setupTestRekapi();
      actor = setupTestActor(rekapi, { context: actorContext });

      assert(actor instanceof Rekapi.Actor);
      assert.equal(actorContext, actor.context);
    });
  });

  describe('#getActor', () => {
    it('retrieves added actor', () => {
      assert.equal(rekapi.getActor(actor.id), actor);
    });
  });

  describe('#removeActor', () => {
    it('removes an actor', () => {
      rekapi.removeActor(actor);

      assert.equal(rekapi._actors[actor.id], undefined);

      // FIXME: This needs to be moved to canvas renderer tests
      //assert.equal(rekapi._renderOrder.indexOf(actor.id), -1);
    });
  });

  describe('removeAllActors', () => {
    it('removes all actors', () => {
      setupTestActor(rekapi);
      const removedActors = rekapi.removeAllActors();

      assert.equal(Object.keys(rekapi._actors).length, 0);
      assert.equal(
        removedActors.filter(actor => actor instanceof Rekapi.Actor).length,
        2
      );
    });
  });

  describe('#getActorIds', () => {
    it('gets actor ids', () => {
      actor2 = setupTestActor(rekapi);
      const ids = rekapi.getActorIds();

      assert.equal(ids.length, 2);
      assert(contains(ids, actor.id));
      assert(contains(ids, actor2.id));
    });
  });

  describe('#getAllActors', () => {
    it('gets all actors', () => {
      actor2 = setupTestActor(rekapi);
      const actors = rekapi.getAllActors();

      assert.equal(actors[actor.id], actor);
      assert.equal(actors[actor2.id], actor2);
    });

  });
});
<|endoftext|>


<commit_before>'use strict()';

process.env.NODE_ENV = 'test';

var assert = require('assert'),
		expect = require('chai').expect,
		autostart = require('../lib/index.js');

describe('Arguments', function() {
	it('should not accept too few arguments', function() {
		expect(autostart.enableAutostart('someString', 'anotherString', 'stillAString')).to.equal(1);
		expect(autostart.disableAutostart('someString')).to.equal(1);
		expect(autostart.isAutostartEnabled('someString')).to.equal(1);
	});

	it('should not accept arguments with wrong types', function() {
		expect(autostart.enableAutostart(1, 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 'string', 4)).to.equal(1);
		expect(autostart.disableAutostart(1, 2)).to.equal(1);
		expect(autostart.disableAutostart('string', 2)).to.equal(1);
		expect(autostart.isAutostartEnabled(1, 2)).to.equal(1);
		expect(autostart.isAutostartEnabled('string', 2)).to.equal(1);
	});
});

describe('Checks', function() {
	it('should respond with isEnabled=false and not throw for fake service', function() {
		autostart.isAutostartEnabled('test', function(isEnabled, error) {
	    if (error !== null) {
	      err = error;
	      callback(err);
	      return 1;
	    }

			expect(isEnabled).to.equal(false);
			expect(error).to.equal(null);
		});
	});
});
<commit_msg>Repaired testing<commit_after>'use strict()';

process.env.NODE_ENV = 'test';

var assert = require('assert'),
		expect = require('chai').expect,
		autostart = require('../lib/index.js');

describe('Arguments', function() {
	it('should not accept too few arguments', function() {
		expect(autostart.enableAutostart('someString', 'anotherString', 'stillAString')).to.equal(1);
		expect(autostart.disableAutostart('someString')).to.equal(1);
		expect(autostart.isAutostartEnabled('someString')).to.equal(1);
	});

	it('should not accept arguments with wrong types', function() {
		expect(autostart.enableAutostart(1, 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 'string', 4)).to.equal(1);
		expect(autostart.disableAutostart(1, 2)).to.equal(1);
		expect(autostart.disableAutostart('string', 2)).to.equal(1);
		expect(autostart.isAutostartEnabled(1, 2)).to.equal(1);
		expect(autostart.isAutostartEnabled('string', 2)).to.equal(1);
	});
});

describe('Checks', function() {
	it('should respond with isEnabled=false and not throw for fake service', function() {
		autostart.isAutostartEnabled('test', function(isEnabled, error) {
			expect(isEnabled).to.equal(false);
			expect(error).to.equal(null);
		});
	});
});
<|endoftext|>


<commit_before>"use strict";

var fs      = require('fs');
var path    = require('path');
var expect  = require('chai').expect();
var should  = require('chai').should();
var pdf2img = require('../index.js');

var input   = __dirname + path.sep + 'test.pdf';

pdf2img.setOptions({
  outputdir: __dirname + path.sep + '/output',
  outputname: 'test'
});

describe('Split and convert pdf into images', function() {
  it ('Create jpg files', function(done) {
    this.timeout(100000);
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        var n = 1;
        info.message.forEach(function(file) {
          file.page.should.equal(n);
          file.name.should.equal('test_' + n + '.jpg');
          isFileExists(file.path).should.to.be.true;
          if (n === 3) done();
          n++;
        });
      }
    });
  });
  it ('Create png files', function(done) {
    this.timeout(100000);
    pdf2img.setOptions({ type: 'png' });
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        var n = 1;
        info.message.forEach(function(file) {
          file.page.should.equal(n);
          file.name.should.equal('test_' + n + '.png');
          isFileExists(file.path).should.to.be.true;
          if (n === 3) done();
          n++;
        });
      }
    });
  });
  it ('Create jpg file only for given page', function(done) {
    this.timeout(100000);
    pdf2img.setOptions({ type: 'jpg', page: 1 });
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        info.message.length.should.equal(1)
        var file = info.message[0];
        file.page.should.equal(1);
        file.name.should.equal('test_1.jpg');
        isFileExists(file.path).should.to.be.true;
        done();
      }
    });
  });
  it ('Create png file only for given page', function(done) {
    this.timeout(100000);
    pdf2img.setOptions({ type: 'png', page: 2 });
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        info.message.length.should.equal(1)
        var file = info.message[0];
        file.page.should.equal(2);
        file.name.should.equal('test_2.png');
        isFileExists(file.path).should.to.be.true;
        done();
      }
    });
  });
});

var isFileExists = function(path) {
  try {
    return fs.statSync(path).isFile();
  } catch (e) {
    return false;
  }
}
<commit_msg>Test passing quality for jpg compression<commit_after>"use strict";

var fs      = require('fs');
var path    = require('path');
var expect  = require('chai').expect();
var should  = require('chai').should();
var pdf2img = require('../index.js');

var input   = __dirname + path.sep + 'test.pdf';

describe('Split and convert pdf into images', function() {
  it ('Create jpg files', function(done) {
    this.timeout(100000);
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        var n = 1;
        info.message.forEach(function(file) {
          file.page.should.equal(n);
          file.name.should.equal('test_' + n + '.jpg');
          isFileExists(file.path).should.to.be.true;
          if (n === 3) done();
          n++;
        });
      }
    });
  });
  it ('Create png files', function(done) {
    this.timeout(100000);
    pdf2img.setOptions({ type: 'png' });
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        var n = 1;
        info.message.forEach(function(file) {
          file.page.should.equal(n);
          file.name.should.equal('test_' + n + '.png');
          isFileExists(file.path).should.to.be.true;
          if (n === 3) done();
          n++;
        });
      }
    });
  });
  it ('Create jpg file only for given page', function(done) {
    this.timeout(100000);
    pdf2img.setOptions({ type: 'jpg', page: 1 });
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        info.message.length.should.equal(1)
        var file = info.message[0];
        file.page.should.equal(1);
        file.name.should.equal('test_1.jpg');
        isFileExists(file.path).should.to.be.true;
        done();
      }
    });
  });
  it ('Create png file only for given page', function(done) {
    this.timeout(100000);
    pdf2img.setOptions({ type: 'png', page: 2 });
    pdf2img.convert(input, function(err, info) {
      if (info.result !== 'success') {
        info.result.should.equal('success');
        done();
      } else {
        info.message.length.should.equal(1)
        var file = info.message[0];
        file.page.should.equal(2);
        file.name.should.equal('test_2.png');
        isFileExists(file.path).should.to.be.true;
        done();
      }
    });
  });
  it ('Can pass quality to jpg files', function(done) {
    this.timeout(100000);
    pdf2img.setOptions({ type: 'jpg', page: 2 });
    pdf2img.convert(input, function(err, info) {
      var file1Info = info;
      pdf2img.setOptions({ quality: 60 });
      pdf2img.convert(input, function(err, info) {
        var file2Info = info;
        file1Info.message[0].size.should.gt(file2Info.message[0].size);
        done();
      });
    });
  });
});

var isFileExists = function(path) {
  try {
    return fs.statSync(path).isFile();
  } catch (e) {
    return false;
  }
}
<|endoftext|>


<commit_before>
var tape = require('tape')
var level = require('level-test')()
var sub = require('level-sublevel')
var ContentCache = require('../')

/*
Code Paths

key is in cache
key is not in cache
key is in cache but it's expired or fresh explicitly requested
  - retrived but not changed
  - retrived and changed

*/

var data = {
  foo: 'bar.sasas',
  blah: 'bbbbbbbbb'

}

var db = sub(level('test-content-cache', {encoding: 'json'}))
var get = ContentCache(db, 'cache', {
  encoding: 'utf8',
  getter: function (key, meta, cb) {
    //... okay what should I test this with?
    if(data[key]) {
      console.error('GET', key)
      cb(null, data[key])
    } else {
      console.error('GET', key, 'ERROR - Not Found')
      cb(new Error('not found'))
    }
  }
})

tape('simple', function (t) {

  // non cached
  get('foo', function (err, content, meta) {
    console.log('RESULT', content, meta)

    t.equal(content, data.foo)
    t.notOk(meta.cached, 'was cached')
    t.ok(meta.fetched, 'was fetched')
    get('foo', function (err, content, meta) {
      t.equal(content, data.foo)
      t.ok(meta.cached, 'was cached')
      t.notOk(meta.fetched, 'was fetched')

      get('foo', {fetch: true}, function (err, content, meta) {
        t.equal(content, data.foo)
        t.ok(meta.cached, 'was cached')
        t.ok(meta.fetched, 'was fetched')

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

tape('age', function (t) {
  get('blah', function (err, content, meta) {
    t.equal(content, data.blah)
      t.ok(meta.fetched)
      t.notOk(meta.cached)
    get('blah', {age: 0}, function (err, content, meta) {
      t.ok(meta.fetched)
      t.ok(meta.cached)
      t.end()
    })
  })

})
<commit_msg>test concurrent fetches<commit_after>
var tape = require('tape')
var level = require('level-test')()
var sub = require('level-sublevel')
var ContentCache = require('../')

/*
Code Paths

key is in cache
key is not in cache
key is in cache but it's expired or fresh explicitly requested
  - retrived but not changed
  - retrived and changed

*/

var data = {
  foo: 'bar.sasas',
  blah: 'bbbbbbbbb'

}

var db = sub(level('test-content-cache', {encoding: 'json'}))
var count = 0
var get = ContentCache(db, 'cache', {
  encoding: 'utf8',
  getter: function (key, meta, cb) {
    //... okay what should I test this with?
    count ++
    process.nextTick(function () {
      if(data[key]) {
        console.error('GET', key)
        cb(null, data[key])
      } else {
        console.error('GET', key, 'ERROR - Not Found')
        cb(new Error('not found'))
      }
    })
  }
})

tape('simple', function (t) {

  // non cached
  get('foo', function (err, content, meta) {
    console.log('RESULT', content, meta)

    t.equal(content, data.foo)
    t.notOk(meta.cached, 'was cached')
    t.ok(meta.fetched, 'was fetched')
    get('foo', function (err, content, meta) {
      t.equal(content, data.foo)
      t.ok(meta.cached, 'was cached')
      t.notOk(meta.fetched, 'was fetched')

      get('foo', {fetch: true}, function (err, content, meta) {
        t.equal(content, data.foo)
        t.ok(meta.cached, 'was cached')
        t.ok(meta.fetched, 'was fetched')

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

tape('age', function (t) {
  get('blah', function (err, content, meta) {
    t.equal(content, data.blah)
      t.ok(meta.fetched)
      t.notOk(meta.cached)
    get('blah', {age: 0}, function (err, content, meta) {
      t.ok(meta.fetched)
      t.ok(meta.cached)
      t.end()
    })
  })

})

tape('concurrent fetch', function (t) {
  var _count = count
  var n = 2, a, b
  get('blah', {fetch: true}, function (err, content, meta) {
    a = content
    t.equal(count, _count + 1); next()
  })
  get('blah', {fetch: true}, function (err, content, meta) {
    b = content
    t.equal(count, _count + 1); next()
  })

  function next () {
    if(--n) return
    //these should be exactly the same object.
    t.strictEqual(a, b)
    t.end()
  }
})
<|endoftext|>


<commit_before>// Dependencies
var Debug = require("../index");

Debug._config.logLevel = 4;

// Test defaults
Debug
  .log("A fancy error message", "error")
  .log("Info messages are useful", "info")
  .log("Hey, you've got a warning", "warn")
  ;

// Don't show date
Debug._config.displayDate = false;
Debug.log("Display date is disabled.", "info");

// Custom type
Debug._config.myType = {
    color: [0, 255, 200]
  , text: "CUSTOM"
};

Debug.log("This is a custom message type", "myType");
<commit_msg>Lowercase message texts<commit_after>// Dependencies
var Debug = require("../index");

Debug._config.logLevel = 4;

// Test defaults
Debug
  .log("A fancy error message", "error")
  .log("Info messages are useful", "info")
  .log("Hey, you've got a warning", "warn")
  ;

// Don't show date
Debug._config.displayDate = false;
Debug.log("Display date is disabled.", "info");

// Custom type
Debug._config.myType = {
    color: [0, 255, 200]
  , text: "custom"
};

Debug.log("This is a custom message type", "myType");
<|endoftext|>


<commit_before>var ML = require('../lib');
var Lab = require('lab');
var Code = require('code');
var Async = require('async');
var Batch = require('../lib/batchLayer');
var mongo = require('../lib/mongo');

// Declare internals
var internals = {};
// Test shortcuts
var lab = exports.lab = Lab.script();
var before = lab.before;
var beforeEach = lab.beforeEach;
var after = lab.after;
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;

var testReports = internals.testReports = [{
        name: "report1",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report2",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report3",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report4",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
}];

internals.scrubMaster = function(next) {
    mongo.db.collection('master').remove({}, function(err, noDocs) {
        expect(err).to.not.exist();
        next(err);
    })
}

internals.scrubSpeed = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_delta').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

internals.scrubBatches = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_batches').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

describe('Mongo Lambda API', function () {

    var config = {
        host: 'localhost',
        port: 27017,
        db: 'mongo-lambda-test',
        masterColl: "master"
    };

    beforeEach(function(done) {
        Async.series({
            insertReports: Async.apply(Batch.insertReports, testReports),
            mongoInit: Async.apply(mongo.init, config),
            scrubMaster: internals.scrubMaster,
            scrubSpeed: internals.scrubSpeed,
            scrubBatches: internals.scrubBatches
        }, function(err, results) {
            expect(err).to.not.exist();
            done();
        });
    });

    it('validates good configuration', function (done) {
        var instance = function () {
            var lambda = new ML.Lambda(config);
        };
        expect(instance).to.not.throw();
        done()
    });

    it('invalidates bad configuration', function (done) {
        var badConfig = {};
        var instance = function () {
            var lambda = new ML.Lambda(badConfig);
        };
        expect(instance).to.throw();
        done()
    });

    it('can start', function (done) {
        var start = function () {
            var lambda = new ML.Lambda(config);

            lambda.reports([testReports[0]]);

            lambda.start(function() {})
        };
        expect(start).to.not.throw();
        done();
    });

    it('inserts data into master collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[1]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.master.find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('inserts data into speed collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[2]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.speed['report3'].find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('gets bactches and live data', { timeout: 7000}, function (done) {
        var lambda = new ML.Lambda(config);
        lambda.reports([testReports[3]]);

        lambda.start(function() {
            //Drip data
            var i = 0;
            setInterval(function() {
                console.log(new Date());
                lambda.insert({ua: "iphone"}, function(err, results) {

                    console.log(' imp!');
                    console.log('---------------------');

                    lambda.getResults('report4', {}, function(err, batches, onTheFly) {
                        i++;
                        // expect(err).to.not.exist();
                        var total = 0;

                        batches.forEach(function(batch) {
                            if (batch.data.length > 0) {
                                total = total + batch.data[0].count;
                            }

                        })
                        console.log('batch layer: '+ total)

                        if(onTheFly.length > 0) {
                            console.log('speed layer: '+ onTheFly[0].count)
                            total = total + onTheFly[0].count;
                        }

                        console.log('---------------------');
                        console.log('TOTAL COUNT: '+total)
                        console.log('---------------------\n');
                        // console.log(new Date());

                        expect(total).to.equal(i);
                    });

                });
            }, 1000);

            setTimeout(function() {
                done();
            }, 6500);

        })
    });

});
<commit_msg>fixed up tests<commit_after>var ML = require('../lib');
var Lab = require('lab');
var Code = require('code');
var Async = require('async');
var Batch = require('../lib/batchLayer');
var mongo = require('../lib/mongo');

// Declare internals
var internals = {};
// Test shortcuts
var lab = exports.lab = Lab.script();
var before = lab.before;
var beforeEach = lab.beforeEach;
var after = lab.after;
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;

var testReports = internals.testReports = [{
        name: "report1",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report2",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report3",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report4",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
}];

internals.scrubMaster = function(next) {
    mongo.db.collection('master').remove({}, function(err, noDocs) {
        expect(err).to.not.exist();
        next(err);
    })
}

internals.scrubSpeed = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_delta').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

internals.scrubBatches = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_batches').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

describe('Mongo Lambda API', function () {

    var config = {
        host: 'localhost',
        port: 27017,
        db: 'mongo-lambda-test',
        masterColl: "master"
    };

    beforeEach(function(done) {
        Async.series({
            insertReports: Async.apply(Batch.insertReports, testReports),
            mongoInit: Async.apply(mongo.init, config),
            scrubMaster: internals.scrubMaster,
            scrubSpeed: internals.scrubSpeed,
            scrubBatches: internals.scrubBatches
        }, function(err, results) {
            expect(err).to.not.exist();
            done();
        });
    });

    it('validates good configuration', function (done) {
        var instance = function () {
            var lambda = new ML.Lambda(config);
        };
        expect(instance).to.not.throw();
        done()
    });

    it('invalidates bad configuration', function (done) {
        var badConfig = {};
        var instance = function () {
            var lambda = new ML.Lambda(badConfig);
        };
        expect(instance).to.throw();
        done()
    });

    it('can start', function (done) {
        var start = function () {
            var lambda = new ML.Lambda(config);

            lambda.reports([testReports[0]]);

            lambda.start(function() {})
        };
        expect(start).to.not.throw();
        done();
    });

    it('inserts data into master collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[1]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.master.find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('inserts data into speed collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[2]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.speed['report3'].find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('gets bactches and live data', { timeout: 7000}, function (done) {
        var lambda = new ML.Lambda(config);
        lambda.reports([testReports[3]]);

        lambda.start(function() {
            //Drip data
            var i = 0;
            setInterval(function() {
                lambda.insert({ua: "iphone"}, function(err, results) {

                    // console.log(' imp!');
                    // console.log('---------------------');

                    lambda.getResults('report4', {}, function(err, batches, onTheFly) {
                        i++;
                        // expect(err).to.not.exist();
                        var total = 0;

                        batches.forEach(function(batch) {
                            if (batch.data.length > 0) {
                                total = total + batch.data[0].count;
                            }

                        })
                        console.log('batch layer: '+ total)

                        if(onTheFly.length > 0) {
                            console.log('speed layer: '+ onTheFly[0].count)
                            total = total + onTheFly[0].count;
                        }

                        // console.log('---------------------');
                        // console.log('TOTAL COUNT: '+total)
                        // console.log('---------------------\n');
                        // console.log(new Date());

                        expect(total).to.equal(i);
                    });

                });
            }, 1000);

            setTimeout(function() {
                done();
            }, 6500);

        })
    });

});
<|endoftext|>


<commit_before>var CustomElementRegistry = function () {};

CustomElementRegistry.prototype.define = function (tag, constructor) {
  console.warn ('WHAT THE FUCK THIS WORKED FOR IE!!!!')
  console.warn ('tag:', tag)
  console.warn ('class definition:', constructor)
};

// WHATWG Custom Elements Spec - https://html.spec.whatwg.org/multipage/custom-elements.htm

window.customElements
  = window.customElements
  || CustomElementRegistry

(new window.customElements).define ('foo-bar')
var HTMLLinkElement = function

  // http://w3c.github.io/webcomponents/spec/imports/#h-interface-import

(tag) {

  var
    evt = new Event ('load')

  , target = document.querySelector // use CSS :any ?
      ('link[href*='+tag+'][rel=import]')

  // https://github.com/webcomponents/html-imports#htmlimports
  ;(evt.target = target)
    && window.HTMLImports
    && !!! window.HTMLImports.useNative
    && HTMLImports.whenReady ( function (_) { return target.dispatchEvent (evt); } ) // eww

  return target
}

var TokenList = function (node) {

  this
    .sift (node)
    .map(this.tokenize, this)
};

TokenList.prototype.tokenize = function (node) {
    var this$1 = this;

  var
    insert = function (node) { return function (symbol) { return (this$1 [symbol] = this$1 [symbol] || []).push (node); }; }

  void (node.text = node.textContent)
    .match (/([^{]*?)(\w|#)(?=\})/g)
    .map (insert (node))
};

TokenList.prototype.sift = function (node) {

  var
    nodes = []
  , expression = /{(\w+|#)}/

  , visit = function (node) { return node.nodeType === Node.TEXT_NODE
        ? TEXT_NODE (node)
        : ELEMENT_NODE (node.attributes)
      && NodeFilter.FILTER_REJECT; } // We don't need 'em

  , TEXT_NODE = function (node) { return expression.test (node.textContent)
      && nodes.push (node); }

  , ELEMENT_NODE = function (attrs) { return Array
        .from (attrs)
        .map(function (attr) { return expression.test (attr.value) && nodes.push (attr); }); }

  , walker =
      document.createNodeIterator
        (node, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, visit)
        // by default breaks on template YAY! 🎉

  while (walker.nextNode ()) { 0 } // Walk all nodes and do nothing.

  return nodes
};

TokenList.prototype.bind = function (context) {
    var this$1 = this;

  var
    keys = Object.keys (this)

  , reset = function (symbol) { return this$1 [symbol].map
        (function (node) { return (node.textContent = node.text) && symbol; }); }

  , replace =
      function (symbol, token) {
            if ( token === void 0 ) token = '{'+symbol+'}';

            return function (item) { return (item.textContent = item.textContent.replace (token, context [symbol])); };
    }

  keys.map (reset)

  for (var symbol$1 in this$1)
    { this$1 [symbol$1]
      .map (replace (symbol$1)) }
};

// INTERESTING! Converting `Template` to a class increases size by ~16 octets

var Template = HTMLTemplateElement = function (template) {

  template =
    (typeof template == 'string')
      ? document.querySelector ('template[name='+template+']')
      : template

  // create shallow clone using `.getOwnPropertyDescriptors`
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors#Examples
  // https://docs.microsoft.com/en-us/scripting/javascript/reference/object-getownpropertydescriptor-function-javascript
  // NO IE SUPPORT!!!!
  return Object.assign (template, { bind: bind } )

  function bind (context) {

    var
      html     = ''
    , template = this.innerHTML
    , contexts =
        (ref = []).concat.apply ( ref, [context] )
        // https://dom.spec.whatwg.org/#converting-nodes-into-a-node

    , keys =
        Object
          .keys (contexts [0] || [])    // memoize keys
          .concat (['#', 'self']) // add helper keys

    , tokens   = keys.map (function (key) { return '{'+key+'}'; }) // memoize tokens
    , fragment = document.createElement ('template')

    , deposit = function (context, index) {
        var clone = template

        context = (typeof context  === 'object')
          ? context : { self: context }

        context ['#'] = index

        for (var i=0; i<tokens.length; i++)
          { clone = clone
            .split (tokens [i])
            .join  (context [keys [i]]) }

        return clone
      }

    void (this.dependents || [])
      .map (function (dependent) { return dependent.remove (); })

    for (var i=0, final = ''; i<contexts.length; i++)
      { html += deposit (contexts [i], i) }

    fragment.innerHTML = html

    this.dependents = Array.from // non-live
      (fragment.content.childNodes)

    (ref$1 = this).after.apply ( ref$1, this.dependents )
    var ref;
    var ref$1;
  }
}
var EventTarget = function (HTMLElement) { return ((function (HTMLElement) {
    function anonymous () {
      HTMLElement.apply(this, arguments);
    }

    if ( HTMLElement ) anonymous.__proto__ = HTMLElement;
    anonymous.prototype = Object.create( HTMLElement && HTMLElement.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.on = function ( event, handler ) {

    this.addEventListener
      (event, this.renderable (handler))
  };

  anonymous.prototype.renderable = function ( handler ) {
    var this$1 = this;

    return function (event, render) {
        if ( render === void 0 ) render = true;

        return (event.prevent = function (_) { return (render = false) && event.preventDefault (); })

      && handler.call (this$1, event) !== false // for `return false`

      && render && this$1.render ();
    } // check render availability
  };

    return anonymous;
  }(HTMLElement))); }

var ParentNode = function (Element) { return ((function (Element) {
    function anonymous () {
      Element.apply(this, arguments);
    }

    if ( Element ) anonymous.__proto__ = Element;
    anonymous.prototype = Object.create( Element && Element.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.selectAll = function ( fragments ) {
    var tokens = [], len = arguments.length - 1;
    while ( len-- > 0 ) tokens[ len ] = arguments[ len + 1 ];

    fragments =
      (ref = []).concat.apply ( ref, [fragments] )

    var
      zip = function (selector, token) { return selector + token + fragments.shift (); }

    return Array
      .from
        (this.querySelectorAll
          (tokens.reduce (zip, fragments.shift ())))
    var ref;
  };

  anonymous.prototype.select = function ()
    // watch out for clobbering `HTMLInputElement.select ()`
    // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
    {
    var selector = [], len = arguments.length;
    while ( len-- ) selector[ len ] = arguments[ len ];
 return (ref = this).selectAll.apply ( ref, selector ) [0]
    var ref; };

    return anonymous;
  }(Element))); }

//function comb
//  // ElementTraversal interface
//  // https://www.w3.org/TR/ElementTraversal/#interface-elementTraversal
//
//(parent) {
//  if (parent.hasChildNodes())
//    for (let node = parent.firstChild; node; node = node.nextSibling)
//      comb (node)
//}

var GlobalEventHandlers = function (Element) { return ((function (Element) {
    function anonymous () {
      Element.apply(this, arguments);
    }

    if ( Element ) anonymous.__proto__ = Element;
    anonymous.prototype = Object.create( Element && Element.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.onconnect = function (event, target) {

    (target = event.target)
      && this.mirror (target.import.querySelector ('template'))

    Element.prototype.onconnect
      && Element.prototype.onconnect.call (this)

    this.tokens = new TokenList (this)
    this.render ()
  };

  // Reflection - https://en.wikipedia.org/wiki/Reflection_(computer_programming)
  // Type Introspection - https://en.wikipedia.org/wiki/Type_introspection
  //
  // In computing, type introspection is the ability of a program
  // to examine the type or properties of an object at runtime.
  // Some programming languages possess this capability.
  //
  // Introspection should not be confused with reflection,
  // which goes a step further and is the ability for a program to manipulate the values,
  // meta-data, properties and/or functions of an object at runtime.

  anonymous.prototype.reflect = function (handler, event) {
    ( event = ( handler.match (/^on(.+)$/) || [] ) [1] )

    && Object.keys // ensure W3C on event
     ( HTMLElement.prototype )
       .includes ( handler )

    && this.on (event, this [handler])
  };

  anonymous.prototype.register = function (node) {
    var this$1 = this;

    var
      register = function (event, handler) { return (handler = /{\s*(\w+)\s*}/.exec (node [event]))

        && ( handler = this$1 [ (handler || []) [1] ] )
        && ( node [event] = this$1.renderable (handler) ); }

    Array
      .from (node.attributes)
      .map (function (attr) { return attr.name; })
      .filter (function (name) { return /^on/.test (name); })
      .map (register)
  };

    return anonymous;
  }(Element))); }

var Component = function (HTMLElement) { return ( (function (superclass) {
    function anonymous () {
  var this$1 = this;
 superclass.call (this)

    var
      descriptions =
        Object.getOwnPropertyDescriptors
          (HTMLElement.prototype)

    , bind = function (key) { return 'function' === typeof descriptions [key].value
        && (this$1 [key] = this$1 [key].bind (this$1)); }

    Object
      .keys (descriptions)
      .map (bind)

    Object
      .getOwnPropertyNames (HTMLElement.prototype)
      // POTENTIAL REDUNDANCY
      // Aren't `on` events set up in `.bind` on 20?
      // If so we are `.bind`ing to `this` on two iterations
      // of the same function
      .map (this.reflect, this)

    this.context = {}
    this.initialize && this.initialize ()
  }

    if ( superclass ) anonymous.__proto__ = superclass;
    anonymous.prototype = Object.create( superclass && superclass.prototype );
    anonymous.prototype.constructor = anonymous;

  anonymous.prototype.connectedCallback = function (link) {
    link = HTMLLinkElement
      (this.tagName.toLowerCase ())

    link
      ? link.addEventListener ('load', this.onconnect.bind (this))
      : this.onconnect (new Event ('load'))
  };

  anonymous.prototype.render = function () {
    var this$1 = this;

    this.tokens.bind (this)

    Array
      .from
        (this.selectAll ('template[name]'))

      .map
        (function (template) { return template.getAttribute ('name'); })

      .map
        (function (name) { return (new Template (name)).bind (this$1 [name]); })

    Array
      .from (this.selectAll ('*'))

      .concat ([this])

      .map (this.register, this)

    superclass.prototype.onidle && superclass.prototype.onidle.call (this)
  };

  anonymous.prototype.mirror = function (template, insert) {
    var this$1 = this;

    template = template.cloneNode (true)

    insert = function (replacement, name, slot) { return (name = replacement.getAttribute ('slot')) &&

      (slot = template.content.querySelector ('slot[name='+name+']'))
         // prefer to use replaceWith however support is sparse
         // https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
         // using `Node.parentNode` - https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode
         // & `Node.replaceChid` - https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
         // as is defined in (ancient) W3C DOM Level 1,2,3
         .parentNode
         .replaceChild (replacement, slot); }

    for (var i = 0, list = this$1.selectAll ('[slot]'); i < list.length; i += 1)
      {
      var replacement = list[i];

      insert (replacement)
    }

    Array
      .from (template.attributes)

      // skip swapping attribute if setting exists
      .filter (function (attr) { return !!! this$1.attributes [attr.name]; })

      .map  (function (attr) { return this$1.setAttribute (attr.name, attr.value); })

    this.innerHTML = template.innerHTML
  };

    return anonymous;
  }(( EventTarget ( ParentNode ( GlobalEventHandlers ( HTMLElement ))))))); }

var ElementPrototype = window.Element.prototype // see bottom of this file

var Element = function (tag) { return function (Element) { return (ref = window.customElements).define.apply
        ( ref, (ref$1 = []).concat.apply ( ref$1, [tag]).concat( [Component (Element)] ))
        var ref;
        var ref$1;; }; }

// Assign `window.Element.prototype` in case of feature checking on `Element`
Element.prototype = ElementPrototype
  // http://2ality.com/2013/09/window.html
  // http://tobyho.com/2013/03/13/window-prop-vs-global-var
  // https://github.com/webcomponents/webcomponentsjs/blob/master/webcomponents-es5-loader.js#L19

<commit_msg>:muscle: bump TRANSPILED distribution dist/snuggsi.js<commit_after>var CustomElementRegistry = function () {};

CustomElementRegistry.prototype.define = function (tag, constructor) {
  console.warn ('WHAT THE FUCK THIS WORKED FOR IE!!!!')
  console.warn ('tag:', tag)
  console.warn ('class definition:', constructor)
};

// WHATWG Custom Elements Spec - https://html.spec.whatwg.org/multipage/custom-elements.htm

window.customElements
  = window.customElements
  || CustomElementRegistry

void (new window.customElements).define ('foo-bar')
var HTMLLinkElement = function

  // http://w3c.github.io/webcomponents/spec/imports/#h-interface-import

(tag) {

  var
    evt = new Event ('load')

  , target = document.querySelector // use CSS :any ?
      ('link[href*='+tag+'][rel=import]')

  // https://github.com/webcomponents/html-imports#htmlimports
  ;(evt.target = target)
    && window.HTMLImports
    && !!! window.HTMLImports.useNative
    && HTMLImports.whenReady ( function (_) { return target.dispatchEvent (evt); } ) // eww

  return target
}

var TokenList = function (node) {

  this
    .sift (node)
    .map(this.tokenize, this)
};

TokenList.prototype.tokenize = function (node) {
    var this$1 = this;

  var
    insert = function (node) { return function (symbol) { return (this$1 [symbol] = this$1 [symbol] || []).push (node); }; }

  void (node.text = node.textContent)
    .match (/([^{]*?)(\w|#)(?=\})/g)
    .map (insert (node))
};

TokenList.prototype.sift = function (node) {

  var
    nodes = []
  , expression = /{(\w+|#)}/

  , visit = function (node) { return node.nodeType === Node.TEXT_NODE
        ? TEXT_NODE (node)
        : ELEMENT_NODE (node.attributes)
      && NodeFilter.FILTER_REJECT; } // We don't need 'em

  , TEXT_NODE = function (node) { return expression.test (node.textContent)
      && nodes.push (node); }

  , ELEMENT_NODE = function (attrs) { return Array
        .from (attrs)
        .map(function (attr) { return expression.test (attr.value) && nodes.push (attr); }); }

  , walker =
      document.createNodeIterator
        (node, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, visit)
        // by default breaks on template YAY! 🎉

  while (walker.nextNode ()) { 0 } // Walk all nodes and do nothing.

  return nodes
};

TokenList.prototype.bind = function (context) {
    var this$1 = this;

  var
    keys = Object.keys (this)

  , reset = function (symbol) { return this$1 [symbol].map
        (function (node) { return (node.textContent = node.text) && symbol; }); }

  , replace =
      function (symbol, token) {
            if ( token === void 0 ) token = '{'+symbol+'}';

            return function (item) { return (item.textContent = item.textContent.replace (token, context [symbol])); };
    }

  keys.map (reset)

  for (var symbol$1 in this$1)
    { this$1 [symbol$1]
      .map (replace (symbol$1)) }
};

// INTERESTING! Converting `Template` to a class increases size by ~16 octets

var Template = HTMLTemplateElement = function (template) {

  template =
    (typeof template == 'string')
      ? document.querySelector ('template[name='+template+']')
      : template

  // create shallow clone using `.getOwnPropertyDescriptors`
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors#Examples
  // https://docs.microsoft.com/en-us/scripting/javascript/reference/object-getownpropertydescriptor-function-javascript
  // NO IE SUPPORT!!!!
  return Object.assign (template, { bind: bind } )

  function bind (context) {

    var
      html     = ''
    , template = this.innerHTML
    , contexts =
        (ref = []).concat.apply ( ref, [context] )
        // https://dom.spec.whatwg.org/#converting-nodes-into-a-node

    , keys =
        Object
          .keys (contexts [0] || [])    // memoize keys
          .concat (['#', 'self']) // add helper keys

    , tokens   = keys.map (function (key) { return '{'+key+'}'; }) // memoize tokens
    , fragment = document.createElement ('template')

    , deposit = function (context, index) {
        var clone = template

        context = (typeof context  === 'object')
          ? context : { self: context }

        context ['#'] = index

        for (var i=0; i<tokens.length; i++)
          { clone = clone
            .split (tokens [i])
            .join  (context [keys [i]]) }

        return clone
      }

    void (this.dependents || [])
      .map (function (dependent) { return dependent.remove (); })

    for (var i=0, final = ''; i<contexts.length; i++)
      { html += deposit (contexts [i], i) }

    fragment.innerHTML = html

    this.dependents = Array.from // non-live
      (fragment.content.childNodes)

    (ref$1 = this).after.apply ( ref$1, this.dependents )
    var ref;
    var ref$1;
  }
}
var EventTarget = function (HTMLElement) { return ((function (HTMLElement) {
    function anonymous () {
      HTMLElement.apply(this, arguments);
    }

    if ( HTMLElement ) anonymous.__proto__ = HTMLElement;
    anonymous.prototype = Object.create( HTMLElement && HTMLElement.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.on = function ( event, handler ) {

    this.addEventListener
      (event, this.renderable (handler))
  };

  anonymous.prototype.renderable = function ( handler ) {
    var this$1 = this;

    return function (event, render) {
        if ( render === void 0 ) render = true;

        return (event.prevent = function (_) { return (render = false) && event.preventDefault (); })

      && handler.call (this$1, event) !== false // for `return false`

      && render && this$1.render ();
    } // check render availability
  };

    return anonymous;
  }(HTMLElement))); }

var ParentNode = function (Element) { return ((function (Element) {
    function anonymous () {
      Element.apply(this, arguments);
    }

    if ( Element ) anonymous.__proto__ = Element;
    anonymous.prototype = Object.create( Element && Element.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.selectAll = function ( fragments ) {
    var tokens = [], len = arguments.length - 1;
    while ( len-- > 0 ) tokens[ len ] = arguments[ len + 1 ];

    fragments =
      (ref = []).concat.apply ( ref, [fragments] )

    var
      zip = function (selector, token) { return selector + token + fragments.shift (); }

    return Array
      .from
        (this.querySelectorAll
          (tokens.reduce (zip, fragments.shift ())))
    var ref;
  };

  anonymous.prototype.select = function ()
    // watch out for clobbering `HTMLInputElement.select ()`
    // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
    {
    var selector = [], len = arguments.length;
    while ( len-- ) selector[ len ] = arguments[ len ];
 return (ref = this).selectAll.apply ( ref, selector ) [0]
    var ref; };

    return anonymous;
  }(Element))); }

//function comb
//  // ElementTraversal interface
//  // https://www.w3.org/TR/ElementTraversal/#interface-elementTraversal
//
//(parent) {
//  if (parent.hasChildNodes())
//    for (let node = parent.firstChild; node; node = node.nextSibling)
//      comb (node)
//}

var GlobalEventHandlers = function (Element) { return ((function (Element) {
    function anonymous () {
      Element.apply(this, arguments);
    }

    if ( Element ) anonymous.__proto__ = Element;
    anonymous.prototype = Object.create( Element && Element.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.onconnect = function (event, target) {

    (target = event.target)
      && this.mirror (target.import.querySelector ('template'))

    Element.prototype.onconnect
      && Element.prototype.onconnect.call (this)

    this.tokens = new TokenList (this)
    this.render ()
  };

  // Reflection - https://en.wikipedia.org/wiki/Reflection_(computer_programming)
  // Type Introspection - https://en.wikipedia.org/wiki/Type_introspection
  //
  // In computing, type introspection is the ability of a program
  // to examine the type or properties of an object at runtime.
  // Some programming languages possess this capability.
  //
  // Introspection should not be confused with reflection,
  // which goes a step further and is the ability for a program to manipulate the values,
  // meta-data, properties and/or functions of an object at runtime.

  anonymous.prototype.reflect = function (handler, event) {
    ( event = ( handler.match (/^on(.+)$/) || [] ) [1] )

    && Object.keys // ensure W3C on event
     ( HTMLElement.prototype )
       .includes ( handler )

    && this.on (event, this [handler])
  };

  anonymous.prototype.register = function (node) {
    var this$1 = this;

    var
      register = function (event, handler) { return (handler = /{\s*(\w+)\s*}/.exec (node [event]))

        && ( handler = this$1 [ (handler || []) [1] ] )
        && ( node [event] = this$1.renderable (handler) ); }

    Array
      .from (node.attributes)
      .map (function (attr) { return attr.name; })
      .filter (function (name) { return /^on/.test (name); })
      .map (register)
  };

    return anonymous;
  }(Element))); }

var Component = function (HTMLElement) { return ( (function (superclass) {
    function anonymous () {
  var this$1 = this;
 superclass.call (this)

    var
      descriptions =
        Object.getOwnPropertyDescriptors
          (HTMLElement.prototype)

    , bind = function (key) { return 'function' === typeof descriptions [key].value
        && (this$1 [key] = this$1 [key].bind (this$1)); }

    Object
      .keys (descriptions)
      .map (bind)

    Object
      .getOwnPropertyNames (HTMLElement.prototype)
      // POTENTIAL REDUNDANCY
      // Aren't `on` events set up in `.bind` on 20?
      // If so we are `.bind`ing to `this` on two iterations
      // of the same function
      .map (this.reflect, this)

    this.context = {}
    this.initialize && this.initialize ()
  }

    if ( superclass ) anonymous.__proto__ = superclass;
    anonymous.prototype = Object.create( superclass && superclass.prototype );
    anonymous.prototype.constructor = anonymous;

  anonymous.prototype.connectedCallback = function (link) {
    link = HTMLLinkElement
      (this.tagName.toLowerCase ())

    link
      ? link.addEventListener ('load', this.onconnect.bind (this))
      : this.onconnect (new Event ('load'))
  };

  anonymous.prototype.render = function () {
    var this$1 = this;

    this.tokens.bind (this)

    Array
      .from
        (this.selectAll ('template[name]'))

      .map
        (function (template) { return template.getAttribute ('name'); })

      .map
        (function (name) { return (new Template (name)).bind (this$1 [name]); })

    Array
      .from (this.selectAll ('*'))

      .concat ([this])

      .map (this.register, this)

    superclass.prototype.onidle && superclass.prototype.onidle.call (this)
  };

  anonymous.prototype.mirror = function (template, insert) {
    var this$1 = this;

    template = template.cloneNode (true)

    insert = function (replacement, name, slot) { return (name = replacement.getAttribute ('slot')) &&

      (slot = template.content.querySelector ('slot[name='+name+']'))
         // prefer to use replaceWith however support is sparse
         // https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
         // using `Node.parentNode` - https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode
         // & `Node.replaceChid` - https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
         // as is defined in (ancient) W3C DOM Level 1,2,3
         .parentNode
         .replaceChild (replacement, slot); }

    for (var i = 0, list = this$1.selectAll ('[slot]'); i < list.length; i += 1)
      {
      var replacement = list[i];

      insert (replacement)
    }

    Array
      .from (template.attributes)

      // skip swapping attribute if setting exists
      .filter (function (attr) { return !!! this$1.attributes [attr.name]; })

      .map  (function (attr) { return this$1.setAttribute (attr.name, attr.value); })

    this.innerHTML = template.innerHTML
  };

    return anonymous;
  }(( EventTarget ( ParentNode ( GlobalEventHandlers ( HTMLElement ))))))); }

var ElementPrototype = window.Element.prototype // see bottom of this file

var Element = function (tag) { return function (Element) { return (ref = window.customElements).define.apply
        ( ref, (ref$1 = []).concat.apply ( ref$1, [tag]).concat( [Component (Element)] ))
        var ref;
        var ref$1;; }; }

// Assign `window.Element.prototype` in case of feature checking on `Element`
Element.prototype = ElementPrototype
  // http://2ality.com/2013/09/window.html
  // http://tobyho.com/2013/03/13/window-prop-vs-global-var
  // https://github.com/webcomponents/webcomponentsjs/blob/master/webcomponents-es5-loader.js#L19

<|endoftext|>


<commit_before><commit_msg>Review members section<commit_after><|endoftext|>