<commit_before>var idom = IncrementalDOM;

var now;
if (window.performance) {
    now = function () {
        return window.performance.now();
    };
}
else {
    now = function () {
        return new Date().getTime();
    };
}

function section(heading, f) {
    var section = document.createElement('section');
    var h2 = document.createElement('h2');
    h2.textContent = heading;
    section.appendChild(h2);
    var span = document.createElement('span');
    span.textContent = 'Running...';
    section.appendChild(span);
    var container = document.getElementById('results');
    container.appendChild(section);
    var results = {};
    function bench(name, f) {
        var container = document.getElementById('output');
        f(container, function (iterations, patch) {
            var sample = [];
            var fastest = Infinity;
            var slowest = 0;
            var start = now();
            for (var i = 0; i < iterations; i++) {
                var istart = now();
                patch(i);
                var iend = now();
                var iduration = iend - istart;
                if (i % 10 === 0) {
                    sample.push(iduration);
                }
                if (iduration > slowest) {
                    slowest = iduration;
                }
                if (iduration < fastest) {
                    fastest = iduration;
                }
            }
            var end = now();
            var data = {
                fastest: fastest,
                slowest: slowest,
                total: (end - start),
                average: (end - start) / iterations,
                iterations: iterations,
                sample: sample
            };
            results[name] = data;
        });
    }
    f(bench);
    span.textContent = 'Total time (ms)';
    var responsiveOptions = {};
    var chart = document.createElement('div');
    chart.style = 'height: 200px; width: 80%;';
    container.appendChild(chart);
    chart.className = 'ct-chart ct-perfect-fourth';
    var data = {
        labels: Object.keys(results),
        series: [
            Object.keys(results).map(function (name) {
                return results[name].total;
            })
        ]
    };
    var options = {
        seriesBarDistance: 1,
        reverseData: true,
        horizontalBars: true,
        axisY: {
            offset: 100
        }
    };
    new Chartist.Bar(chart, data, options, responsiveOptions);
}

function createTemplateNode(id, src) {
    var el = document.getElementById(id);
    if (!el) {
        el = document.createElement('template');
        document.body.appendChild(el);
        el.id = id;
    }
    el.innerHTML = src;
    return el;
}

section('Add 100 elements to a list, one at a time - no keys', function (bench) {
    bench('Magery', function (container, iter) {
        createTemplateNode('app',
              '
' +
                '<template-each name="item" in="items">' +
                  '
{{item.name}}
' +
                '</template-each>' +
              '
'
        );
        var data = {items: []};
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.push({name: 'item' + i});
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement('li', null, item.name);
                }));
            }
        });
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({name: 'item' + i});
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', '', null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({name: 'item' + i});
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Add 100 elements to a list, one at a time - keys', function (bench) {

    bench('Magery', function (container, iter) {
        createTemplateNode('app',
              '
' +
                '<template-each name="item" in="items" key="id">' +
                  '
{{item.name}}
' +
                '</template-each>' +
              '
'
        );
        var data = {items: []};
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.push({id: i, name: 'item' + i});
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var Item = React.createClass({
            shouldComponentUpdate: function(nextProps, nextState) {
                return nextProps.item.id !== this.props.item.id;
            },
            render: function () {
                return React.createElement('li', null, this.props.item.name);
            }
        });
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement(Item, {key: item.id, item: item});
                }));
            }
        });
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({id: i, name: 'item' + i});
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', item.id, null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({id: i, name: 'item' + i});
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Randomly remove elements from 100 length list, one at a time - no keys', function (bench) {

    function random(max) {
        return Math.floor(Math.random() * (max + 1));
    }

    bench('Magery', function (container, iter) {
        createTemplateNode('app',
                '
' +
                    '<template-each name="item" in="items">' +
                        '
{{item.name}}
' +
                    '</template-each>' +
                '
'
        );
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({name: 'item' + i});
        }
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.splice(random(app.context.items.length - 1), 1);
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var Item = React.createClass({
            shouldComponentUpdate: function(nextProps, nextState) {
                return nextProps.item.id !== this.props.item.id;
            },
            render: function () {
                return React.createElement('li', null, this.props.item.name);
            }
        });
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement(Item, {item: item});
                }));
            }
        });
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', '', null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Randomly remove elements from 100 length list, one at a time - keys', function (bench) {

    function random(max) {
        return Math.floor(Math.random() * (max + 1));
    }

    bench('Magery', function (container, iter) {
        createTemplateNode('app',
                '
' +
                    '<template-each name="item" in="items" key="id">' +
                        '
{{item.name}}
' +
                    '</template-each>' +
                '
'
        );
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({id: i, name: 'item' + i});
        }
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.splice(random(app.context.items.length - 1), 1);
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var Item = React.createClass({
            shouldComponentUpdate: function(nextProps, nextState) {
                return nextProps.item.id !== this.props.item.id;
            },
            render: function () {
                return React.createElement('li', null, this.props.item.name);
            }
        });
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement(Item, {key: item.id, item: item});
                }));
            }
        });
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({id: i, name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', item.id, null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({id: i, name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Live update a managed text box', function (bench) {

    function input(el, value){
        var ev = new InputEvent('input');
        el.value = value;
        el.dispatchEvent(ev);
    }

    var test_string = 'This is a test of how quickly input events update a textbox';

    bench('Magery', function (container, iter) {
        createTemplateNode(
            'app',
            '<input type="text" id="testInput" value="{{name}}" oninput="updateInput(event)" />'
        );
        var data = {name: ''};
        var app = Magery.bind(container, 'app', data, {
            updateInput: function (ev) {
                this.context.name = ev.target.value;
            }
        });
        var el = document.getElementById('testInput');
        iter(test_string.length, function (i) {
            input(el, test_string.substring(0, i + 1));
        });
    });

    bench('React', function (container, iter) {
        var data = {name: ''};
        var App = React.createClass({
            render: function () {
                return React.createElement('input', {
                    type: 'text',
                    id: 'testInput',
                    value: this.props.name,
                    onInput: this.props.updateInput
                });
            }
        });
        var updateInput = function (ev) {
            data.name = ev.target.value;
            ReactDOM.render(React.createElement(App, {name: data.name, updateInput: updateInput}), container);
        };
        var el = document.getElementById('testInput');
        iter(100, function (i) {
            input(el, test_string.substring(0, i + 1));
        });
    });

});
<commit_msg>Update simple benchmarks to use new API<commit_after>var idom = IncrementalDOM;

var now;
if (window.performance) {
    now = function () {
        return window.performance.now();
    };
}
else {
    now = function () {
        return new Date().getTime();
    };
}

function section(heading, f) {
    var section = document.createElement('section');
    var h2 = document.createElement('h2');
    h2.textContent = heading;
    section.appendChild(h2);
    var span = document.createElement('span');
    span.textContent = 'Running...';
    section.appendChild(span);
    var container = document.getElementById('results');
    container.appendChild(section);
    var results = {};
    function bench(name, f) {
        var container = document.getElementById('output');
        f(container, function (iterations, patch) {
            var sample = [];
            var fastest = Infinity;
            var slowest = 0;
            var start = now();
            for (var i = 0; i < iterations; i++) {
                var istart = now();
                patch(i);
                var iend = now();
                var iduration = iend - istart;
                if (i % 10 === 0) {
                    sample.push(iduration);
                }
                if (iduration > slowest) {
                    slowest = iduration;
                }
                if (iduration < fastest) {
                    fastest = iduration;
                }
            }
            var end = now();
            var data = {
                fastest: fastest,
                slowest: slowest,
                total: (end - start),
                average: (end - start) / iterations,
                iterations: iterations,
                sample: sample
            };
            results[name] = data;
        });
    }
    f(bench);
    span.textContent = 'Total time (ms)';
    var responsiveOptions = {};
    var chart = document.createElement('div');
    chart.style = 'height: 200px; width: 80%;';
    container.appendChild(chart);
    chart.className = 'ct-chart ct-perfect-fourth';
    var data = {
        labels: Object.keys(results),
        series: [
            Object.keys(results).map(function (name) {
                return results[name].total;
            })
        ]
    };
    var options = {
        seriesBarDistance: 1,
        reverseData: true,
        horizontalBars: true,
        axisY: {
            offset: 100
        }
    };
    new Chartist.Bar(chart, data, options, responsiveOptions);
}

function createTemplateNode(id, src) {
    var el = document.getElementById(id);
    if (!el) {
        el = document.createElement('template');
        document.body.appendChild(el);
        el.id = id;
    }
    el.innerHTML = src;
    return el;
}

section('Add 100 elements to a list, one at a time - no keys', function (bench) {
    bench('Magery', function (container, iter) {
        createTemplateNode('app',
              '
' +
                '
' +
                  '{{item.name}}' +
                '
' +
              '
'
        );
        var data = {items: []};
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.push({name: 'item' + i});
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement('li', null, item.name);
                }));
            }
        });
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({name: 'item' + i});
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', '', null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({name: 'item' + i});
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Add 100 elements to a list, one at a time - keys', function (bench) {

    bench('Magery', function (container, iter) {
        createTemplateNode('app',
              '
' +
                '
' +
                  '{{item.name}}' +
                '
' +
              '
'
        );
        var data = {items: []};
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.push({id: i, name: 'item' + i});
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var Item = React.createClass({
            shouldComponentUpdate: function(nextProps, nextState) {
                return nextProps.item.id !== this.props.item.id;
            },
            render: function () {
                return React.createElement('li', null, this.props.item.name);
            }
        });
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement(Item, {key: item.id, item: item});
                }));
            }
        });
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({id: i, name: 'item' + i});
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', item.id, null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        iter(100, function (i) {
            data.items.push({id: i, name: 'item' + i});
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Randomly remove elements from 100 length list, one at a time - no keys', function (bench) {

    function random(max) {
        return Math.floor(Math.random() * (max + 1));
    }

    bench('Magery', function (container, iter) {
        createTemplateNode('app',
                '
' +
                    '
' +
                        '{{item.name}}' +
                    '
' +
                '
'
        );
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({name: 'item' + i});
        }
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.splice(random(app.context.items.length - 1), 1);
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var Item = React.createClass({
            shouldComponentUpdate: function(nextProps, nextState) {
                return nextProps.item.id !== this.props.item.id;
            },
            render: function () {
                return React.createElement('li', null, this.props.item.name);
            }
        });
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement(Item, {item: item});
                }));
            }
        });
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', '', null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Randomly remove elements from 100 length list, one at a time - keys', function (bench) {

    function random(max) {
        return Math.floor(Math.random() * (max + 1));
    }

    bench('Magery', function (container, iter) {
        createTemplateNode('app',
                '
' +
                    '
' +
                        '{{item.name}}' +
                    '
' +
                '
'
        );
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({id: i, name: 'item' + i});
        }
        var app = Magery.bind(container, 'app', data, {});
        iter(100, function (i) {
            app.context.items.splice(random(app.context.items.length - 1), 1);
            app.update();
        });
    });

    bench('React', function (container, iter) {
        var Item = React.createClass({
            shouldComponentUpdate: function(nextProps, nextState) {
                return nextProps.item.id !== this.props.item.id;
            },
            render: function () {
                return React.createElement('li', null, this.props.item.name);
            }
        });
        var App = React.createClass({
            render: function () {
                var items = this.props.items;
                return React.createElement('ul', null, items.map(function (item) {
                    return React.createElement(Item, {key: item.id, item: item});
                }));
            }
        });
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({id: i, name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            ReactDOM.render(React.createElement(App, data), container);
        });
    });

    bench('IncrementalDOM', function (container, iter) {
        function render(data) {
            idom.elementOpen('ul', '', null);
            data.items.forEach(function (item) {
                idom.elementOpen('li', item.id, null);
                idom.text(item.name);
                idom.elementClose('li');
            });
            idom.elementClose('ul');
        }
        var data = {items: []};
        for (var i = 0; i < 100; i++) {
            data.items.push({id: i, name: 'item' + i});
        }
        iter(100, function (i) {
            data.items.splice(random(data.items.length), 1);
            idom.patch(container, function() {
                render(data);
            });
        });
    });

});

section('Live update a managed text box', function (bench) {

    function input(el, value){
        var ev = new InputEvent('input');
        el.value = value;
        el.dispatchEvent(ev);
    }

    var test_string = 'This is a test of how quickly input events update a textbox';

    bench('Magery', function (container, iter) {
        createTemplateNode(
            'app',
            '<input type="text" id="testInput" value="{{name}}" oninput="updateInput(event)" />'
        );
        var data = {name: ''};
        var app = Magery.bind(container, 'app', data, {
            updateInput: function (ev) {
                this.context.name = ev.target.value;
            }
        });
        var el = document.getElementById('testInput');
        iter(test_string.length, function (i) {
            input(el, test_string.substring(0, i + 1));
        });
    });

    bench('React', function (container, iter) {
        var data = {name: ''};
        var App = React.createClass({
            render: function () {
                return React.createElement('input', {
                    type: 'text',
                    id: 'testInput',
                    value: this.props.name,
                    onInput: this.props.updateInput
                });
            }
        });
        var updateInput = function (ev) {
            data.name = ev.target.value;
            ReactDOM.render(React.createElement(App, {name: data.name, updateInput: updateInput}), container);
        };
        var el = document.getElementById('testInput');
        iter(100, function (i) {
            input(el, test_string.substring(0, i + 1));
        });
    });

});
<|endoftext|>


<commit_before>export default function (babel) {

  const t = babel.types;
  var visitor, _class;

  visitor = {
    // CLASS
    ClassDeclaration: {
      enter(path) {
        _class = {id: path.node.id, parentId: path.node.superClass, statics: [], methods: []};
      },
      exit(path) {
        path.replaceWithMultiple(es5Class(_class));
      }
    },
    // SUPER CALL
    Super: superCall,
    // NEW.TARGET
    MetaProperty(path) {
      var node = path.node;
      if (node.meta.name === "new" && node.property.name === "target") {
        path.replaceWith(expression('this.constructor'));
      }
    },
    // METHODS
    ClassMethod(path) {
      var node = path.node;
      if (node.kind === 'constructor') {
        // CONSTRUCTOR
        _class.constructor = t.functionDeclaration(_class.id,  node.params, node.body);
        return;
      }
      if (node.static) {
        // STATIC METHODS
        _class.statics.push(es5Method(node));
        return;
      }
      // PROTOTYPE METHODS
      _class.methods.push(es5Method(node));
    }
  };

  // Utils

  function isString(value) {
      return typeof value === 'string';
  }
  function isMember(value) {
      return value.type = 'MemberExpression';
  }

  function toIdentifier(key) {
    return t.identifier(key)
  }

  function toMember(target, property) {
    return t.memberExpression(target, property);
  }

  function expression() {
    var index = arguments.length - 1, members = [], member;
    do {
      member = arguments[index];
      members = isString(member) ?
        members.concat(member.split('.').reverse().map(toIdentifier)) :
        members.concat([member]);
      index--;
    } while (index > -1);
    return members.reduceRight(toMember);
  }

  function objectAssign(target, members) {
    return t.expressionStatement(t.callExpression(
      // Object.assign(target, members)
      expression("Object.assign"), [target, t.objectExpression(members)]
    ));
  }

  function objectCreate(parentClass) {
    return t.callExpression(
      // Object.create(parentClass)
      expression("Object.create"), [parentClass]
    );
  }

  function assign(key, value) {
    // key = value
    return t.expressionStatement(t.assignmentExpression('=', key, value));
  }

  function es5Method(method) {
    var id = method.key;
    // foo: function foo(args) {/* code */}
    return t.objectProperty(id, t.functionExpression(id, method.params, method.body));
  }

  function superCall(path) {
    var
        targetPath = path.parentPath,
        ParentClass = _class.parentId,
        caller, method;
    if (path.parent.type ==="MemberExpression") {
      method = targetPath.node.property;
      targetPath = targetPath.parentPath;
      // caller => ParentClass.prototype.methodName.call
      caller = expression(ParentClass, 'prototype', method, 'call');
    } else {
      // caller => ParentClass.call
      caller = expression(ParentClass, 'call');
    }
    targetPath.replaceWith(t.callExpression(
      // {super target}.apply(this, args)
      caller, [t.Identifier('this')].concat(targetPath.node.arguments)
    ));
  }

  function es5Class(_class) {
    var _es5Class = [_class.constructor], MyClass = _class.id;
    // parent class
    if (_class.parentId) {
      // MyClass.prototype = Object.create(MyParentClass);
      _es5Class.push( assign( expression(MyClass, 'prototype'), objectCreate(_class.parentId) ));
    }
    // methods
    if (_class.methods.length > 0) {
      // Object.assign(MyClass.prototype, { /* my methods *//});
      _es5Class.push( objectAssign(expression(MyClass, 'prototype'), _class.methods) );
    }
    // statics
    if (_class.statics.length > 0) {
      // Object.assign(MyClass, { /* my statics *//});
      _es5Class.push( objectAssign(MyClass, _class.statics) );
    }
    return _es5Class;
  }

  return {
    name: "transform-class",
    visitor: visitor
  };
}
<commit_msg>fix the missing prototype and constructor<commit_after>export default function (babel) {

  const t = babel.types;
  var visitor, _class;

  visitor = {
    // CLASS
    ClassDeclaration: {
      enter(path) {
        _class = {id: path.node.id, parentId: path.node.superClass, statics: [], methods: []};
      },
      exit(path) {
        path.replaceWithMultiple(es5Class(_class));
      }
    },
    // SUPER CALL
    Super: superCall,
    // NEW.TARGET
    MetaProperty(path) {
      var node = path.node;
      if (node.meta.name === "new" && node.property.name === "target") {
        path.replaceWith(expression('this.constructor'));
      }
    },
    // METHODS
    ClassMethod(path) {
      var node = path.node;
      if (node.kind === 'constructor') {
        // CONSTRUCTOR
        _class.constructor = t.functionDeclaration(_class.id,  node.params, node.body);
        return;
      }
      if (node.static) {
        // STATIC METHODS
        _class.statics.push(es5Method(node));
        return;
      }
      // PROTOTYPE METHODS
      _class.methods.push(es5Method(node));
    }
  };

  // Utils

  function isString(value) {
      return typeof value === 'string';
  }
  function isMember(value) {
      return value.type = 'MemberExpression';
  }

  function toIdentifier(key) {
    return t.identifier(key)
  }

  function toMember(target, property) {
    return t.memberExpression(target, property);
  }

  function expression() {
    var index = arguments.length - 1, members = [], member;
    do {
      member = arguments[index];
      members = isString(member) ?
        members.concat(member.split('.').reverse().map(toIdentifier)) :
        members.concat([member]);
      index--;
    } while (index > -1);
    return members.reduceRight(toMember);
  }

  function objectAssign(target, members) {
    return t.expressionStatement(t.callExpression(
      // Object.assign(target, members)
      expression("Object.assign"), [target, t.objectExpression(members)]
    ));
  }

  function objectCreate(parentClass) {
    return t.callExpression(
      // Object.create(parentClass)
      expression("Object.create"), [parentClass]
    );
  }

  function assign(key, value) {
    // key = value
    return t.expressionStatement(t.assignmentExpression('=', key, value));
  }

  function es5Method(method) {
    var id = method.key;
    // foo: function foo(args) {/* code */}
    return t.objectProperty(id, t.functionExpression(id, method.params, method.body));
  }

  function superCall(path) {
    var
        targetPath = path.parentPath,
        ParentClass = _class.parentId,
        caller, method;
    if (path.parent.type ==="MemberExpression") {
      method = targetPath.node.property;
      targetPath = targetPath.parentPath;
      // caller => ParentClass.prototype.methodName.call
      caller = expression(ParentClass, 'prototype', method, 'call');
    } else {
      // caller => ParentClass.call
      caller = expression(ParentClass, 'call');
    }
    targetPath.replaceWith(t.callExpression(
      // {super target}.apply(this, args)
      caller, [t.Identifier('this')].concat(targetPath.node.arguments)
    ));
  }

  function es5Class(_class) {
    var _es5Class = [_class.constructor], MyClass = _class.id;
    // parent class
    if (_class.parentId) {
      // MyClass.prototype = Object.create(MyParentClass.prototype);
      _es5Class.push( assign(
        expression(MyClass, 'prototype'),
        objectCreate(expression(_class.parentId, 'prototype'))
      ));
      // force the prototype.constructor property to make new.target / this.constructor valid
      _class.methods.push(t.objectProperty(t.identifier('constructor'), MyClass));
    }
    // methods
    if (_class.methods.length > 0) {
      // Object.assign(MyClass.prototype, { /* my methods *//});
      _es5Class.push( objectAssign(expression(MyClass, 'prototype'), _class.methods) );
    }
    // statics
    if (_class.statics.length > 0) {
      // Object.assign(MyClass, { /* my statics *//});
      _es5Class.push( objectAssign(MyClass, _class.statics) );
    }
    return _es5Class;
  }

  return {
    name: "transform-class",
    visitor: visitor
  };
}
<|endoftext|>


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

var basicAuth = require('basic-auth');
var nodeStatic = require('node-static');

var internals = {
  node_env: process.env.NODE_ENVIRONMENT || 'development',
  host: process.env.MOZ_GAMES_HOST || process.env.HOST || '0.0.0.0',
  port: process.env.MOZ_GAMES_PORT || process.env.PORT || 3000,
  fileServer: new nodeStatic.Server('./public', {gzip: true}),
  cacheExpiryDates: {
    fonts: 31536000  // 1 year
  }
};

var server = http.createServer(function (req, res) {
  var credentials = basicAuth(req);
  var authChunks = (process.env.AUTH_GDC || ':').split(':');
  var authValid = (credentials &&
                   credentials.name === authChunks[0] &&
                   credentials.pass === authChunks[1]);

  // Protect only the `/gdc/` directory.
  function ipInRange(ip) {
    var blocks = (ip || '').split('.').map(function (num) {
      return parseInt(num, 10);
    });
    return (blocks[0] === 63 &&
            blocks[1] === 245 &&
            blocks[2] >= 208 && blocks[2] <= 223 &&
            blocks[3] >=0 && blocks[3] <= 255);
  }

  if (req.url === '/ip') {
    res.writeHead(200, {'content-type': 'application/json'});
    return res.end(JSON.stringify({
      'req.connection.remoteAddress': req.connection.remoteAddress,
      'req.connection.socket.remoteAddress': req.connection.socket && req.connection.socket.remoteAddress,
      'req.socket.remoteAddress': req.socket && req.socket.remoteAddress,
      'x-forwarded-for': req.headers['x-forwarded-for']
    }));
  }

  if (!ipInRange(req.headers['x-forwarded-for']) &&
      process.env.AUTH_GDC && req.url.indexOf('/gdc/') === 0 && !authValid) {

    return internals.fileServer.serveFile('/401.html', 401,
      {'WWW-Authenticate': 'Basic realm="mozgames"'}, req, res);
  }

  var urlBase = req.url.split('?')[0] || '';
  var urlExtension = urlBase.substr(urlBase.lastIndexOf('.'));
  if (['.woff', '.ttf', '.eot'].indexOf(urlExtension) !== -1) {
    var now = new Date();
    now.setSeconds(now.getSeconds() + internals.cacheExpiryDates.fonts);
    res.setHeader('Expires', now.toUTCString());
  }

  req.addListener('end', function () {
    internals.fileServer.serve(req, res, function (err) {
      if (!err) {
        console.log('[%s] [200] %s', req.method, req.url);
        return;
      }

      console.warn('[%s] [%s] %s', req.method, err.status, req.url);

      if (err.status === 404) {
        internals.fileServer.serveFile('/404.html', 404, {}, req, res);
      }
    });
  }).resume();
});

server.listen(internals.port, internals.host, function () {
  console.log('[%s] Server listening on http://%s:%s',
    internals.node_env, internals.host, internals.port);
});

module.exports = server;
<commit_msg>keep gzip+cache disabled for local development<commit_after>var http = require('http');

var basicAuth = require('basic-auth');
var nodeStatic = require('node-static');

var internals = {
  node_env: process.env.NODE_ENVIRONMENT || 'development',
  host: process.env.MOZ_GAMES_HOST || process.env.HOST || '0.0.0.0',
  port: process.env.MOZ_GAMES_PORT || process.env.PORT || 3000,
  nodeStaticOptions: {gzip: false, cache: false},
  cacheExpiryDates: {
    fonts: 31536000  // 1 year
  }
};

if (internals.node_env === 'production') {
  internals.nodeStaticOptions = {gzip: true, cache: true};
}

internals.fileServer = new nodeStatic.Server('./public', internals.nodeStaticOptions);

var server = http.createServer(function (req, res) {
  var credentials = basicAuth(req);
  var authChunks = (process.env.AUTH_GDC || ':').split(':');
  var authValid = (credentials &&
                   credentials.name === authChunks[0] &&
                   credentials.pass === authChunks[1]);

  // Protect only the `/gdc/` directory.
  function ipInRange(ip) {
    var blocks = (ip || '').split('.').map(function (num) {
      return parseInt(num, 10);
    });
    return (blocks[0] === 63 &&
            blocks[1] === 245 &&
            blocks[2] >= 208 && blocks[2] <= 223 &&
            blocks[3] >=0 && blocks[3] <= 255);
  }

  if (req.url === '/ip') {
    res.writeHead(200, {'content-type': 'application/json'});
    return res.end(JSON.stringify({
      'req.connection.remoteAddress': req.connection.remoteAddress,
      'req.connection.socket.remoteAddress': req.connection.socket && req.connection.socket.remoteAddress,
      'req.socket.remoteAddress': req.socket && req.socket.remoteAddress,
      'x-forwarded-for': req.headers['x-forwarded-for']
    }));
  }

  if (!ipInRange(req.headers['x-forwarded-for']) &&
      process.env.AUTH_GDC && req.url.indexOf('/gdc/') === 0 && !authValid) {

    return internals.fileServer.serveFile('/401.html', 401,
      {'WWW-Authenticate': 'Basic realm="mozgames"'}, req, res);
  }

  var urlBase = req.url.split('?')[0] || '';
  var urlExtension = urlBase.substr(urlBase.lastIndexOf('.'));
  if (['.woff', '.ttf', '.eot'].indexOf(urlExtension) !== -1) {
    var now = new Date();
    now.setSeconds(now.getSeconds() + internals.cacheExpiryDates.fonts);
    res.setHeader('Expires', now.toUTCString());
  }

  req.addListener('end', function () {
    internals.fileServer.serve(req, res, function (err) {
      if (!err) {
        console.log('[%s] [200] %s', req.method, req.url);
        return;
      }

      console.warn('[%s] [%s] %s', req.method, err.status, req.url);

      if (err.status === 404) {
        internals.fileServer.serveFile('/404.html', 404, {}, req, res);
      }
    });
  }).resume();
});

server.listen(internals.port, internals.host, function () {
  console.log('[%s] Server listening on http://%s:%s',
    internals.node_env, internals.host, internals.port);
});

module.exports = server;
<|endoftext|>


<commit_before>'use strict';
var execFile = require('child_process').execFile;
var fs = require('fs');
var appPath = require('app-path');

function getVersion(path, cb) {
	var cmd = 'mdls';
	var args = [
		'-name',
		'kMDItemVersion',
		'-raw',
		path
	];

	execFile(cmd, args, function (err, stdout) {
		if (err) {
			cb(err);
			return;
		}

		cb(null, stdout);
	});
}

module.exports = function (app, cb) {
	if (process.platform !== 'darwin') {
		throw new Error('Only OS X are supported');
	}

	if (typeof app !== 'string') {
		throw new Error('Application is required');
	}

	fs.stat(app, function (err, stats) {
		if (err && err.code === 'ENOENT') {
			appPath(app, function (err, path) {
				if (err) {
					cb(err);
					return;
				}

				getVersion(path, cb);
			});
			return;
		}

		if (err) {
			cb(err);
			return;
		}

		if (!stats.isDirectory()) {
			throw new Error('Expected an application');
		}

		getVersion(app, cb);
	});
};
<commit_msg>Small tweak<commit_after>'use strict';
var execFile = require('child_process').execFile;
var fs = require('fs');
var appPath = require('app-path');

function getVersion(path, cb) {
	var cmd = 'mdls';
	var args = [
		'-name',
		'kMDItemVersion',
		'-raw',
		path
	];

	execFile(cmd, args, function (err, stdout) {
		if (err) {
			cb(err);
			return;
		}

		cb(null, stdout);
	});
}

module.exports = function (app, cb) {
	if (process.platform !== 'darwin') {
		throw new Error('Only OS X systems are supported');
	}

	if (typeof app !== 'string') {
		throw new Error('Application is required');
	}

	fs.stat(app, function (err, stats) {
		if (err && err.code === 'ENOENT') {
			appPath(app, function (err, path) {
				if (err) {
					cb(err);
					return;
				}

				getVersion(path, cb);
			});
			return;
		}

		if (err) {
			cb(err);
			return;
		}

		if (!stats.isDirectory()) {
			throw new Error('Expected an application');
		}

		getVersion(app, cb);
	});
};
<|endoftext|>


<commit_before>/*!
    GPII pilotsConfig

    Copyright 2014 Technische Universitt Dresden (TUD)
    Copyright 2014 Raising the Floor - International (RtF)

    Licensed under the New BSD license. You may not use this file except in
    compliance with this License.

    You may obtain a copy of the License at
    https://github.com/GPII/universal/blob/master/LICENSE.txt

    Acknowledgements:
    The research leading to these results has received funding from
    the European Union's Seventh Framework Programme (FP7/2007-2013)
    under grant agreement no. 289016.
*/

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandler");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/setDeviceinfo"] = requestHandlers.setDeviceinfo;
handle["/selectMM"] = requestHandlers.selectMM;
handle["/snapshotToPrefs"] = requestHandlers.snapshotToPrefs;
handle["/getFeedback"] = requestHandlers.getFeedback;
handle["/logging"] = requestHandlers.logging;
// outdated logging
// handle["/snapshotToLog"] = requestHandlers.snapshotToLog;

// injecting the route function of router module into server module:
server.start(router.route, handle);

<commit_msg>GPII-842: adding a more detailed device reporter<commit_after>/*!
    GPII pilotsConfig

    Copyright 2014 Technische Universität Dresden (TUD)
    Copyright 2014 Raising the Floor - International (RtF)

    Licensed under the New BSD license. You may not use this file except in
    compliance with this License.

    You may obtain a copy of the License at
    https://github.com/GPII/universal/blob/master/LICENSE.txt

    Acknowledgements:
    The research leading to these results has received funding from
    the European Union's Seventh Framework Programme (FP7/2007-2013)
    under grant agreement no. 289016.
*/

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandler");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/setDeviceinfo"] = requestHandlers.setDeviceinfo;
handle["/setDetailedDeviceinfo"] = requestHandlers.setDetailedDeviceinfo;
handle["/selectMM"] = requestHandlers.selectMM;
handle["/snapshotToPrefs"] = requestHandlers.snapshotToPrefs;
handle["/getFeedback"] = requestHandlers.getFeedback;
handle["/logging"] = requestHandlers.logging;
// outdated logging
// handle["/snapshotToLog"] = requestHandlers.snapshotToLog;

// injecting the route function of router module into server module:
server.start(router.route, handle);
<|endoftext|>


<commit_before>/**
 * MIT License
 *
 * Copyright (c) 2017 ITGorillaz
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

const Wave = {

    /**
     * Http Exceptions
     */
    HttpException                          : require('./lib/exception/http-exception'),
    BadGatewayException                    : require('./lib/exception/bad-gateway-exception'),
    BadRequestException                    : require('./lib/exception/bad-request-exception'),
    ConflictException                      : require('./lib/exception/conflict-exception'),
    ExpectationFailedException             : require('./lib/exception/expectation-failed-exception'),
    FailedDependencyException              : require('./lib/exception/failed-dependency-exception'),
    ForbiddenException                     : require('./lib/exception/forbidden-exception'),
    GatewayTimeoutException                : require('./lib/exception/gateway-timeout-exception'),
    GoneException                          : require('./lib/exception/gone-exception'),
    HTTPVersionNotSupportedException       : require('./lib/exception/http-version-not-supported-exception'),
    ImaTeapotException                     : require('./lib/exception/im-a-teapot-exception'),
    InsufficientStorageException           : require('./lib/exception/insufficient-storage-exception'),
    InternalServerErrorException           : require('./lib/exception/internal-server-error-exception'),
    LengthRequiredException                : require('./lib/exception/length-required-exception'),
    LockedException                        : require('./lib/exception/locked-exception'),
    LoopDetectedException                  : require('./lib/exception/loop-detected-exception'),
    MethodNotAllowedException              : require('./lib/exception/method-not-allowed-exception'),
    MisdirectedRequestException            : require('./lib/exception/misdirected-request-exception'),
    NetworkAuthenticationRequiredException : require('./lib/exception/network-authentication-required-exception'),
    NotAcceptableException                 : require('./lib/exception/not-acceptable-exception'),
    NotExtendedException                   : require('./lib/exception/not-extended-exception'),
    NotImplementedException                : require('./lib/exception/not-implemented-exception'),
    PayloadTooLargeException               : require('./lib/exception/payload-too-large-exception'),
    PaymentRequiredException               : require('./lib/exception/payment-required-exception'),
    PreconditionFailedException            : require('./lib/exception/precondition-failed-exception'),
    PreconditionRequiredException          : require('./lib/exception/precondition-required-exception'),
    ProxyAuthenticationRequiredException   : require('./lib/exception/proxy-authentication-required-exception'),
    RequestHeaderFieldsTooLargeException   : require('./lib/exception/request-header-fields-too-large-exception'),
    RequestTimeoutException                : require('./lib/exception/request-timeout-exception'),
    RequestedRangeNotSatisfiableException  : require('./lib/exception/requested-range-not-satisfiable-exception'),
    ResourceNotFoundException              : require('./lib/exception/resource-not-found-exception'),
    ServiceUnavailableException            : require('./lib/exception/service-unavailable-exception'),
    TooManyRequestsException               : require('./lib/exception/too-many-requests-exception'),
    UnauthorizedException                  : require('./lib/exception/unauthorized-exception'),
    UnavailableForLegalReasonsException    : require('./lib/exception/unavailable-for-legal-reasons-exception'),
    UnprocessableEntityException           : require('./lib/exception/unprocessable-entity-exception'),
    UnsupportedMediaTypeException          : require('./lib/exception/unsupported-media-type-exception'),
    UpgradeRequiredException               : require('./lib/exception/upgrade-required-exception'),
    URITooLongException                    : require('./lib/exception/uri-too-long-exception'),
    VariantAlsoNegotiatesException         : require('./lib/exception/variant-also-negotiates-exception'),

    /**
     * Deserializers
     */
    DeserializerStrategy               : require('./lib/deserializer/deserializer-strategy'),
    RequestBodyDeserializerStrategy    : require('./lib/deserializer/request-body-deserializer-strategy'),
    JsonRequestBodyDeserializerStrategy: require('./lib/json/json-request-body-deserializer-strategy'),

    /**
     * Serializers
     */
    SerializerStrategy                : require('./lib/serializer/serializer-strategy'),
    ResponseBodySerializerStrategy    : require('./lib/serializer/response-body-serializer-strategy'),
    JsonResponseBodySerializerStrategy: require('./lib/json/json-response-body-serializer-strategy'),

    /**
     * Validator
     */
    RequestBodyValidator: require('./lib/validator/request-body-validator'),

    /**
     * Handler
     */
    AbstractRequestHandler: require('./lib/handler/abstract-request-handler')
}

module.exports = Wave;
<commit_msg>Updated index exports<commit_after>/**
 * MIT License
 *
 * Copyright (c) 2017 ITGorillaz
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

const Wave = {

    /**
     * Http Exceptions
     */
    HttpException                          : require('./lib/exception/http-exception'),
    BadGatewayException                    : require('./lib/exception/bad-gateway-exception'),
    BadRequestException                    : require('./lib/exception/bad-request-exception'),
    ConflictException                      : require('./lib/exception/conflict-exception'),
    ExpectationFailedException             : require('./lib/exception/expectation-failed-exception'),
    FailedDependencyException              : require('./lib/exception/failed-dependency-exception'),
    ForbiddenException                     : require('./lib/exception/forbidden-exception'),
    GatewayTimeoutException                : require('./lib/exception/gateway-timeout-exception'),
    GoneException                          : require('./lib/exception/gone-exception'),
    HTTPVersionNotSupportedException       : require('./lib/exception/http-version-not-supported-exception'),
    ImaTeapotException                     : require('./lib/exception/im-a-teapot-exception'),
    InsufficientStorageException           : require('./lib/exception/insufficient-storage-exception'),
    InternalServerErrorException           : require('./lib/exception/internal-server-error-exception'),
    LengthRequiredException                : require('./lib/exception/length-required-exception'),
    LockedException                        : require('./lib/exception/locked-exception'),
    LoopDetectedException                  : require('./lib/exception/loop-detected-exception'),
    MethodNotAllowedException              : require('./lib/exception/method-not-allowed-exception'),
    MisdirectedRequestException            : require('./lib/exception/misdirected-request-exception'),
    NetworkAuthenticationRequiredException : require('./lib/exception/network-authentication-required-exception'),
    NotAcceptableException                 : require('./lib/exception/not-acceptable-exception'),
    NotExtendedException                   : require('./lib/exception/not-extended-exception'),
    NotImplementedException                : require('./lib/exception/not-implemented-exception'),
    PayloadTooLargeException               : require('./lib/exception/payload-too-large-exception'),
    PaymentRequiredException               : require('./lib/exception/payment-required-exception'),
    PreconditionFailedException            : require('./lib/exception/precondition-failed-exception'),
    PreconditionRequiredException          : require('./lib/exception/precondition-required-exception'),
    ProxyAuthenticationRequiredException   : require('./lib/exception/proxy-authentication-required-exception'),
    RequestHeaderFieldsTooLargeException   : require('./lib/exception/request-header-fields-too-large-exception'),
    RequestTimeoutException                : require('./lib/exception/request-timeout-exception'),
    RequestedRangeNotSatisfiableException  : require('./lib/exception/requested-range-not-satisfiable-exception'),
    ResourceNotFoundException              : require('./lib/exception/resource-not-found-exception'),
    ServiceUnavailableException            : require('./lib/exception/service-unavailable-exception'),
    TooManyRequestsException               : require('./lib/exception/too-many-requests-exception'),
    UnauthorizedException                  : require('./lib/exception/unauthorized-exception'),
    UnavailableForLegalReasonsException    : require('./lib/exception/unavailable-for-legal-reasons-exception'),
    UnprocessableEntityException           : require('./lib/exception/unprocessable-entity-exception'),
    UnsupportedMediaTypeException          : require('./lib/exception/unsupported-media-type-exception'),
    UpgradeRequiredException               : require('./lib/exception/upgrade-required-exception'),
    URITooLongException                    : require('./lib/exception/uri-too-long-exception'),
    VariantAlsoNegotiatesException         : require('./lib/exception/variant-also-negotiates-exception'),

    /**
     * Deserializers
     */
    DeserializerStrategy               : require('./lib/deserializer/deserializer-strategy'),
    RequestBodyDeserializerStrategy    : require('./lib/deserializer/request-body-deserializer-strategy'),
    JsonRequestBodyDeserializerStrategy: require('./lib/json/json-request-body-deserializer-strategy'),

    /**
     * Serializers
     */
    SerializerStrategy                : require('./lib/serializer/serializer-strategy'),
    ResponseBodySerializerStrategy    : require('./lib/serializer/response-body-serializer-strategy'),
    JsonResponseBodySerializerStrategy: require('./lib/json/json-response-body-serializer-strategy'),

    /**
     * Validator
     */
    RequestBodyValidator: require('./lib/validator/request-body-validator'),

    /**
     * Handlers
     */
    AbstractRequestHandler      : require('./lib/handler/abstract-request-handler'),
    AbstractAPIGatewayAuthorizer: require('./lib/auth/abstract-api-gateway-authorizer'),

    /**
     * Utils
     */
    AuthPolicyBuilder: require('./lib/auth/auth-policy-builder'),
    PolicyEffect     : require('./lib/auth/policy-effect'),
    Arn              : require('./lib/utils/arn')
}

module.exports = Wave;
<|endoftext|>


<commit_before>
var _ = require('lodash');
var request = require('superagent');
var d3Color = require('d3-color');
var d3Scale = require('d3-color');

var colorbrewer = require('colorbrewer')
var Color = require('color');
var r;

var utils = {

    preloadImages: function(urls) {
        _.each(urls, function(url) {
            utils.preloadImage(url);
        });
    },

    preloadImage: function(url) {
        var img=new Image();
        img.src=url;
    },

    randomColor: function() {
        return '#'+Math.floor(Math.random()*16777215).toString(16);
    },

    linspace: function(a, b, n) {
      var every = (b-a)/(n-1)
      var ranged = _.range(a, b, every);
      return ranged.length == n ? ranged : ranged.concat(b);
    },

    getThumbnail: function(image) {
        return image + '_small';
    },

    cleanImageURL: function(url) {
        if(url.indexOf('http') > -1) {
            return url;
        }

        return (window.lightning && window.lightning.host) ? window.lightning.host + url : url;
    },

    mapRange: function(value, istart, istop, ostart, ostop) {
        return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
    },

    getColors: function(n) {
        var colors = ['#A38EF3', '#7ABFEA', '#5BC69F', '#E96B88', '#F0E86B', '#C2B08C', '#F9B070', '#F19A9A', '#AADA90', '#DBB1F2'];

        var retColors = [];
        for(var i = 0; i<n; i++) {
            retColors.push(colors[ i % colors.length]);
        }

        return retColors;
    },

    getColorFromData: function(data) {

        // retrieve an array of colors from 'label' or 'color' fields of object data
        // returns an list of lists in the form [[r,g,b],[r,g,b]...]

        if(data.hasOwnProperty('label')) {

            // get bounds and number of labels
            label = data.label
            var mn = Math.min.apply(null, label);
            var mx = Math.max.apply(null, label);
            var n = mx - mn + 1
            var colors = this.getColors(n)

            // get an array of d3 colors
            retColor = label.map(function(d) {return d3Color.rgb(colors[d - mn])});

        } else if (data.hasOwnProperty('color')) {

            // get an array of d3 colors directly from r,g,b values
            color = data.color
            retColor = color.map(function(d) {return d3Color.rgb(d[0], d[1], d[2])})

        } else if (data.hasOwnProperty('value')) {

            value = data.value

            // get d3 colors from a linear scale
            var colormap = data.colormap ? data.colormap : "Purples"

            var ncolor = 9
            if (colormap == "Lightning") {
                var color = ['#A38EF3', '#DBB1F2', '#7ABFEA', '#5BC69F', '#AADA90', '#F0E86B', '#F9B070', '#F19A9A', '#E96B88']
            } else {
                var color = colorbrewer[colormap][ncolor]
            }

            // get min and max of value data
            var vmin = Math.min.apply(null, value);
            var vmax = Math.max.apply(null, value);

            // set up scales
            var domain = this.linspace(vmin, vmax, ncolor)
            var scale = d3Scale.linear().domain(domain).range(color);

            retColor = value.map(function(d) {return d3Color.rgb(scale(d))})

        } else {

            // otherwise return empty
            retColor = []
        }

        return retColor
    },

    buildRGBA: function(base, opacity) {
        var color = Color(base);
        color.alpha(opacity);
        return color.rgbString();
    },

    trackTransforms: function(ctx){

        var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
        var xform = svg.createSVGMatrix();

        ctx.getTransform = function(){ return xform; };

        var savedTransforms = [];
        var save = ctx.save;
        ctx.save = function(){
            savedTransforms.push(xform.translate(0,0));
            return save.call(ctx);
        };
        var restore = ctx.restore;
        ctx.restore = function(){
            xform = savedTransforms.pop();
            return restore.call(ctx);
        };

        var scale = ctx.scale;
        ctx.scale = function(sx,sy){
            var oldXForm = xform;
            xform = xform.scaleNonUniform(sx,sy);
            if(xform.d < 1) {
                xform = oldXForm;
                return;
            }

            return scale.call(ctx,sx,sy);
        };

        var rotate = ctx.rotate;
        ctx.rotate = function(radians){
            xform = xform.rotate(radians*180/Math.PI);
            return rotate.call(ctx,radians);
        };

        var translate = ctx.translate;
        ctx.translate = function(dx,dy){
            xform = xform.translate(dx,dy);
            return translate.call(ctx,dx,dy);
        };

        var transform = ctx.transform;
        ctx.transform = function(a,b,c,d,e,f){
            var m2 = svg.createSVGMatrix();
            m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
            xform = xform.multiply(m2);
            return transform.call(ctx,a,b,c,d,e,f);
        };

        var setTransform = ctx.setTransform;
        ctx.setTransform = function(a,b,c,d,e,f){
            xform.a = a;
            xform.b = b;
            xform.c = c;
            xform.d = d;
            xform.e = e;
            xform.f = f;
            return setTransform.call(ctx,a,b,c,d,e,f);
        };
        var pt  = svg.createSVGPoint();
        ctx.transformedPoint = function(x,y) {
            pt.x=x; pt.y=y;
            return pt.matrixTransform(xform.inverse());
        };
    },

    addCanvasZoomPanListeners: function(canvas, context, redraw) {

        var lastX= canvas.width / 2;
        var lastY = canvas.height / 2;
        var dragStart, dragged;

        canvas.addEventListener('mousedown',function(evt){
            lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
            lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
            dragStart = context.transformedPoint(lastX,lastY);
            dragged = false;
        }, false);

        canvas.addEventListener('mousemove',function(evt){
            lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
            lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
            dragged = true;
            if (dragStart){
                var pt = context.transformedPoint(lastX,lastY);
                context.translate(pt.x-dragStart.x,pt.y-dragStart.y);
                redraw();
            }
        },false);
        canvas.addEventListener('mouseup',function(evt){
            dragStart = null;
            if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
        },false);

        var scaleFactor = 1.025;
        var zoom = function(clicks){
            var pt = context.transformedPoint(lastX,lastY);
            context.translate(pt.x, pt.y);
            var factor = Math.pow(scaleFactor,clicks);
            context.scale(factor,factor);
            context.translate(-pt.x, -pt.y);
            redraw();
        };

        var handleScroll = function(evt){
            var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
            if (delta) zoom(delta);
            return evt.preventDefault() && false;
        };
        canvas.addEventListener('DOMMouseScroll',handleScroll,false);
        canvas.addEventListener('mousewheel',handleScroll,false);

    },

    isEditorOrPreview: function() {
        var url = document.URL;
        return /https?:\/\/[^\/]+\/visualization-types\/*/.test(url);
    },

    getId: function(viz) {
        var $el = viz.$el;
        if(!viz.$el) {
            $el = $(viz.selection);
        }
        return $el.closest('[data-model=visualization]').data('model-id');
    },

    getUrl: function(viz) {

        var vid = this.getId(viz);
        var host = '/';

        if(window.lightning && window.lightning.host) {
            host = window.lightning.host;
        }

        return host + 'visualizations/' + vid;
    },

    fetchData: function(viz, keys, cb) {

        if(!viz.$el) {
            console.warn('Must set .$el property on your visualization');
        }

        if(this.isEditorOrPreview()) {

            setTimeout(function() {
                var data = $('#data-editor').next('.CodeMirror').find('.CodeMirror-code span')[0].innerHTML;
                var fetchedData = JSON.parse(data);

                _.each(keys, function(key) {
                    fetchedData = fetchedData[key];
                });

                cb(null, fetchedData);

            }, 0);

        } else {

            var url = this.getUrl(viz);

            if(r) {
                r.abort();
            }

            r = request.get(url + '/data/' + keys.join('/') + '/', function(err, res) {

                if(err) {
                    return cb(err)
                }

                cb(null, (res.body || {}).data);
            });
        }
    },

    getSettings: function(viz, cb) {

        if(this.isEditorOrPreview()) {
            setTimeout(function() {
                cb(null, {});
            }, 0);

            return;
        }

        var url = this.getUrl(viz);

        r = request.get(url + '/settings/', function(err, res) {

            if(err) {
                return cb(err)
            }

            cb(null, (res.body || {}).settings);
        });
    },

    getUniqueId: function() {
        var s4 = function() {
            return Math.floor((1 + Math.random()) * 0x10000)
                       .toString(16)
                       .substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
           s4() + '-' + s4() + s4() + s4();
    },

    updateSettings: function(viz, settings, cb) {

        if(this.isEditorOrPreview()) {
            setTimeout(function() {
                cb(null, settings);
            }, 0);

            return;
        }

        var url = this.getUrl(viz);

        r = request.post(url + '/settings/', settings, function(err, res) {

            if(err) {
                return cb(err)
            }

            cb(null, (res.body || {}).settings);
        });
    },

    getCommForViz: function(viz) {
        var m = (window.lightning || {}).comm_map;
        if(m) {
            return m[this.getId(viz)];
        }
    },

    sendCommMessage: function(viz, type, data) {
        var comm = this.getCommForViz(viz);
        if(comm) {
            comm.send(JSON.stringify({
                type: type,
                data: data
            }));
        }
    },

    nearestPoint: function(points, target, xscale, yscale) {
        // find point in points nearest to target
        // using scales x and y
        // point must have attrs x, y, and s
        var i = 0, count = 0;
        var found, dist, n, p;
        while (count == 0 & i < points.length) {
            p = points[i]
            dist = Math.sqrt(Math.pow(xscale(p.x) - target[0], 2) + Math.pow(yscale(p.y) - target[1], 2))
            if (dist <= p.s) {
                found = p
                count = 1
            }
            i++;
        }
        return found
    }

};

module.exports = utils;<commit_msg>Fix package name<commit_after>
var _ = require('lodash');
var request = require('superagent');
var d3Color = require('d3-color');
var d3Scale = require('d3-scale');

var colorbrewer = require('colorbrewer')
var Color = require('color');
var r;

var utils = {

    preloadImages: function(urls) {
        _.each(urls, function(url) {
            utils.preloadImage(url);
        });
    },

    preloadImage: function(url) {
        var img=new Image();
        img.src=url;
    },

    randomColor: function() {
        return '#'+Math.floor(Math.random()*16777215).toString(16);
    },

    linspace: function(a, b, n) {
      var every = (b-a)/(n-1)
      var ranged = _.range(a, b, every);
      return ranged.length == n ? ranged : ranged.concat(b);
    },

    getThumbnail: function(image) {
        return image + '_small';
    },

    cleanImageURL: function(url) {
        if(url.indexOf('http') > -1) {
            return url;
        }

        return (window.lightning && window.lightning.host) ? window.lightning.host + url : url;
    },

    mapRange: function(value, istart, istop, ostart, ostop) {
        return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
    },

    getColors: function(n) {
        var colors = ['#A38EF3', '#7ABFEA', '#5BC69F', '#E96B88', '#F0E86B', '#C2B08C', '#F9B070', '#F19A9A', '#AADA90', '#DBB1F2'];

        var retColors = [];
        for(var i = 0; i<n; i++) {
            retColors.push(colors[ i % colors.length]);
        }

        return retColors;
    },

    getColorFromData: function(data) {

        // retrieve an array of colors from 'label' or 'color' fields of object data
        // returns an list of lists in the form [[r,g,b],[r,g,b]...]

        if(data.hasOwnProperty('label')) {

            // get bounds and number of labels
            label = data.label
            var mn = Math.min.apply(null, label);
            var mx = Math.max.apply(null, label);
            var n = mx - mn + 1
            var colors = this.getColors(n)

            // get an array of d3 colors
            retColor = label.map(function(d) {return d3Color.rgb(colors[d - mn])});

        } else if (data.hasOwnProperty('color')) {

            // get an array of d3 colors directly from r,g,b values
            color = data.color
            retColor = color.map(function(d) {return d3Color.rgb(d[0], d[1], d[2])})

        } else if (data.hasOwnProperty('value')) {

            value = data.value

            // get d3 colors from a linear scale
            var colormap = data.colormap ? data.colormap : "Purples"

            var ncolor = 9
            if (colormap == "Lightning") {
                var color = ['#A38EF3', '#DBB1F2', '#7ABFEA', '#5BC69F', '#AADA90', '#F0E86B', '#F9B070', '#F19A9A', '#E96B88']
            } else {
                var color = colorbrewer[colormap][ncolor]
            }

            // get min and max of value data
            var vmin = Math.min.apply(null, value);
            var vmax = Math.max.apply(null, value);

            // set up scales
            var domain = this.linspace(vmin, vmax, ncolor)
            var scale = d3Scale.linear().domain(domain).range(color);

            retColor = value.map(function(d) {return d3Color.rgb(scale(d))})

        } else {

            // otherwise return empty
            retColor = []
        }

        return retColor
    },

    buildRGBA: function(base, opacity) {
        var color = Color(base);
        color.alpha(opacity);
        return color.rgbString();
    },

    trackTransforms: function(ctx){

        var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
        var xform = svg.createSVGMatrix();

        ctx.getTransform = function(){ return xform; };

        var savedTransforms = [];
        var save = ctx.save;
        ctx.save = function(){
            savedTransforms.push(xform.translate(0,0));
            return save.call(ctx);
        };
        var restore = ctx.restore;
        ctx.restore = function(){
            xform = savedTransforms.pop();
            return restore.call(ctx);
        };

        var scale = ctx.scale;
        ctx.scale = function(sx,sy){
            var oldXForm = xform;
            xform = xform.scaleNonUniform(sx,sy);
            if(xform.d < 1) {
                xform = oldXForm;
                return;
            }

            return scale.call(ctx,sx,sy);
        };

        var rotate = ctx.rotate;
        ctx.rotate = function(radians){
            xform = xform.rotate(radians*180/Math.PI);
            return rotate.call(ctx,radians);
        };

        var translate = ctx.translate;
        ctx.translate = function(dx,dy){
            xform = xform.translate(dx,dy);
            return translate.call(ctx,dx,dy);
        };

        var transform = ctx.transform;
        ctx.transform = function(a,b,c,d,e,f){
            var m2 = svg.createSVGMatrix();
            m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
            xform = xform.multiply(m2);
            return transform.call(ctx,a,b,c,d,e,f);
        };

        var setTransform = ctx.setTransform;
        ctx.setTransform = function(a,b,c,d,e,f){
            xform.a = a;
            xform.b = b;
            xform.c = c;
            xform.d = d;
            xform.e = e;
            xform.f = f;
            return setTransform.call(ctx,a,b,c,d,e,f);
        };
        var pt  = svg.createSVGPoint();
        ctx.transformedPoint = function(x,y) {
            pt.x=x; pt.y=y;
            return pt.matrixTransform(xform.inverse());
        };
    },

    addCanvasZoomPanListeners: function(canvas, context, redraw) {

        var lastX= canvas.width / 2;
        var lastY = canvas.height / 2;
        var dragStart, dragged;

        canvas.addEventListener('mousedown',function(evt){
            lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
            lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
            dragStart = context.transformedPoint(lastX,lastY);
            dragged = false;
        }, false);

        canvas.addEventListener('mousemove',function(evt){
            lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
            lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
            dragged = true;
            if (dragStart){
                var pt = context.transformedPoint(lastX,lastY);
                context.translate(pt.x-dragStart.x,pt.y-dragStart.y);
                redraw();
            }
        },false);
        canvas.addEventListener('mouseup',function(evt){
            dragStart = null;
            if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
        },false);

        var scaleFactor = 1.025;
        var zoom = function(clicks){
            var pt = context.transformedPoint(lastX,lastY);
            context.translate(pt.x, pt.y);
            var factor = Math.pow(scaleFactor,clicks);
            context.scale(factor,factor);
            context.translate(-pt.x, -pt.y);
            redraw();
        };

        var handleScroll = function(evt){
            var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
            if (delta) zoom(delta);
            return evt.preventDefault() && false;
        };
        canvas.addEventListener('DOMMouseScroll',handleScroll,false);
        canvas.addEventListener('mousewheel',handleScroll,false);

    },

    isEditorOrPreview: function() {
        var url = document.URL;
        return /https?:\/\/[^\/]+\/visualization-types\/*/.test(url);
    },

    getId: function(viz) {
        var $el = viz.$el;
        if(!viz.$el) {
            $el = $(viz.selection);
        }
        return $el.closest('[data-model=visualization]').data('model-id');
    },

    getUrl: function(viz) {

        var vid = this.getId(viz);
        var host = '/';

        if(window.lightning && window.lightning.host) {
            host = window.lightning.host;
        }

        return host + 'visualizations/' + vid;
    },

    fetchData: function(viz, keys, cb) {

        if(!viz.$el) {
            console.warn('Must set .$el property on your visualization');
        }

        if(this.isEditorOrPreview()) {

            setTimeout(function() {
                var data = $('#data-editor').next('.CodeMirror').find('.CodeMirror-code span')[0].innerHTML;
                var fetchedData = JSON.parse(data);

                _.each(keys, function(key) {
                    fetchedData = fetchedData[key];
                });

                cb(null, fetchedData);

            }, 0);

        } else {

            var url = this.getUrl(viz);

            if(r) {
                r.abort();
            }

            r = request.get(url + '/data/' + keys.join('/') + '/', function(err, res) {

                if(err) {
                    return cb(err)
                }

                cb(null, (res.body || {}).data);
            });
        }
    },

    getSettings: function(viz, cb) {

        if(this.isEditorOrPreview()) {
            setTimeout(function() {
                cb(null, {});
            }, 0);

            return;
        }

        var url = this.getUrl(viz);

        r = request.get(url + '/settings/', function(err, res) {

            if(err) {
                return cb(err)
            }

            cb(null, (res.body || {}).settings);
        });
    },

    getUniqueId: function() {
        var s4 = function() {
            return Math.floor((1 + Math.random()) * 0x10000)
                       .toString(16)
                       .substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
           s4() + '-' + s4() + s4() + s4();
    },

    updateSettings: function(viz, settings, cb) {

        if(this.isEditorOrPreview()) {
            setTimeout(function() {
                cb(null, settings);
            }, 0);

            return;
        }

        var url = this.getUrl(viz);

        r = request.post(url + '/settings/', settings, function(err, res) {

            if(err) {
                return cb(err)
            }

            cb(null, (res.body || {}).settings);
        });
    },

    getCommForViz: function(viz) {
        var m = (window.lightning || {}).comm_map;
        if(m) {
            return m[this.getId(viz)];
        }
    },

    sendCommMessage: function(viz, type, data) {
        var comm = this.getCommForViz(viz);
        if(comm) {
            comm.send(JSON.stringify({
                type: type,
                data: data
            }));
        }
    },

    nearestPoint: function(points, target, xscale, yscale) {
        // find point in points nearest to target
        // using scales x and y
        // point must have attrs x, y, and s
        var i = 0, count = 0;
        var found, dist, n, p;
        while (count == 0 & i < points.length) {
            p = points[i]
            dist = Math.sqrt(Math.pow(xscale(p.x) - target[0], 2) + Math.pow(yscale(p.y) - target[1], 2))
            if (dist <= p.s) {
                found = p
                count = 1
            }
            i++;
        }
        return found
    }

};

module.exports = utils;<|endoftext|>


<commit_before>// http://macfja.github.io/enyo2-lib/onyx/dynamiclist.html

/**
* This TermsAndConditionsPage kind,
*
* - setupPageBody() Impemented method
*/
enyo.ready(function() {
  enyo.kind({
    name: "Bootplate.TermsAndConditionsPage"
    , kind: "Bootplate.ParentPage"
    , id: 'termsAndConditionsPage'
    , authFlag: true // used to help determine if user has access to this page
    , published : {
      listRef:''
    }
    , handlers: {
       onGetTermsAndConditionsScreen: 'getTermsAndConditionsScreen'
      , onLoadTermsAndConditionsScreen: 'loadTermsAndConditionsScreen'
    }

    // This checks to see if the user is allowed on this page
    , rendered: function() {
        this.inherited(arguments);
    }
    , setupPageBody: function(owner) {
        this.createComponent({content:'Terms & Conditions', style: "margin-left: 10%;margin-bottom: 10px;padding-top: 30px;", owner:this});

        this.insertBreak(this);
        this.createComponent({kind: enyo.Checkbox, name: 'showArchivedCheckbox', onActivate: 'checkboxChanged', content:'Show Accepted T&Cs', style: "margin-left: 10%;margin-bottom: 10px;", owner:this});
        this.createComponent({name: "termsAndConditionsList"
            , kind: "macfja.DynamicList"
            , defaultRowHeight: 20
            , style: "width:80%; margin-left:10%; height: 150px; border: 1px solid grey"
            , onSetupRow: "setupRow"
            , classes:"form-input-box form-top-margin"
            , owner: this
          });
        owner.render();
        // populate the list
        this.getTermsAndConditionsScreen();
    } // end setupPageBody
    , checkboxChanged : function() {
        // reload the message list
        this.getTermsAndConditionsScreen();
    }
    , getTermsAndConditionsScreen: function() {
        // load the system message
        var jsonpGetSysMessages = new JSONP.GetTermsAndConditions({owner:this, fireEvent:'onLoadTermsAndConditionsScreen', errorEvent:'onErrorTermsAndConditions'});
        jsonpGetSysMessages.makeRequest({archiveFlag: this.$.showArchivedCheckbox.getChecked()});
    }
    // Dsiplay system messages
    , loadTermsAndConditionsScreen: function(inSender, inEvent) {
        this.$.termsAndConditionsList.setItems(inEvent);
        mvcApp.data.terms = inEvent.length;
        return true;
    }
    , setupRow: function(inSender, inEvent) {
        inEvent.template="
{$label}
";
        inEvent.template={components: [
          { kind: "FittableColumns", components: [
              {content: "Created: ", classes:'list-item-margin bold-text'}
            , {content: inEvent.context.createDate}
          ]}
          , { kind: "FittableColumns", components: [
              {content: "Subject: ", classes:'list-item-margin bold-text'}
              , {content: inEvent.context.subject}
              , {content: "Message: ", classes:'list-item-margin bold-text'}
              , {content: inEvent.context.message}
            ]}
            , {kind: "onyx.Button", content: "Archive", ontap: 'archiveMessage', id: 'archiveMessage_'+inEvent.context._id, owner: this, classes:'list-item-margin'}
        ]};
    }
    , archiveMessage: function(inSender, inEvent) {
        var objId = (inSender.id.substring(inSender.id.indexOf('archiveMessage_') + ("archiveMessage_").length)).trim();
        // archive the system message
        if (objId) {
          var ajaxArchiveSysMessage = new AJAX.ArchiveTermsAndConditions({owner:this, fireEvent:'onGetTermsAndConditionsScreen', errorEvent:'onErrorTermsAndConditions'});
          ajaxArchiveSysMessage.makeRequest({termsAndConditionsId: objId});
        }
    }

  });
});

<commit_msg>Accept terms & Conditions<commit_after>// http://macfja.github.io/enyo2-lib/onyx/dynamiclist.html

/**
* This TermsAndConditionsPage kind,
*
* - setupPageBody() Impemented method
*/
enyo.ready(function() {
  enyo.kind({
    name: "Bootplate.TermsAndConditionsPage"
    , kind: "Bootplate.ParentPage"
    , id: 'termsAndConditionsPage'
    , authFlag: true // used to help determine if user has access to this page
    , published : {
      listRef:''
    }
    , handlers: {
       onGetTermsAndConditionsScreen: 'getTermsAndConditionsScreen'
      , onLoadTermsAndConditionsScreen: 'loadTermsAndConditionsScreen'
    }

    // This checks to see if the user is allowed on this page
    , rendered: function() {
        this.inherited(arguments);
    }
    , setupPageBody: function(owner) {
        this.createComponent({content:'Terms & Conditions', style: "margin-left: 10%;margin-bottom: 10px;padding-top: 30px;", owner:this});

        this.insertBreak(this);
        this.createComponent({kind: enyo.Checkbox, name: 'showArchivedCheckbox', onActivate: 'checkboxChanged', content:'Show Accepted T&Cs', style: "margin-left: 10%;margin-bottom: 10px;", owner:this});
        this.createComponent({name: "termsAndConditionsList"
            , kind: "macfja.DynamicList"
            , defaultRowHeight: 20
            , style: "width:80%; margin-left:10%; height: 150px; border: 1px solid grey"
            , onSetupRow: "setupRow"
            , classes:"form-input-box form-top-margin"
            , owner: this
          });
        owner.render();
        // populate the list
        this.getTermsAndConditionsScreen();
    } // end setupPageBody
    , checkboxChanged : function() {
        // reload the message list
        this.getTermsAndConditionsScreen();
    }
    , getTermsAndConditionsScreen: function() {
        // load the system message
        var jsonpGetSysMessages = new JSONP.GetTermsAndConditions({owner:this, fireEvent:'onLoadTermsAndConditionsScreen', errorEvent:'onErrorTermsAndConditions'});
        jsonpGetSysMessages.makeRequest({archiveFlag: this.$.showArchivedCheckbox.getChecked()});
    }
    // Dsiplay system messages
    , loadTermsAndConditionsScreen: function(inSender, inEvent) {
        this.$.termsAndConditionsList.setItems(inEvent);
        mvcApp.data.terms = inEvent.length;
        return true;
    }
    , setupRow: function(inSender, inEvent) {
        inEvent.template="
{$label}
";
        inEvent.template={components: [
          { kind: "FittableColumns", components: [
              {content: "Created: ", classes:'list-item-margin bold-text'}
            , {content: inEvent.context.createDate}
          ]}
          , { kind: "FittableColumns", components: [
              {content: "Subject: ", classes:'list-item-margin bold-text'}
              , {content: inEvent.context.subject}
              , {content: "Message: ", classes:'list-item-margin bold-text'}
              , {content: inEvent.context.message}
              , {content: "Accepted on: ", classes:'list-item-margin bold-text'}
              , {content: inEvent.context.acceptedDate}
            ]}
          , {kind: "onyx.Button", content: "Accept", ontap: 'archiveMessage', accepted:inEvent.context.acceptedDate, id: 'archiveMessage_'+inEvent.context._id, owner: this, classes:'list-item-margin'}
        ]};
    }
    , archiveMessage: function(inSender, inEvent) {
        var objId = (inSender.id.substring(inSender.id.indexOf('archiveMessage_') + ("archiveMessage_").length)).trim();
      console.log(objId)
        // archive the system message
        if (objId) {
          if (!inSender.accepted) {
            console.log(1)
          var ajaxArchiveSysMessage = new AJAX.ArchiveTermsAndConditions({owner:this, fireEvent:'onGetTermsAndConditionsScreen', errorEvent:'onErrorTermsAndConditions'});
          ajaxArchiveSysMessage.makeRequest({termsAndConditionsId: objId});
          } else {
            console.log(2)
            this.getTermsAndConditionsScreen();
          }
        }
    }

  });
});

<|endoftext|>


<commit_before>/* eslint "key-spacing": ["error", {"align": "colon"}] */

import path from 'path';
import test from 'ava';

import hashed, {ERROR_MSG} from '../dist/lib/hashed';
import helpers             from './helpers/integration';

const NAME = 'hashed';

const CONFIG = {
  buildFolder : `./test/integration/${helpers.dist(NAME)}`,
  assetsFolder: 'assets',
  buildCssFile: 'css/style.css'
};
const WEBPACKCONFIG = {
  output: {
    path    : `./test/integration/${helpers.dist(NAME)}`,
    filename: 'bundle.js'
  }
};

test.before(async () => {
  await helpers.distFromTpl(NAME);
});

test('hashed', t => {
  t.is(typeof hashed, 'function', 'should be a function');
});

test('hashed(config, webpackconfig)', async t => {
  const result = await hashed(CONFIG, WEBPACKCONFIG);

  const bundleFile = path.join(WEBPACKCONFIG.output.path, WEBPACKCONFIG.output.filename);
  const styleFile  = path.join(CONFIG.buildFolder, CONFIG.assetsFolder, CONFIG.buildCssFile);

  const bundleFileBase = path.join(path.dirname(bundleFile), path.basename(bundleFile, '.js'));
  const styleFileBase  = path.join(path.dirname(styleFile), path.basename(styleFile, '.css'));

  t.truthy(result[bundleFile], 'map should have a key for bundle file');
  t.truthy(result[styleFile], 'map should have a key for styles file');
  t.true(result[bundleFile].indexOf(bundleFileBase) > -1, 'map should have a value for bundle file `hashed` version');
  t.true(result[styleFile].indexOf(styleFileBase) > -1, 'map should have a value for styles file `hashed` version');
});

test('hashed(undefined, webpackconfig)', async t => {
  const err = await t.throws(hashed(undefined, WEBPACKCONFIG));

  t.is(err.message, ERROR_MSG, 'should reject with an error');
});

test('hashed(config, undefined)', async t => {
  const err = await t.throws(hashed(CONFIG, undefined));

  t.is(err.message, ERROR_MSG, 'should reject with an error');
});

test.after.always(async () => {
  await helpers.clean(NAME);
});
<commit_msg>extra blank line<commit_after>/* eslint "key-spacing": ["error", {"align": "colon"}] */

import path from 'path';
import test from 'ava';

import hashed, {ERROR_MSG} from '../dist/lib/hashed';
import helpers             from './helpers/integration';

const NAME = 'hashed';

const CONFIG = {
  buildFolder : `./test/integration/${helpers.dist(NAME)}`,
  assetsFolder: 'assets',
  buildCssFile: 'css/style.css'
};

const WEBPACKCONFIG = {
  output: {
    path    : `./test/integration/${helpers.dist(NAME)}`,
    filename: 'bundle.js'
  }
};

test.before(async () => {
  await helpers.distFromTpl(NAME);
});

test('hashed', t => {
  t.is(typeof hashed, 'function', 'should be a function');
});

test('hashed(config, webpackconfig)', async t => {
  const result = await hashed(CONFIG, WEBPACKCONFIG);

  const bundleFile = path.join(WEBPACKCONFIG.output.path, WEBPACKCONFIG.output.filename);
  const styleFile  = path.join(CONFIG.buildFolder, CONFIG.assetsFolder, CONFIG.buildCssFile);

  const bundleFileBase = path.join(path.dirname(bundleFile), path.basename(bundleFile, '.js'));
  const styleFileBase  = path.join(path.dirname(styleFile), path.basename(styleFile, '.css'));

  t.truthy(result[bundleFile], 'map should have a key for bundle file');
  t.truthy(result[styleFile], 'map should have a key for styles file');
  t.true(result[bundleFile].indexOf(bundleFileBase) > -1, 'map should have a value for bundle file `hashed` version');
  t.true(result[styleFile].indexOf(styleFileBase) > -1, 'map should have a value for styles file `hashed` version');
});

test('hashed(undefined, webpackconfig)', async t => {
  const err = await t.throws(hashed(undefined, WEBPACKCONFIG));

  t.is(err.message, ERROR_MSG, 'should reject with an error');
});

test('hashed(config, undefined)', async t => {
  const err = await t.throws(hashed(CONFIG, undefined));

  t.is(err.message, ERROR_MSG, 'should reject with an error');
});

test.after.always(async () => {
  await helpers.clean(NAME);
});
<|endoftext|>


<commit_before>import React from 'react';
import { c, msgid } from 'ttag';
import { Block, Loader, SubTitle, useOrganization, useUser } from 'react-components';

import AddressesWithMembers from './AddressesWithMembers';
import AddressesWithUser from './AddressesWithUser';

const AddressesSection = () => {
    const [user] = useUser();
    const [organization, loadingOrganization] = useOrganization();

    const { MaxMembers, UsedAddresses, MaxAddresses } = organization || {};

    if (loadingOrganization) {
        return <Loader />;
    }

    return (
        <>
            <SubTitle>{c('Title').t`Addresses`}</SubTitle>
            {MaxMembers > 1 && user.isAdmin ? (
                <AddressesWithMembers user={user} organization={organization} />
            ) : (
                <AddressesWithUser user={user} />
            )}
            {MaxAddresses > 1 ? (
                <Block className="opacity-50">
                    {UsedAddresses} / {MaxAddresses}{' '}
                    {c('Info').ngettext(msgid`address used`, `addresses used`, UsedAddresses)}
                </Block>
            ) : null}
        </>
    );
};

export default AddressesSection;
<commit_msg>No need to have multiple member to add a new address (#397)<commit_after>import React from 'react';
import { c, msgid } from 'ttag';
import { Block, Loader, SubTitle, useOrganization, useUser } from 'react-components';

import AddressesWithMembers from './AddressesWithMembers';
import AddressesWithUser from './AddressesWithUser';

const AddressesSection = () => {
    const [user] = useUser();
    const [organization, loadingOrganization] = useOrganization();

    const { UsedAddresses, MaxAddresses } = organization || {};

    if (loadingOrganization) {
        return <Loader />;
    }

    return (
        <>
            <SubTitle>{c('Title').t`Addresses`}</SubTitle>
            {user.isAdmin ? (
                <AddressesWithMembers user={user} organization={organization} />
            ) : (
                <AddressesWithUser user={user} />
            )}
            {MaxAddresses > 1 ? (
                <Block className="opacity-50">
                    {UsedAddresses} / {MaxAddresses}{' '}
                    {c('Info').ngettext(msgid`address used`, `addresses used`, UsedAddresses)}
                </Block>
            ) : null}
        </>
    );
};

export default AddressesSection;
<|endoftext|>