<commit_before>'use strict';

delete require.cache[require.resolve('..')];
var DiagramRenderer = require('..');
var createRendererTester = require('../../../test_helper/create-renderer-tester');
var test = createRendererTester(DiagramRenderer);
var assert = require('../../../test_helper/empowered-assert');

describe('DiagramRenderer', function () {

    describe('Identifier', function () {
        test('boolean', function (transpiledCode) {
            var truthy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       false  ',
        ]);

        test('empty string', function (transpiledCode) {
            var truthy = '';
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       ""     ',
        ]);

        test('zero', function (transpiledCode) {
            var truthy = 0;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       0      ',
        ]);

        test('undefined', function (transpiledCode) {
            var truthy = undefined;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       undefined',
        ]);
    });

    describe('UnaryExpression', function () {
        test('with NumberLiteral', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(-0)',
            '       |  ',
            '       0  '
        ]);

        test('with NumberLiteral and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(4 === -4)',
            '         |   |  ',
            '         |   -4 ',
            '         false  '
        ]);

        test('with Identifier and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(+num === -num)',
            '       ||   |   ||   ',
            '       ||   |   |1   ',
            '       ||   |   -1   ',
            '       |1   false    ',
            '       1             '
        ]);

        test('negation', function (transpiledCode) {
            var truth = true;
            eval(transpiledCode);
        }, [
            'assert(!truth)',
            '       ||     ',
            '       |true  ',
            '       false  '
        ]);

        test('double negation', function (transpiledCode) {
            var some = '';
            eval(transpiledCode);
        }, [
            'assert(!!some)',
            '       |||    ',
            '       ||""   ',
            '       |true  ',
            '       false  '
        ]);

        test('typeof operator', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(typeof foo !== "undefined")',
            '       |          |               ',
            '       |          false           ',
            '       "undefined"                '
        ]);

        test('delete operator', function (transpiledCode) {
            var foo = {
                bar: {
                    baz: false
                }
            };
            eval(transpiledCode);
        }, [
            'assert(delete foo.bar === false)',
            '       |      |   |   |         ',
            '       |      |   |   false     ',
            '       |      |   Object{baz:false}',
            '       true   Object{bar:Object{baz:false}}',
        ]);
    });

    describe('MemberExpression', function () {
        test('computed: false', function (transpiledCode) {
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en.foo)',
            '       |  |   ',
            '       |  false',
            '       Object{foo:false}'
        ]);

        test('computed: false', function (transpiledCode) {
            var propName = 'foo';
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en[propName])',
            '       | ||         ',
            '       | |"foo"     ',
            '       | false      ',
            '       Object{foo:false}'
        ]);

        test('chained member', function (transpiledCode) {
            var en = { foo: { bar: false } };
            eval(transpiledCode);
        }, [
            'assert(en.foo.bar)',
            '       |  |   |   ',
            '       |  |   false',
            '       |  Object{bar:false}',
            '       Object{foo:Object{bar:false}}'
        ]);

        test('undefined property', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert({}.hoge === "xxx")',
            '       |  |    |         ',
            '       |  |    false     ',
            '       |  undefined      ',
            '       Object{}          '
        ]);
    });

    describe('CallExpression', function () {
        test('arguments', function (transpiledCode) {
            var name = 'bar';
            var age = 23;
            var foo = function (n, a) { return false; };
            eval(transpiledCode);
        }, [
            'assert(foo(name, age))',
            '       |   |     |    ',
            '       |   "bar" 23   ',
            '       false          '
        ]);

        test('deep CallExpression', function (transpiledCode) {
            var bar = function () { return 'baz'; };
            var en = { foo: function (n) { return false; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo(bar()))',
            '       |  |   |      ',
            '       |  |   "baz"  ',
            '       |  false      ',
            '       Object{foo:#function#}'
        ]);
    });

    describe('BinaryExpression', function () {
        test('of BinaryExpression', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar === (foo === bar) === (foo === bar))',
            '       |   |   |   |    |   |   |    |    |   |   |    ',
            '       |   |   |   |    |   |   |    |    |   |   "bar"',
            '       |   |   |   |    |   |   |    |    |   false    ',
            '       |   |   |   |    |   |   |    |    "foo"        ',
            '       |   |   |   |    |   |   |    false             ',
            '       |   |   |   |    |   |   "bar"                  ',
            '       |   |   |   |    |   false                      ',
            '       |   |   |   true "foo"                          ',
            '       |   |   "bar"                                   ',
            '       |   false                                       ',
            '       "foo"                                           '
        ]);

        test('of Identifier', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar)',
            '       |   |   |   ',
            '       |   |   "bar"',
            '       |   false   ',
            '       "foo"       ',
        ]);

        test('of Identifier and StringLiteral', function (transpiledCode) {
            var foo = 'foo';
            eval(transpiledCode);
        }, [
            'assert(foo === "bar")',
            '       |   |         ',
            '       |   false     ',
            '       "foo"         ',
        ]);

        test('of StringLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert("foo" === "bar")',
            '             |         ',
            '             false     '
        ]);

        test('of NumberLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(4 !== 4)',
            '         |     ',
            '         false '
        ]);

        test('of MemberExpression', function (transpiledCode) {
            var en = { foo: 'bar', toto: 'tata' };
            var fr = { toto: 'tata'};
            eval(transpiledCode);
        }, [
            'assert(en.foo === fr.toto)',
            '       |  |   |   |  |    ',
            '       |  |   |   |  "tata"',
            '       |  |   |   Object{toto:"tata"}',
            '       |  |   false       ',
            '       |  "bar"           ',
            '       Object{foo:"bar",toto:"tata"}'
        ]);

        test('of CallExpression', function (transpiledCode) {
            var en = { foo: function() { return 'bar';} };
            var fr = { toto: function() { return 'tata'; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo() === fr.toto())',
            '       |  |     |   |  |      ',
            '       |  |     |   |  "tata" ',
            '       |  |     |   Object{toto:#function#}',
            '       |  "bar" false         ',
            '       Object{foo:#function#} '
        ]);

        test('non-Punctuator BinaryExpression operator', function (transpiledCode) {
            function Person (name) { this.name = name; };
            var foo = 'bob';
            eval(transpiledCode);
        }, [
            'assert(foo instanceof Person)',
            '       |   |          |      ',
            '       |   false      #function#',
            '       "bob"                 '
        ]);

        test('Loose equality', function (transpiledCode) {
            var truthy = '1';
            var falsy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy == falsy)',
            '       |      |  |     ',
            '       |      |  false ',
            '       "1"    false    '
        ]);

        test('of NaN', function (transpiledCode) {
            var nan1 = NaN;
            var nan2 = NaN;
            eval(transpiledCode);
        }, [
            'assert(nan1 === nan2)',
            '       |    |   |    ',
            '       |    |   NaN  ',
            '       NaN  false    '
        ]);

        test('of Infinity', function (transpiledCode) {
            var positiveInfinity = Infinity;
            var negativeInfinity = -Infinity;
            eval(transpiledCode);
        }, [
            'assert(positiveInfinity === negativeInfinity)',
            '       |                |   |                ',
            '       |                |   -Infinity        ',
            '       Infinity         false                '
        ]);
    });

    describe('LogicalExpression', function () {
        test('of Identifiers', function (transpiledCode) {
            var x = false;
            var y = 0;
            var z = null;
            eval(transpiledCode);
        }, [
            'assert(x || y || z)',
            '       | |  | |  | ',
            '       | |  | |  null',
            '       | 0  0 null ',
            '       false       '
        ]);

        test('of Identifier evaluation order', function (transpiledCode) {
            var x = 'yeah';
            var y = 0;
            var z = true;
            eval(transpiledCode);
        }, [
            'assert(x && y && z)',
            '       | |  | |    ',
            '       | 0  0 0    ',
            '       "yeah"      '
        ]);

        test('of CallExpression and MemberExpression', function (transpiledCode) {
            var x = { foo: function(n) { return false; } };
            var y = function(n) { return null; };
            var z = { val: 0 };
            eval(transpiledCode);
        }, [
            'assert(x.foo() || y() || z.val)',
            '       | |     |  |   |  | |   ',
            '       | |     |  |   |  | 0   ',
            '       | |     |  |   0  Object{val:0}',
            '       | |     |  null         ',
            '       | false null            ',
            '       Object{foo:#function#}  '
        ]);
    });

    describe('ConditionalExpression', function () {
        test('of Identifiers, consequent', function (transpiledCode) {
            var foo = false;
            var bar = null;
            var baz = 0;
            eval(transpiledCode);
        }, [
            'assert(foo ? bar : baz)',
            '       |           |   ',
            '       false       0   '
        ]);
        test('of Identifiers, alternate', function (transpiledCode) {
            var foo = true;
            var bar = null;
            var baz = 0;
            eval(transpiledCode);
        }, [
            'assert(foo ? bar : baz)',
            '       |     |         ',
            '       true  null      '
        ]);
        test('of another ConditionalExpression', function (transpiledCode) {
            var falsy = null;
            var truthy = 'truth';
            var anotherFalsy = 0;
            eval(transpiledCode);
        }, [
            'assert(falsy ? truthy : truthy ? anotherFalsy : truthy)',
            '       |                |        |                     ',
            '       null             "truth"  0                     '
        ]);
    });

    describe('ObjectExpression', function () {
        test('of Literals', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ foo: 0 }, { foo: 1 })',
            '                 |           |          ',
            '                 |           Object{foo:1}',
            '                 Object{foo:0}          '
        ]);
        test('of Identifiers', function (transpiledCode) {
            var bar = 'BAR';
            var fuga = 'FUGA';
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ foo: bar }, { hoge: fuga })',
            '                 |      |      |       |      ',
            '                 |      |      |       "FUGA" ',
            '                 |      "BAR"  Object{hoge:"FUGA"}',
            '                 Object{foo:"BAR"}            '
        ]);
        test('enhanced object literals', function (transpiledCode) {
            var name = 'bobby';
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ name, [`greet from ${name}`]: `Hello, I am ${name}` }, null)',
            '                 |        |             |        |              |              ',
            '                 |        |             |        |              "bobby"        ',
            '                 |        |             "bobby"  "Hello, I am bobby"           ',
            '                 |        "greet from bobby"                                   ',
            '                 Object{name:"bobby","greet from bobby":"Hello, I am bobby"}   '
        ]);
    });

    test('ArrayExpression as an argument of CallExpression', function (transpiledCode) {
        var pop = function (ary) { return ary.pop(); };
        var zero = 0;
        var one = 1;
        var two = 2;
        eval(transpiledCode);
    }, [
        'assert(pop([zero, one, two]) === one)',
        '       |   ||     |    |     |   |   ',
        '       |   ||     |    |     |   1   ',
        '       |   |0     1    2     false   ',
        '       2   [0,1]                     '
    ]);

    describe('ObjectRestSpread', function () {
        test('Spread Properties', function (transpiledCode) {
            var a = 'a';
            var b = 'b';
            var obj = { foo: 'FOO', bar: 'BAR' };
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ b, ...obj }, { a, ...obj })',
            '                 |              |             ',
            '                 |              Object{a:"a",foo:"FOO",bar:"BAR"}',
            '                 Object{b:"b",foo:"FOO",bar:"BAR"}'
        ]);
    });

    describe('Function Bind Syntax', function () {
        test('avajs/ava#881', function (transpiledCode) {
            function validate(name) {
                return {
                    name: name,
                    valid: true,
                    value: this
                };
            }
            eval(transpiledCode);
        }, [
            'assert.deepEqual(true::validate("foo"), { valid: true, value: true, name: "bar" })',
            '                 |                      |                                         ',
            '                 |                      Object{valid:true,value:true,name:"bar"}  ',
            '                 Object{name:"foo",valid:true,value:true}                         '
        ]);
    });

    describe('SequenceExpression i.e., comma operator', function () {
        test('power-assert-js/power-assert#59', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert((-0, -1) + 1 === -0 + -1)',
            '        |   |   |   |   |  | |  ',
            '        |   |   |   |   |  | -1 ',
            '        |   |   |   |   0  -1   ',
            '        0   -1  0   false       '
        ]);
    });
});
<commit_msg>style(power-assert-renderer-diagram): remove trailing spaces<commit_after>'use strict';

delete require.cache[require.resolve('..')];
var DiagramRenderer = require('..');
var createRendererTester = require('../../../test_helper/create-renderer-tester');
var test = createRendererTester(DiagramRenderer);
var assert = require('../../../test_helper/empowered-assert');

describe('DiagramRenderer', function () {

    describe('Identifier', function () {
        test('boolean', function (transpiledCode) {
            var truthy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       false  ',
        ]);

        test('empty string', function (transpiledCode) {
            var truthy = '';
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       ""     ',
        ]);

        test('zero', function (transpiledCode) {
            var truthy = 0;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       0      ',
        ]);

        test('undefined', function (transpiledCode) {
            var truthy = undefined;
            eval(transpiledCode);
        }, [
            'assert(truthy)',
            '       |      ',
            '       undefined',
        ]);
    });

    describe('UnaryExpression', function () {
        test('with NumberLiteral', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(-0)',
            '       |  ',
            '       0  '
        ]);

        test('with NumberLiteral and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(4 === -4)',
            '         |   |  ',
            '         |   -4 ',
            '         false  '
        ]);

        test('with Identifier and BinaryExpression', function (transpiledCode) {
            var num = 1;
            eval(transpiledCode);
        }, [
            'assert(+num === -num)',
            '       ||   |   ||   ',
            '       ||   |   |1   ',
            '       ||   |   -1   ',
            '       |1   false    ',
            '       1             '
        ]);

        test('negation', function (transpiledCode) {
            var truth = true;
            eval(transpiledCode);
        }, [
            'assert(!truth)',
            '       ||     ',
            '       |true  ',
            '       false  '
        ]);

        test('double negation', function (transpiledCode) {
            var some = '';
            eval(transpiledCode);
        }, [
            'assert(!!some)',
            '       |||    ',
            '       ||""   ',
            '       |true  ',
            '       false  '
        ]);

        test('typeof operator', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(typeof foo !== "undefined")',
            '       |          |               ',
            '       |          false           ',
            '       "undefined"                '
        ]);

        test('delete operator', function (transpiledCode) {
            var foo = {
                bar: {
                    baz: false
                }
            };
            eval(transpiledCode);
        }, [
            'assert(delete foo.bar === false)',
            '       |      |   |   |         ',
            '       |      |   |   false     ',
            '       |      |   Object{baz:false}',
            '       true   Object{bar:Object{baz:false}}',
        ]);
    });

    describe('MemberExpression', function () {
        test('computed: false', function (transpiledCode) {
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en.foo)',
            '       |  |   ',
            '       |  false',
            '       Object{foo:false}'
        ]);

        test('computed: false', function (transpiledCode) {
            var propName = 'foo';
            var en = { foo: false };
            eval(transpiledCode);
        }, [
            'assert(en[propName])',
            '       | ||         ',
            '       | |"foo"     ',
            '       | false      ',
            '       Object{foo:false}'
        ]);

        test('chained member', function (transpiledCode) {
            var en = { foo: { bar: false } };
            eval(transpiledCode);
        }, [
            'assert(en.foo.bar)',
            '       |  |   |   ',
            '       |  |   false',
            '       |  Object{bar:false}',
            '       Object{foo:Object{bar:false}}'
        ]);

        test('undefined property', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert({}.hoge === "xxx")',
            '       |  |    |         ',
            '       |  |    false     ',
            '       |  undefined      ',
            '       Object{}          '
        ]);
    });

    describe('CallExpression', function () {
        test('arguments', function (transpiledCode) {
            var name = 'bar';
            var age = 23;
            var foo = function (n, a) { return false; };
            eval(transpiledCode);
        }, [
            'assert(foo(name, age))',
            '       |   |     |    ',
            '       |   "bar" 23   ',
            '       false          '
        ]);

        test('deep CallExpression', function (transpiledCode) {
            var bar = function () { return 'baz'; };
            var en = { foo: function (n) { return false; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo(bar()))',
            '       |  |   |      ',
            '       |  |   "baz"  ',
            '       |  false      ',
            '       Object{foo:#function#}'
        ]);
    });

    describe('BinaryExpression', function () {
        test('of BinaryExpression', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar === (foo === bar) === (foo === bar))',
            '       |   |   |   |    |   |   |    |    |   |   |    ',
            '       |   |   |   |    |   |   |    |    |   |   "bar"',
            '       |   |   |   |    |   |   |    |    |   false    ',
            '       |   |   |   |    |   |   |    |    "foo"        ',
            '       |   |   |   |    |   |   |    false             ',
            '       |   |   |   |    |   |   "bar"                  ',
            '       |   |   |   |    |   false                      ',
            '       |   |   |   true "foo"                          ',
            '       |   |   "bar"                                   ',
            '       |   false                                       ',
            '       "foo"                                           '
        ]);

        test('of Identifier', function (transpiledCode) {
            var foo = 'foo';
            var bar = 'bar';
            eval(transpiledCode);
        }, [
            'assert(foo === bar)',
            '       |   |   |   ',
            '       |   |   "bar"',
            '       |   false   ',
            '       "foo"       ',
        ]);

        test('of Identifier and StringLiteral', function (transpiledCode) {
            var foo = 'foo';
            eval(transpiledCode);
        }, [
            'assert(foo === "bar")',
            '       |   |         ',
            '       |   false     ',
            '       "foo"         ',
        ]);

        test('of StringLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert("foo" === "bar")',
            '             |         ',
            '             false     '
        ]);

        test('of NumberLiteral', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert(4 !== 4)',
            '         |     ',
            '         false '
        ]);

        test('of MemberExpression', function (transpiledCode) {
            var en = { foo: 'bar', toto: 'tata' };
            var fr = { toto: 'tata'};
            eval(transpiledCode);
        }, [
            'assert(en.foo === fr.toto)',
            '       |  |   |   |  |    ',
            '       |  |   |   |  "tata"',
            '       |  |   |   Object{toto:"tata"}',
            '       |  |   false       ',
            '       |  "bar"           ',
            '       Object{foo:"bar",toto:"tata"}'
        ]);

        test('of CallExpression', function (transpiledCode) {
            var en = { foo: function() { return 'bar';} };
            var fr = { toto: function() { return 'tata'; } };
            eval(transpiledCode);
        }, [
            'assert(en.foo() === fr.toto())',
            '       |  |     |   |  |      ',
            '       |  |     |   |  "tata" ',
            '       |  |     |   Object{toto:#function#}',
            '       |  "bar" false         ',
            '       Object{foo:#function#} '
        ]);

        test('non-Punctuator BinaryExpression operator', function (transpiledCode) {
            function Person (name) { this.name = name; };
            var foo = 'bob';
            eval(transpiledCode);
        }, [
            'assert(foo instanceof Person)',
            '       |   |          |      ',
            '       |   false      #function#',
            '       "bob"                 '
        ]);

        test('Loose equality', function (transpiledCode) {
            var truthy = '1';
            var falsy = false;
            eval(transpiledCode);
        }, [
            'assert(truthy == falsy)',
            '       |      |  |     ',
            '       |      |  false ',
            '       "1"    false    '
        ]);

        test('of NaN', function (transpiledCode) {
            var nan1 = NaN;
            var nan2 = NaN;
            eval(transpiledCode);
        }, [
            'assert(nan1 === nan2)',
            '       |    |   |    ',
            '       |    |   NaN  ',
            '       NaN  false    '
        ]);

        test('of Infinity', function (transpiledCode) {
            var positiveInfinity = Infinity;
            var negativeInfinity = -Infinity;
            eval(transpiledCode);
        }, [
            'assert(positiveInfinity === negativeInfinity)',
            '       |                |   |                ',
            '       |                |   -Infinity        ',
            '       Infinity         false                '
        ]);
    });

    describe('LogicalExpression', function () {
        test('of Identifiers', function (transpiledCode) {
            var x = false;
            var y = 0;
            var z = null;
            eval(transpiledCode);
        }, [
            'assert(x || y || z)',
            '       | |  | |  | ',
            '       | |  | |  null',
            '       | 0  0 null ',
            '       false       '
        ]);

        test('of Identifier evaluation order', function (transpiledCode) {
            var x = 'yeah';
            var y = 0;
            var z = true;
            eval(transpiledCode);
        }, [
            'assert(x && y && z)',
            '       | |  | |    ',
            '       | 0  0 0    ',
            '       "yeah"      '
        ]);

        test('of CallExpression and MemberExpression', function (transpiledCode) {
            var x = { foo: function(n) { return false; } };
            var y = function(n) { return null; };
            var z = { val: 0 };
            eval(transpiledCode);
        }, [
            'assert(x.foo() || y() || z.val)',
            '       | |     |  |   |  | |   ',
            '       | |     |  |   |  | 0   ',
            '       | |     |  |   0  Object{val:0}',
            '       | |     |  null         ',
            '       | false null            ',
            '       Object{foo:#function#}  '
        ]);
    });

    describe('ConditionalExpression', function () {
        test('of Identifiers, consequent', function (transpiledCode) {
            var foo = false;
            var bar = null;
            var baz = 0;
            eval(transpiledCode);
        }, [
            'assert(foo ? bar : baz)',
            '       |           |   ',
            '       false       0   '
        ]);
        test('of Identifiers, alternate', function (transpiledCode) {
            var foo = true;
            var bar = null;
            var baz = 0;
            eval(transpiledCode);
        }, [
            'assert(foo ? bar : baz)',
            '       |     |         ',
            '       true  null      '
        ]);
        test('of another ConditionalExpression', function (transpiledCode) {
            var falsy = null;
            var truthy = 'truth';
            var anotherFalsy = 0;
            eval(transpiledCode);
        }, [
            'assert(falsy ? truthy : truthy ? anotherFalsy : truthy)',
            '       |                |        |                     ',
            '       null             "truth"  0                     '
        ]);
    });

    describe('ObjectExpression', function () {
        test('of Literals', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ foo: 0 }, { foo: 1 })',
            '                 |           |          ',
            '                 |           Object{foo:1}',
            '                 Object{foo:0}          '
        ]);
        test('of Identifiers', function (transpiledCode) {
            var bar = 'BAR';
            var fuga = 'FUGA';
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ foo: bar }, { hoge: fuga })',
            '                 |      |      |       |      ',
            '                 |      |      |       "FUGA" ',
            '                 |      "BAR"  Object{hoge:"FUGA"}',
            '                 Object{foo:"BAR"}            '
        ]);
        test('enhanced object literals', function (transpiledCode) {
            var name = 'bobby';
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ name, [`greet from ${name}`]: `Hello, I am ${name}` }, null)',
            '                 |        |             |        |              |              ',
            '                 |        |             |        |              "bobby"        ',
            '                 |        |             "bobby"  "Hello, I am bobby"           ',
            '                 |        "greet from bobby"                                   ',
            '                 Object{name:"bobby","greet from bobby":"Hello, I am bobby"}   '
        ]);
    });

    test('ArrayExpression as an argument of CallExpression', function (transpiledCode) {
        var pop = function (ary) { return ary.pop(); };
        var zero = 0;
        var one = 1;
        var two = 2;
        eval(transpiledCode);
    }, [
        'assert(pop([zero, one, two]) === one)',
        '       |   ||     |    |     |   |   ',
        '       |   ||     |    |     |   1   ',
        '       |   |0     1    2     false   ',
        '       2   [0,1]                     '
    ]);

    describe('ObjectRestSpread', function () {
        test('Spread Properties', function (transpiledCode) {
            var a = 'a';
            var b = 'b';
            var obj = { foo: 'FOO', bar: 'BAR' };
            eval(transpiledCode);
        }, [
            'assert.deepEqual({ b, ...obj }, { a, ...obj })',
            '                 |              |             ',
            '                 |              Object{a:"a",foo:"FOO",bar:"BAR"}',
            '                 Object{b:"b",foo:"FOO",bar:"BAR"}'
        ]);
    });

    describe('Function Bind Syntax', function () {
        test('avajs/ava#881', function (transpiledCode) {
            function validate(name) {
                return {
                    name: name,
                    valid: true,
                    value: this
                };
            }
            eval(transpiledCode);
        }, [
            'assert.deepEqual(true::validate("foo"), { valid: true, value: true, name: "bar" })',
            '                 |                      |                                         ',
            '                 |                      Object{valid:true,value:true,name:"bar"}  ',
            '                 Object{name:"foo",valid:true,value:true}                         '
        ]);
    });

    describe('SequenceExpression i.e., comma operator', function () {
        test('power-assert-js/power-assert#59', function (transpiledCode) {
            eval(transpiledCode);
        }, [
            'assert((-0, -1) + 1 === -0 + -1)',
            '        |   |   |   |   |  | |  ',
            '        |   |   |   |   |  | -1 ',
            '        |   |   |   |   0  -1   ',
            '        0   -1  0   false       '
        ]);
    });
});
<|endoftext|>


<commit_before>'use strict';

var makeAssimilatePrototype = require('./makeAssimilatePrototype'),
    requestForceUpdateAll = require('./requestForceUpdateAll');

function hasLegacyTypeProperty(ReactClass) {
  if (!ReactClass.hasOwnProperty('type')) {
    return false;
  }

  var descriptor = Object.getOwnPropertyDescriptor(ReactClass, 'type');
  if (typeof descriptor.get === 'function') {
    return false;
  }

  return true;
}

function getPrototype(ReactClass) {
  var prototype = ReactClass.prototype;

  if (typeof prototype.render !== 'function' && hasLegacyTypeProperty(ReactClass)) {
    prototype = ReactClass.type.prototype;
  }

  return prototype;
}

/**
 * Returns a function that will patch React class with new versions of itself
 * on subsequent invocations. Both legacy and ES6 style classes are supported.
 */
module.exports = function makePatchReactClass(getRootInstances) {
  var assimilatePrototype = makeAssimilatePrototype(),
      FirstClass = null;

  return function patchReactClass(NextClass) {
    var nextPrototype = getPrototype(NextClass);
    assimilatePrototype(nextPrototype);

    if (FirstClass) {
      requestForceUpdateAll(getRootInstances);
    }

    return FirstClass || (FirstClass = NextClass);
  };
};<commit_msg>Don't crash when hot-reloading an element factory. Fixes #4.<commit_after>'use strict';

var makeAssimilatePrototype = require('./makeAssimilatePrototype'),
    requestForceUpdateAll = require('./requestForceUpdateAll');

function hasNonStubTypeProperty(ReactClass) {
  if (!ReactClass.hasOwnProperty('type')) {
    return false;
  }

  var descriptor = Object.getOwnPropertyDescriptor(ReactClass, 'type');
  if (typeof descriptor.get === 'function') {
    return false;
  }

  return true;
}

function getPrototype(ReactClass) {
  var prototype = ReactClass.prototype,
      seemsLegit = prototype && typeof prototype.render === 'function';

  if (!seemsLegit && hasNonStubTypeProperty(ReactClass)) {
    prototype = ReactClass.type.prototype;
  }

  return prototype;
}

/**
 * Returns a function that will patch React class with new versions of itself
 * on subsequent invocations. Both legacy and ES6 style classes are supported.
 */
module.exports = function makePatchReactClass(getRootInstances) {
  var assimilatePrototype = makeAssimilatePrototype(),
      FirstClass = null;

  return function patchReactClass(NextClass) {
    var nextPrototype = getPrototype(NextClass);
    assimilatePrototype(nextPrototype);

    if (FirstClass) {
      requestForceUpdateAll(getRootInstances);
    }

    return FirstClass || (FirstClass = NextClass);
  };
};<|endoftext|>


<commit_before>import cloudinary from "cloudinary";
import Posts from "meteor/vulcan:posts";
import Users from 'meteor/vulcan:users';
import { addCallback, Utils, getSetting } from 'meteor/vulcan:core';

const Cloudinary = cloudinary.v2;
const uploadSync = Meteor.wrapAsync(Cloudinary.uploader.upload);

Cloudinary.config({
  cloud_name: getSetting("cloudinaryCloudName"),
  api_key: getSetting("cloudinaryAPIKey"),
  api_secret: getSetting("cloudinaryAPISecret"),
  secure: true,
});

const CloudinaryUtils = {

  // send an image URL to Cloudinary and get a cloudinary result object in return
  uploadImage(imageUrl) {
    try {
      var result = uploadSync(Utils.addHttp(imageUrl));
      const data = {
        cloudinaryId: result.public_id,
        result: result,
        urls: CloudinaryUtils.getUrls(result.public_id)
      };
      return data;
    } catch (error) {
      console.log("// Cloudinary upload failed for URL: "+imageUrl); // eslint-disable-line
      console.log(error); // eslint-disable-line
    }
  },

  // generate signed URL for each format based off public_id
  getUrls(cloudinaryId) {
    return getSetting("cloudinaryFormats").map(format => {
      const url = Cloudinary.url(cloudinaryId, {
        width: format.width,
        height: format.height,
        crop: 'fill',
        sign_url: true,
        fetch_format: "auto",
        quality: "auto"
      });
      return {
        name: format.name,
        url: url
      };
    });
  }
};

// methods
Meteor.methods({
  testCloudinaryUpload: function (thumbnailUrl) {
    if (Users.isAdmin(Meteor.user())) {
      thumbnailUrl = typeof thumbnailUrl === "undefined" ? "http://www.telescopeapp.org/images/logo.png" : thumbnailUrl;
      const data = CloudinaryUtils.uploadImage(thumbnailUrl);
      console.log(data); // eslint-disable-line
    }
  },
  cachePostThumbnails: function (limit = 20) {

    if (Users.isAdmin(Meteor.user())) {

      var postsWithUncachedThumbnails = Posts.find({
        thumbnailUrl: { $exists: true },
        originalThumbnailUrl: { $exists: false }
      }, {sort: {createdAt: -1}, limit: limit});

      postsWithUncachedThumbnails.forEach(Meteor.bindEnvironment((post, index) => {

          Meteor.setTimeout(function () {
          console.log(`// ${index}. Caching thumbnail for post “${post.title}” (_id: ${post._id})`); // eslint-disable-line

          const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
          Posts.update(post._id, {$set:{
            cloudinaryId: data.cloudinaryId,
            cloudinaryUrls: data.urls
          }});

        }, index * 1000);

      }));
    }
  }
});

// post submit callback
function cachePostThumbnailOnSubmit (post) {
  if (getSetting("cloudinaryAPIKey")) {
    if (post.thumbnailUrl) {

      const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
      if (data) {
        Posts.update(post._id, {$set:{
          cloudinaryId: data.cloudinaryId,
          cloudinaryUrls: data.urls
        }});
      }

    }
  }
}
addCallback("posts.new.async", cachePostThumbnailOnSubmit);

// post edit callback
function cachePostThumbnailOnEdit (newPost, oldPost) {
  if (getSetting("cloudinaryAPIKey")) {
    if (newPost.thumbnailUrl && newPost.thumbnailUrl !== oldPost.thumbnailUrl) {

      const data = CloudinaryUtils.uploadImage(newPost.thumbnailUrl);
      Posts.update(newPost._id, {$set:{
        cloudinaryId: data.cloudinaryId,
        cloudinaryUrls: data.urls
      }});

    }
  }
}
addCallback("posts.edit.async", cachePostThumbnailOnEdit);

export default CloudinaryUtils;
<commit_msg>make Cloudinary callback sync so that mutations can return thumbnail URLs<commit_after>import cloudinary from "cloudinary";
import Posts from "meteor/vulcan:posts";
import Users from 'meteor/vulcan:users';
import { addCallback, Utils, getSetting } from 'meteor/vulcan:core';

const Cloudinary = cloudinary.v2;
const uploadSync = Meteor.wrapAsync(Cloudinary.uploader.upload);

Cloudinary.config({
  cloud_name: getSetting("cloudinaryCloudName"),
  api_key: getSetting("cloudinaryAPIKey"),
  api_secret: getSetting("cloudinaryAPISecret"),
  secure: true,
});

const CloudinaryUtils = {

  // send an image URL to Cloudinary and get a cloudinary result object in return
  uploadImage(imageUrl) {
    try {
      var result = uploadSync(Utils.addHttp(imageUrl));
      const data = {
        cloudinaryId: result.public_id,
        result: result,
        urls: CloudinaryUtils.getUrls(result.public_id)
      };
      return data;
    } catch (error) {
      console.log("// Cloudinary upload failed for URL: "+imageUrl); // eslint-disable-line
      console.log(error); // eslint-disable-line
    }
  },

  // generate signed URL for each format based off public_id
  getUrls(cloudinaryId) {
    return getSetting("cloudinaryFormats").map(format => {
      const url = Cloudinary.url(cloudinaryId, {
        width: format.width,
        height: format.height,
        crop: 'fill',
        sign_url: true,
        fetch_format: "auto",
        quality: "auto"
      });
      return {
        name: format.name,
        url: url
      };
    });
  }
};

// methods
Meteor.methods({
  testCloudinaryUpload: function (thumbnailUrl) {
    if (Users.isAdmin(Meteor.user())) {
      thumbnailUrl = typeof thumbnailUrl === "undefined" ? "http://www.telescopeapp.org/images/logo.png" : thumbnailUrl;
      const data = CloudinaryUtils.uploadImage(thumbnailUrl);
      console.log(data); // eslint-disable-line
    }
  },
  cachePostThumbnails: function (limit = 20) {

    if (Users.isAdmin(Meteor.user())) {

      var postsWithUncachedThumbnails = Posts.find({
        thumbnailUrl: { $exists: true },
        originalThumbnailUrl: { $exists: false }
      }, {sort: {createdAt: -1}, limit: limit});

      postsWithUncachedThumbnails.forEach(Meteor.bindEnvironment((post, index) => {

          Meteor.setTimeout(function () {
          console.log(`// ${index}. Caching thumbnail for post “${post.title}” (_id: ${post._id})`); // eslint-disable-line

          const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
          Posts.update(post._id, {$set:{
            cloudinaryId: data.cloudinaryId,
            cloudinaryUrls: data.urls
          }});

        }, index * 1000);

      }));
    }
  }
});

// post submit callback
function cachePostThumbnailOnSubmit (post) {
  if (getSetting("cloudinaryAPIKey")) {
    if (post.thumbnailUrl) {

      const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
      if (data) {
        post.cloudinaryId = data.cloudinaryId;
        post.cloudinaryUrls = data.urls;
      }

    }
  }
  return post;
}
addCallback("posts.new.sync", cachePostThumbnailOnSubmit);

function cachePostThumbnailOnEdit (modifier, oldPost) {
  if (getSetting("cloudinaryAPIKey")) {
    if (modifier.$set.thumbnailUrl && modifier.$set.thumbnailUrl !== oldPost.thumbnailUrl) {
      const data = CloudinaryUtils.uploadImage(modifier.$set.thumbnailUrl);
      modifier.$set.cloudinaryId = data.cloudinaryId;
      modifier.$set.cloudinaryUrls = data.urls;
    }
  }
  return modifier;
}
addCallback("posts.edit.sync", cachePostThumbnailOnEdit);

export default CloudinaryUtils;
<|endoftext|>


<commit_before>import React, { Component } from "react"
import PropTypes from "prop-types"
import { Table, Column, Cell } from "fixed-data-table-2"
import { Card, CardText } from "material-ui/Card"
import DeploymentLink from "../DeploymentLink/DeploymentLink"
import JobLink from "../JobLink/JobLink"
import DeploymentDistribution from "../DeploymentDistribution/DeploymentDistribution"

/* eslint-disable react/prop-types */

const TextCell = ({ rowIndex, data, col, ...props }) =>
  <Cell {...props}>
    {data[rowIndex][col]}
  </Cell>

const JobLinkCell = ({ rowIndex, data, ...props }) =>
  <Cell {...props}>
    <JobLink jobId={data[rowIndex].JobID} />
  </Cell>

const DeploymentLinkCell = ({ rowIndex, data, col, ...props }) =>
  <Cell {...props}>
    <DeploymentLink deploymentId={data[rowIndex][col]} />
  </Cell>

const DeploymentDistributionCell = ({ rowIndex, data, type, ...props }) =>
  <Cell {...props}>
    <DeploymentDistribution deployment={data[rowIndex]} type={type} />
  </Cell>

class DeploymentList extends Component {
  updateDimensions() {
    this.setState({
      ...this.state,
      width: window.innerWidth,
      height: window.innerHeight
    })
  }

  componentWillMount() {
    this.updateDimensions()
  }

  componentDidMount() {
    window.addEventListener("resize", () => this.updateDimensions())
  }

  componentWillUnmount() {
    window.removeEventListener("resize", () => this.updateDimensions())
  }

  render() {
    const deployments = this.props.deployments
    const width = this.state.width - 240
    let height = this.state.height - 90

    if (this.props.nested) {
      height = height - 120
    }

    if (height < 300) {
      height = 300
    }

    return (
      <Card>
        <CardText>
          <Table
            rowHeight={35}
            headerHeight={35}
            rowsCount={deployments.length}
            height={height}
            width={width}
            touchScrollEnabled
            {...this.props}
          >
            <Column header={<Cell>ID</Cell>} cell={<DeploymentLinkCell data={deployments} col="ID" />} width={100} />
            <Column header={<Cell>Job</Cell>} cell={<JobLinkCell data={deployments} />} flexGrow={2} width={100} />
            <Column header={<Cell>Version</Cell>} cell={<TextCell data={deployments} col="JobVersion" />} width={100} />
            <Column header={<Cell>Status</Cell>} cell={<TextCell data={deployments} col="Status" />} width={150} />
            <Column
              header={<Cell>Canary</Cell>}
              cell={<DeploymentDistributionCell data={deployments} type="canary" />}
              width={150}
            />
            <Column
              header={<Cell>Healthy</Cell>}
              cell={<DeploymentDistributionCell data={deployments} type="healthy" />}
              width={150}
            />
            <Column
              header={<Cell>Total</Cell>}
              cell={<DeploymentDistributionCell data={deployments} type="total" />}
              width={150}
            />
            <Column
              header={<Cell>Description</Cell>}
              cell={<TextCell data={deployments} col="StatusDescription" />}
              flexGrow={2}
              width={250}
            />
          </Table>
        </CardText>
      </Card>
    )
  }
}

DeploymentList.defaultProps = {
  deployments: [],
  nested: false
}

DeploymentList.propTypes = {
  deployments: PropTypes.array.isRequired,
  nested: PropTypes.bool.isRequired
}

export default DeploymentList
<commit_msg>change titles<commit_after>import React, { Component } from "react"
import PropTypes from "prop-types"
import { Table, Column, Cell } from "fixed-data-table-2"
import { Card, CardText } from "material-ui/Card"
import DeploymentLink from "../DeploymentLink/DeploymentLink"
import JobLink from "../JobLink/JobLink"
import DeploymentDistribution from "../DeploymentDistribution/DeploymentDistribution"

/* eslint-disable react/prop-types */

const TextCell = ({ rowIndex, data, col, ...props }) =>
  <Cell {...props}>
    {data[rowIndex][col]}
  </Cell>

const JobLinkCell = ({ rowIndex, data, ...props }) =>
  <Cell {...props}>
    <JobLink jobId={data[rowIndex].JobID} />
  </Cell>

const DeploymentLinkCell = ({ rowIndex, data, col, ...props }) =>
  <Cell {...props}>
    <DeploymentLink deploymentId={data[rowIndex][col]} />
  </Cell>

const DeploymentDistributionCell = ({ rowIndex, data, type, ...props }) =>
  <Cell {...props}>
    <DeploymentDistribution deployment={data[rowIndex]} type={type} />
  </Cell>

class DeploymentList extends Component {
  updateDimensions() {
    this.setState({
      ...this.state,
      width: window.innerWidth,
      height: window.innerHeight
    })
  }

  componentWillMount() {
    this.updateDimensions()
  }

  componentDidMount() {
    window.addEventListener("resize", () => this.updateDimensions())
  }

  componentWillUnmount() {
    window.removeEventListener("resize", () => this.updateDimensions())
  }

  render() {
    const deployments = this.props.deployments
    const width = this.state.width - 240
    let height = this.state.height - 90

    if (this.props.nested) {
      height = height - 120
    }

    if (height < 300) {
      height = 300
    }

    return (
      <Card>
        <CardText>
          <Table
            rowHeight={35}
            headerHeight={35}
            rowsCount={deployments.length}
            height={height}
            width={width}
            touchScrollEnabled
            {...this.props}
          >
            <Column header={<Cell>ID</Cell>} cell={<DeploymentLinkCell data={deployments} col="ID" />} width={100} />
            <Column header={<Cell>Job</Cell>} cell={<JobLinkCell data={deployments} />} flexGrow={2} width={100} />
            <Column header={<Cell>Version</Cell>} cell={<TextCell data={deployments} col="JobVersion" />} width={100} />
            <Column header={<Cell>Status</Cell>} cell={<TextCell data={deployments} col="Status" />} width={150} />
            <Column
              header={<Cell>Canary</Cell>}
              cell={<DeploymentDistributionCell data={deployments} type="canary" />}
              width={150}
            />
            <Column
              header={<Cell>Roll out</Cell>}
              cell={<DeploymentDistributionCell data={deployments} type="healthy" />}
              width={150}
            />
            <Column
              header={<Cell>Placement</Cell>}
              cell={<DeploymentDistributionCell data={deployments} type="total" />}
              width={150}
            />
            <Column
              header={<Cell>Description</Cell>}
              cell={<TextCell data={deployments} col="StatusDescription" />}
              flexGrow={2}
              width={250}
            />
          </Table>
        </CardText>
      </Card>
    )
  }
}

DeploymentList.defaultProps = {
  deployments: [],
  nested: false
}

DeploymentList.propTypes = {
  deployments: PropTypes.array.isRequired,
  nested: PropTypes.bool.isRequired
}

export default DeploymentList
<|endoftext|>


<commit_before>// Javascript controlling the taxonomy browser.

var TaxonomyBrowser = function () {
  var self = this;

  self.init = function () {

    self.$browserDiv = $('#browse-container');

    if (self.$browserDiv.length) {
      var term = self.getTermFromUrl();
      self.loadTerms(term, false);

      $(window).bind('popstate', function (e) {
        var term = self.getTermFromUrl();
        self.loadTerms(term, false);
      });
    }
  };

  // Examines window.location to see if we are starting at a given term; if so, returns that term.
  // If we are at the top level, returns null.
  self.getTermFromUrl = function() {

    // TODO: this will break if we ever have more than one parameter on this page.
    var pieces = window.location.href.split('?path=');
    var term = '/';
    if (pieces.length == 2) {
      term = decodeURI(pieces[1]);
    }
    return term;

  };

  // Renders the browser, given a JSON list of subjects.
  // If pushState is true, we will push the current state onto the browser history.
  self.renderTerms = function (terms, pushState) {
    var termList = '';
    var parent = '/';
    for (var i = 0; i < terms.length; i++) {
      var fullPath = terms[i].subject;
      var levels = fullPath.split('/');
      var leaf = levels[levels.length - 1];

      // Get parent term if there is one.  Only do this once for efficiency since all terms
      // will have the same parent.
      if (i == 0 && levels.length > 2) {
        for (var j = 0; j < levels.length - 1; j++) {
          if (j > 1) {
            parent += '/';
          }
          parent += levels[j];
        }
      }

      var termHtml = $('#subject-term-template').html();
      termHtml = termHtml.replace('__TAXONOMY_TERM_ESCAPED__', leaf);
      termHtml = termHtml.replace('__TAXONOMY_TERM_LEAF__', leaf);
      termHtml = termHtml.replace('__TAXONOMY_TERM_FULL_PATH__', fullPath);
      var childLinkStyle = 'browse-further browse-right';
      if (terms[i].childCount === 0) {
        childLinkStyle += ' inactive';
      }
      termHtml = termHtml.replace('__CHILD_LINK_STYLE__', childLinkStyle);
      termList += termHtml;
    }
    var html = $('#subject-list-template').html();
    html = html.replace('__TAXONOMY_LINKS__', termList);
    $('#browse-container').html(html);
    $('a.browse-further:not(.inactive)').click(function (e) {
      self.loadTerms($(this).data('term'), true);
    });

    if (pushState) {
      self.pushState(parent);
      $('body').addClass('historyPushed');
    }
  };

  // Saves the current state to the browser history, so the back button functions correctly.
  // Term should be the parent term of the ones we are currently displaying.
  self.pushState = function(term) {
    var url = 'browse';
    var title = 'browse';
    if (term) {
      url += '?path=' + term;
      title = term;
    }
    window.history.pushState(null, title, url);
  };

  // Loads the child terms given a parent term.  If the parent evaluates to false,
  // the root taxonomy terms will be loaded.
  self.loadTerms = function (parent, pushState) {
    var url = 'taxonomy';
    if (parent) {
      url += parent;
    } else {
      url += '/';
    }
    $.ajax(url, {
      type: 'GET',
      success: function (data) {
        self.renderTerms(data, pushState);
      },
      error: function (xOptions, textStatus) {
        console.log('Error loading term ' + parent + ': ' + textStatus);
      }
    });
  };
};

$(document).ready(function () {
  var browser = new TaxonomyBrowser();
  browser.init();
});
<commit_msg>DPRO-396: replace spaces with '+' in mobile taxonomy links<commit_after>// Javascript controlling the taxonomy browser.

var TaxonomyBrowser = function () {
  var self = this;

  self.init = function () {

    self.$browserDiv = $('#browse-container');

    if (self.$browserDiv.length) {
      var term = self.getTermFromUrl();
      self.loadTerms(term, false);

      $(window).bind('popstate', function (e) {
        var term = self.getTermFromUrl();
        self.loadTerms(term, false);
      });
    }
  };

  // Examines window.location to see if we are starting at a given term; if so, returns that term.
  // If we are at the top level, returns null.
  self.getTermFromUrl = function() {

    // TODO: this will break if we ever have more than one parameter on this page.
    var pieces = window.location.href.split('?path=');
    var term = '/';
    if (pieces.length == 2) {
      term = decodeURI(pieces[1]);
    }
    return term;

  };

  // Renders the browser, given a JSON list of subjects.
  // If pushState is true, we will push the current state onto the browser history.
  self.renderTerms = function (terms, pushState) {
    var termList = '';
    var parent = '/';
    for (var i = 0; i < terms.length; i++) {
      var fullPath = terms[i].subject;
      var levels = fullPath.split('/');
      var leaf = levels[levels.length - 1];

      // Get parent term if there is one.  Only do this once for efficiency since all terms
      // will have the same parent.
      if (i == 0 && levels.length > 2) {
        for (var j = 0; j < levels.length - 1; j++) {
          if (j > 1) {
            parent += '/';
          }
          parent += levels[j];
        }
      }

      var termHtml = $('#subject-term-template').html();
      termHtml = termHtml.replace('__TAXONOMY_TERM_ESCAPED__', leaf);
      termHtml = termHtml.replace('__TAXONOMY_TERM_LEAF__', leaf.replace(/ /g, '+'));
      termHtml = termHtml.replace('__TAXONOMY_TERM_FULL_PATH__', fullPath);
      var childLinkStyle = 'browse-further browse-right';
      if (terms[i].childCount === 0) {
        childLinkStyle += ' inactive';
      }
      termHtml = termHtml.replace('__CHILD_LINK_STYLE__', childLinkStyle);
      termList += termHtml;
    }
    var html = $('#subject-list-template').html();
    html = html.replace('__TAXONOMY_LINKS__', termList);
    $('#browse-container').html(html);
    $('a.browse-further:not(.inactive)').click(function (e) {
      self.loadTerms($(this).data('term'), true);
    });

    if (pushState) {
      self.pushState(parent);
      $('body').addClass('historyPushed');
    }
  };

  // Saves the current state to the browser history, so the back button functions correctly.
  // Term should be the parent term of the ones we are currently displaying.
  self.pushState = function(term) {
    var url = 'browse';
    var title = 'browse';
    if (term) {
      url += '?path=' + term;
      title = term;
    }
    window.history.pushState(null, title, url);
  };

  // Loads the child terms given a parent term.  If the parent evaluates to false,
  // the root taxonomy terms will be loaded.
  self.loadTerms = function (parent, pushState) {
    var url = 'taxonomy';
    if (parent) {
      url += parent;
    } else {
      url += '/';
    }
    $.ajax(url, {
      type: 'GET',
      success: function (data) {
        self.renderTerms(data, pushState);
      },
      error: function (xOptions, textStatus) {
        console.log('Error loading term ' + parent + ': ' + textStatus);
      }
    });
  };
};

$(document).ready(function () {
  var browser = new TaxonomyBrowser();
  browser.init();
});
<|endoftext|>


<commit_before>jest.autoMockOff();

const babel = require('babel-core');

function transform(code) {
  return babel.transform(code,  {
    plugins: [require('../index')],
  }).code;
}

describe('mangle-names', () => {
  it('should not mangle names in the global namespace', () => {
    const source = unpad(`
      var Foo = 1;
    `);
    const expected = unpad(`
      var Foo = 1;
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should mangle names', () => {
    const source = unpad(`
      function foo() {
        var xxx = 1;
        if (xxx) {
          console.log(xxx);
        }
      }
    `);
    const expected = unpad(`
      function foo() {
        var a = 1;
        if (a) {
          console.log(a);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should handle name collisions', () => {
    const source = unpad(`
      function foo() {
        var x = 2;
        var xxx = 1;
        if (xxx) {
          console.log(xxx + x);
        }
      }
    `);
    const expected = unpad(`
      function foo() {
        var a = 2;
        var b = 1;
        if (b) {
          console.log(b + a);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should be fine with shadowing', () => {
    const source = unpad(`
      var a = 1;
      function foo() {
        var xxx = 1;
        if (xxx) {
          console.log(xxx);
        }
      }
    `);
    const expected = unpad(`
      var a = 1;
      function foo() {
        var a = 1;
        if (a) {
          console.log(a);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should not shadow outer references', () => {
    const source = unpad(`
      function bar() {
        function foo(a, b, c) {
          lol(a,b,c);
        }

        function lol() {}
      }
    `);
    const expected = unpad(`
      function bar() {
        function a(c, d, e) {
          b(c, d, e);
        }

        function b() {}
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should not shadow outer references 2', () => {
    const source = `
__d(function(require) {
var ErrorUtilsConfig = {};

var eprintf = require('eprintf');
var erx = require('erx');
var removeFromArray = require('removeFromArray');

var ANONYMOUS_GUARD_TAG = '<anonymous guard>';
var GENERATED_GUARD_TAG = '<generated guard>';
var GLOBAL_ERROR_HANDLER_TAG = (typeof window === 'undefined') ?
  '<self.onerror>' : // It would be better if self is replaced by worker name
  '<window.onerror>';

var HTTP_OR_HTTPS_URI_PATTERN = /^https?:\/\//i;
var TYPECHECKER_ERROR_PATTERN = /^Type Mismatch for/;

// These are possible values in stack frame's script property besides normal
// URIs when it's IE. If you saw them in normalized stack frames, e.g. Scuba
// x_js_error, you can look up their meanings here.
var IE_STACK_TRACE_REFERENCES = [
  'Unknown script code', // (probably programmatically) injected script tag,
  'Function code',
  'eval code'
];
var IE_STACK_FRAME_PATTERN =
  new RegExp('(.*?)(\\s)(?:' + IE_STACK_TRACE_REFERENCES.join('|') + ')$');

var IE_AND_OTHER_FRAME_PATTERN = /(.*)(@|\s)[^\s]+$/;

// Callbacks to notify of errors
var listeners = [];

// Source resolver is only set and used by m-site when ScriptLoader is in use
var sourceResolver;

// Cache of the first MAX_HISTORY errors in the page
var history = [];
var MAX_HISTORY = 50;

var guardList = [];

// Returns true if we're inside applyWithGuard() call
var isGuarding = false;

// Returns true if we're currently reporting errors to listeners
// during that time further errors won't be reported to avoid infinite loops
var isReporting = false;

var nocatch =
  ErrorUtilsConfig.nocatch ||
  (/nocatch/).test(location.search);

/**
 * Normalizes the stack trace for Opera, Firefox and Chrome into the format used
 * by Chrome.
 */
function normalizeStack(input) {
  if (!input) {
    return [];
  }
  var stack = input
      .map(function(frame) {
    var identifier, line, col;

    frame = frame.trim();
    // First extract the line and col, these are always in the same format
    if (/(:(\d+)(:(\d+))?)$/.test(frame)) {
      line = RegExp.$2;
      col = RegExp.$4;
      frame = frame.slice(0, -RegExp.$1.length);
    }
    // Now, extract the part matching the function identifier.

    if (
      IE_STACK_FRAME_PATTERN.test(frame) || /* IE */
      IE_AND_OTHER_FRAME_PATTERN.test(frame) /* IE and Everyone else */
    ) {
      frame = frame.substring(RegExp.$1.length + 1);
      identifier =
        /(at)?\s*(.*)([^\s]+|$)/.test(RegExp.$1) ? RegExp.$2 : '';
    }

    var stackFrame = {
      identifier: identifier,
      script: frame,
      line: line,
      column: col
    };

    if (sourceResolver) {
      sourceResolver(stackFrame);
    }

    // return using a pattern matching that of Chrome
    stackFrame.text = '    at'
      + (stackFrame.identifier ? ' ' + stackFrame.identifier + ' (' : ' ')
      + stackFrame.script
      + (stackFrame.line ? ':' + stackFrame.line : '')
      + (stackFrame.column ? ':' + stackFrame.column : '')
      + (stackFrame.identifier ? ')' : '');

    return stackFrame;
  });

  return stack;
}

/**
 * Normalize properties in Error objects across browsers. This has the dual
 * benefits of copying the state off an error object (which tends to get GC'ed
 * at unexpected/awkward times) and providing predictable names for that state.
 *
 * @see http://broofa.com/tests/ErrorProperties.htm
 */
function normalizeError(err) {
  if (!err) {
    return {};
  } else if (err._originalError) {
    return err;
  }

  var stackData = normalizeStack(err.stackTrace || err.stack);
  var stackPopped = false;

  if (err.framesToPop) {
    // used by TypeChecker, invariant and other error throwers.
    var framesToPop = err.framesToPop;
    var lastPoppedFrame;
    while (framesToPop > 0 && stackData.length > 0) {
      lastPoppedFrame = stackData.shift();
      framesToPop--;
      stackPopped = true;
    }
    if (
      TYPECHECKER_ERROR_PATTERN.test(err.message) &&
      err.framesToPop === 2 &&
      lastPoppedFrame
    ) {
      // this is for TypeChecker. in order to avoid grouping different type
      // check error with same argument name and type together, we append uri
      // and line to the error message. we do that when they can be mapped back
      // to source code, otherwise we would separate same error with different
      // messages.
      if (HTTP_OR_HTTPS_URI_PATTERN.test(lastPoppedFrame.script)) {
        err.message += ' at ' + lastPoppedFrame.script
          + (lastPoppedFrame.line ? ':' + lastPoppedFrame.line : '')
          + (lastPoppedFrame.column ? ':' + lastPoppedFrame.column : '');
      }
    }
    delete err.framesToPop;
  }

  var info = {
    line:
      err.lineNumber ||
      err.line,
    column:
      err.columnNumber ||
      err.column,
    name: err.name,
    message: err.message,
    messageWithParams: err.messageWithParams,
    type: err.type,
    script:
      err.fileName ||
      err.sourceURL ||
      err.script,
    stack: stackData.map(function(frame) { return frame.text; }).join(''),
    stackFrames: stackData,
    guard: err.guard,
    guardList: err.guardList,
    extra: err.extra, /* tags to override MJSErrorExtra */
    snapshot: err.snapshot /* usually from DocumentSnapShot */
  };

  if (typeof info.message === 'string' && !info.messageWithParams) {
    info.messageWithParams = erx(info.message);
    info.message = eprintf.apply(global, info.messageWithParams);
  } else {
    info.messageObject = info.message;
    info.message = String(info.message);
  }

  // because error has script and line properties just like a stack frame,
  // we can pass it to sourceResolver just like a stack frame.
  if (sourceResolver) {
    sourceResolver(info);
  }

  // if first stack is popped, original script, line, column properties are
  // wrong, and they should be filled by current first stack or left empty.
  if (stackPopped) {
    delete info.script;
    delete info.line;
    delete info.column;
  }

  // fill in missing script, line, column properties from first stack frame.
  if (stackData[0]) {
    info.script = info.script || stackData[0].script;
    info.line = info.line || stackData[0].line;
    info.column = info.column || stackData[0].column;
  }

  // Keep a reference to the original error
  info._originalError = err;

  // Clear out unspecified properties
  for (var k in info) {
    (info[k] == null && delete info[k]);
  }
  return info;
}

/**
 * @param err Error to report (will be normalized as necessary)
 * @param quiet suppresses console output if true
 */
function reportError(err, quiet) {
  if (isReporting) {
    // already in the process of reporting errors
    console.error('Error reported during error processing', err);
    return false;
  }

  // fill in guard and guardList properties even if it's not caught by
  // applyWithGuard as long as there is any guard in context
  if (guardList.length > 0) {
    err.guard = err.guard || guardList[0];
    err.guardList = guardList.slice();
  }

  err = normalizeError(err);
  if (!quiet) {
    // Stack traces that point here are probably wrong.  err.stack may
    // contain the correct trace.  To fix this, use the 'js_nocatch'
    // gatekeeper to opt out of error catching/guarding.
    console.error(err._originalError.message + '' +
      err.stack + '' +
      'Original error:' + err._originalError);
  }

  // Cache early errors for playback to listeners
  if (history.length > MAX_HISTORY) {
    history.splice(MAX_HISTORY / 2, 1);
  }
  history.push(err);

  isReporting = true;
  for (var i = 0; i < listeners.length; i++) {
    try {
      listeners[i](err);
    } catch (e) {
      console.error('Error thrown from listener during error processing', e);
    }
  }
  isReporting = false;
  return true;
}

// Returns true if we're inside applyWithGuard() call
function inGuard() {
  return isGuarding;
}

function pushGuard(name) {
  guardList.unshift(name);
  isGuarding = true;
}

function popGuard() {
  guardList.shift();
  isGuarding = (guardList.length !== 0);
}

/**
 * Call a function while guarding against errors.
 *
 * @param func (Function) function to invoke
 * @param context (Object) 'this' context
 * @param args (Array) arguments to pass to func
 * @param onError (Function) Called if an error occurs.  Gets one argument, the
 *                normalized error object that will be passed to ERROR event
 *                listeners
 * @param name (?String) name of the guard and will be used as guard property
 *             of the error
 */
function applyWithGuard(func, context, args, onError, name) {
  pushGuard(name || ANONYMOUS_GUARD_TAG);

  var returnValue;

  // TODO (cpojer|#2497966): Remove this after disabling channel iframe for
  // IE8-9 and use ErrorUtilsConfig. This check is inlined in applyWithGuard

  if (require('Env').nocatch) {
    nocatch = true;
  }

  if (nocatch) {
    try {
      returnValue = func.apply(context, args || []);
    } finally {
      // IE: finally block won't be triggered if there's no catch block, and
      //     this only happens when testing with IE on sandbox. details:
      //     http://fburl.com/ie-try-finally-bug
      popGuard();
    }
    return returnValue;
  }

  try {
    // IE8: Function#apply throws if you pass null args parameter
    returnValue = func.apply(context, args || []);
    return returnValue;
  } catch (ex) {
    var err = normalizeError(ex);
    if (onError) {
      onError(err);
    }

    // function args can provide valuable debug info. add it to normalized err
    if (func) {
      err.callee = func.toString().substring(0, 100);
    }
    if (args) {
      err.args = Array.prototype.slice.call(args).toString().substring(0, 100);
    }
    err.guard = guardList[0]; // for compatibility of original single guard
    err.guardList = guardList.slice();

    if (__DEV__) {
      // Warn (once) about error catching being enabled
      if (!nocatch && !applyWithGuard.warned) {
        console.warn('Note: Error catching is enabled, which may lead to ' +
          'misleading stack traces in the JS debugger.  To disable, ' +
          'whitelist yourself in the "js_nocatch" gatekeeper.  See ' +
          'ErrorUtils.js for more info.');
        applyWithGuard.warned = true;
      }
    }

    reportError(err);
  } finally {
    popGuard();
  }
}
});
    `;
    const expected = unpad(`
      function bar(a) {
        function a(c, d, e) {
          b(c, d, e);
        }

        function b() {}
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should mangle args', () => {
    const expected = unpad(`
      function foo(a) {
        if (a) {
          console.log(a);
        }
      }
    `);
    const source = unpad(`
      function foo(xxx) {
        if (xxx) {
          console.log(xxx);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });
});

function unpad(str) {
  const lines = str.split('\n');
  const m = lines[1] && lines[1].match(/^\s+/);
  if (!m) {
    return str;
  }
  const spaces = m[0].length;
  return lines.map(
    line => line.slice(spaces)
  ).join('\n').trim();
}
<commit_msg>remove random test case<commit_after>jest.autoMockOff();

const babel = require('babel-core');

function transform(code) {
  return babel.transform(code,  {
    plugins: [require('../index')],
  }).code;
}

describe('mangle-names', () => {
  it('should not mangle names in the global namespace', () => {
    const source = unpad(`
      var Foo = 1;
    `);
    const expected = unpad(`
      var Foo = 1;
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should mangle names', () => {
    const source = unpad(`
      function foo() {
        var xxx = 1;
        if (xxx) {
          console.log(xxx);
        }
      }
    `);
    const expected = unpad(`
      function foo() {
        var a = 1;
        if (a) {
          console.log(a);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should handle name collisions', () => {
    const source = unpad(`
      function foo() {
        var x = 2;
        var xxx = 1;
        if (xxx) {
          console.log(xxx + x);
        }
      }
    `);
    const expected = unpad(`
      function foo() {
        var a = 2;
        var b = 1;
        if (b) {
          console.log(b + a);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should be fine with shadowing', () => {
    const source = unpad(`
      var a = 1;
      function foo() {
        var xxx = 1;
        if (xxx) {
          console.log(xxx);
        }
      }
    `);
    const expected = unpad(`
      var a = 1;
      function foo() {
        var a = 1;
        if (a) {
          console.log(a);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should not shadow outer references', () => {
    const source = unpad(`
      function bar() {
        function foo(a, b, c) {
          lol(a,b,c);
        }

        function lol() {}
      }
    `);
    const expected = unpad(`
      function bar() {
        function a(c, d, e) {
          b(c, d, e);
        }

        function b() {}
      }
    `);

    expect(transform(source)).toBe(expected);
  });

  it('should mangle args', () => {
    const expected = unpad(`
      function foo(a) {
        if (a) {
          console.log(a);
        }
      }
    `);
    const source = unpad(`
      function foo(xxx) {
        if (xxx) {
          console.log(xxx);
        }
      }
    `);

    expect(transform(source)).toBe(expected);
  });
});

function unpad(str) {
  const lines = str.split('\n');
  const m = lines[1] && lines[1].match(/^\s+/);
  if (!m) {
    return str;
  }
  const spaces = m[0].length;
  return lines.map(
    line => line.slice(spaces)
  ).join('\n').trim();
}
<|endoftext|>


<commit_before>import React from 'react';

class Home extends React.Component {
  render() {
    return (

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.
View details

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.
View details

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.
View details

    );
  }
}

export default Home;
<commit_msg>Connected home component to redux store<commit_after>import React from 'react';
import {connect} from 'react-redux'
import Messages from './Messages';

class Home extends React.Component {
  render() {
    return (

        <Messages messages={this.props.messages}/>

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor
                  mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna
                  mollis euismod. Donec sed odio dui.
View
                details

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor
                  mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna
                  mollis euismod. Donec sed odio dui.
View
                details

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor
                  mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna
                  mollis euismod. Donec sed odio dui.
View
                details

    );
  }
}

const mapStateToProps = (state) => {
  return {
    messages: state.messages
  };
};

export default connect(mapStateToProps)(Home);
<|endoftext|>


<commit_before>import { join } from 'path';
import { mkdirs, copy, replaceCode, addNpmPackage } from '../utils';

// helper function
async function updateLayoutTemplate(params) {
  const layout = join(__base, 'build', params.uuid, 'views', 'layout.jade');

  const appContainer = join(__dirname, 'modules', 'jade', 'app-container.jade');
  const blockContent = join(__dirname, 'modules', 'jade', 'block-content.jade');
  const socketIoImport = join(__dirname, 'modules', 'jade', 'socketio-import.jade');

  if (params.jsFramework) {
    // Use "#app-container" div element (single page app)
    await replaceCode(layout, 'APP_CONTAINER_OR_BLOCK_CONTENT', appContainer, { indentLevel: 2 });
  } else {
    // Use "block content" (traditional web app)
    await replaceCode(layout, 'APP_CONTAINER_OR_BLOCK_CONTENT', blockContent, { indentLevel: 2 });
  }

  // Add Socket.IO <script> tag (optional)
  if (params.frameworkOptions.includes('socketio')) {
    await replaceCode(layout, 'SOCKETIO_IMPORT', socketIoImport, { indentLevel: 2 });
  }
}

// helper function
async function copyTemplates(params) {
  const views = join(__base, 'build', params.uuid, 'views');
  const layout = join(__dirname, 'modules', 'jade', 'views', 'layout.jade');

  await copy(layout, join(views, 'layout.jade'));

  if (!params.jsFramework) {
    const footer = join(__dirname, 'modules', 'jade', 'views', 'footer.jade');
    const header = join(__dirname, 'modules', 'jade', 'views', `header-${params.cssFramework}.jade`);
    const headerAuth = join(__dirname, 'modules', 'jade', 'views', `header-auth-${params.cssFramework}.jade`);
    const home = join(__dirname, 'modules', 'jade', 'views', `home-${params.cssFramework}.jade`);
    const contact = join(__dirname, 'modules', 'jade', 'views', `contact-${params.cssFramework}.jade`);

    await copy(footer, join(views, 'includes', 'footer.jade'));
    await copy(header, join(views, 'includes', 'header.jade'));
    await copy(home, join(views, 'home.jade'));
    await copy(contact, join(views, 'contact.jade'));

    // Is authentication checked? Then add log in, sign up, logout links to the header
    if (params.authentication.length) {
      const headerAuthIndent = {
        none: 2,
        bootstrap: 2,
        foundation: 3
      };
      await replaceCode(join(views, 'includes', 'header.jade'), 'HEADER_AUTH', headerAuth, { indentLevel: headerAuthIndent[params.cssFramework] });
    }
  }
}

async function generateJadeTemplateEngine(params) {
  switch (params.framework) {
    case 'express':
      const server = join(__base, 'build', params.uuid, 'server.js');
      const expressViewEngine = join(__dirname, 'modules', 'jade', 'jade-express.js');
      const expressHomeRoute = join(__dirname, 'modules', 'routes', 'home-route-express.js');
      const homeControllerRequire = join(__dirname, 'modules', 'controllers', 'home-require.js');
      const expressHomeController = join(__dirname, 'modules', 'controllers', 'home-controller-express.js');

      // Set "views dir" and "view engine" Express settings
      await replaceCode(server, 'TEMPLATE_ENGINE', expressViewEngine);

      if (!params.jsFramework) {
        // Require home controller and add "/" route
        await replaceCode(server, 'HOME_ROUTE', expressHomeRoute);
        await replaceCode(server, 'HOME_CONTROLLER', homeControllerRequire);
        // Copy home controller
        await copy(expressHomeController, join(__base, 'build', params.uuid, 'controllers', 'home.js'));
      }

      // Copy Jade templates
      await copyTemplates(params);

      // Add/remove features to the newly generated layout file above
      await updateLayoutTemplate(params);
      break;

    case 'meteor':
      break;

    default:
  }

  // Add Jade to package.json
  await addNpmPackage('jade', params);
}

export default generateJadeTemplateEngine;
<commit_msg>Fixed bootstrap HEADER_AUTH indent in Jade template<commit_after>import { join } from 'path';
import { mkdirs, copy, replaceCode, addNpmPackage } from '../utils';

// helper function
async function updateLayoutTemplate(params) {
  const layout = join(__base, 'build', params.uuid, 'views', 'layout.jade');

  const appContainer = join(__dirname, 'modules', 'jade', 'app-container.jade');
  const blockContent = join(__dirname, 'modules', 'jade', 'block-content.jade');
  const socketIoImport = join(__dirname, 'modules', 'jade', 'socketio-import.jade');

  if (params.jsFramework) {
    // Use "#app-container" div element (single page app)
    await replaceCode(layout, 'APP_CONTAINER_OR_BLOCK_CONTENT', appContainer, { indentLevel: 2 });
  } else {
    // Use "block content" (traditional web app)
    await replaceCode(layout, 'APP_CONTAINER_OR_BLOCK_CONTENT', blockContent, { indentLevel: 2 });
  }

  // Add Socket.IO <script> tag (optional)
  if (params.frameworkOptions.includes('socketio')) {
    await replaceCode(layout, 'SOCKETIO_IMPORT', socketIoImport, { indentLevel: 2 });
  }
}

// helper function
async function copyTemplates(params) {
  const views = join(__base, 'build', params.uuid, 'views');
  const layout = join(__dirname, 'modules', 'jade', 'views', 'layout.jade');

  await copy(layout, join(views, 'layout.jade'));

  if (!params.jsFramework) {
    const footer = join(__dirname, 'modules', 'jade', 'views', 'footer.jade');
    const header = join(__dirname, 'modules', 'jade', 'views', `header-${params.cssFramework}.jade`);
    const headerAuth = join(__dirname, 'modules', 'jade', 'views', `header-auth-${params.cssFramework}.jade`);
    const home = join(__dirname, 'modules', 'jade', 'views', `home-${params.cssFramework}.jade`);
    const contact = join(__dirname, 'modules', 'jade', 'views', `contact-${params.cssFramework}.jade`);

    await copy(footer, join(views, 'includes', 'footer.jade'));
    await copy(header, join(views, 'includes', 'header.jade'));
    await copy(home, join(views, 'home.jade'));
    await copy(contact, join(views, 'contact.jade'));

    // Is authentication checked? Then add log in, sign up, logout links to the header
    if (params.authentication.length) {
      const headerAuthIndent = {
        none: 2,
        bootstrap: 3,
        foundation: 3
      };
      await replaceCode(join(views, 'includes', 'header.jade'), 'HEADER_AUTH', headerAuth, { indentLevel: headerAuthIndent[params.cssFramework] });
    }
  }
}

async function generateJadeTemplateEngine(params) {
  switch (params.framework) {
    case 'express':
      const server = join(__base, 'build', params.uuid, 'server.js');
      const expressViewEngine = join(__dirname, 'modules', 'jade', 'jade-express.js');
      const expressHomeRoute = join(__dirname, 'modules', 'routes', 'home-route-express.js');
      const homeControllerRequire = join(__dirname, 'modules', 'controllers', 'home-require.js');
      const expressHomeController = join(__dirname, 'modules', 'controllers', 'home-controller-express.js');

      // Set "views dir" and "view engine" Express settings
      await replaceCode(server, 'TEMPLATE_ENGINE', expressViewEngine);

      if (!params.jsFramework) {
        // Require home controller and add "/" route
        await replaceCode(server, 'HOME_ROUTE', expressHomeRoute);
        await replaceCode(server, 'HOME_CONTROLLER', homeControllerRequire);
        // Copy home controller
        await copy(expressHomeController, join(__base, 'build', params.uuid, 'controllers', 'home.js'));
      }

      // Copy Jade templates
      await copyTemplates(params);

      // Add/remove features to the newly generated layout file above
      await updateLayoutTemplate(params);
      break;

    case 'meteor':
      break;

    default:
  }

  // Add Jade to package.json
  await addNpmPackage('pug', params);
}

export default generateJadeTemplateEngine;
<|endoftext|>