<commit_before>var path = require('path'),
    webpack = require('webpack'),
    ExtractTextPlugin = require('extract-text-webpack-plugin'),
    uglifyJsPlugin = webpack.optimize.UglifyJsPlugin
    // HtmlWebpackPlugin = require('html-webpack-plugin')

var ROOT_PATH = __dirname,
    APP_PATH = path.resolve(ROOT_PATH, 'src'),
    BUILD_PATH = path.resolve(ROOT_PATH, 'dist')
var PROXY = 'http://localhost:3000/'

module.exports = {
  entry: {
    app:['webpack/hot/dev-server', path.resolve(APP_PATH, 'app.js')],
    login: path.resolve(APP_PATH, 'login.js'),
    manager: path.resolve(APP_PATH, 'manager.js'),
    vendor: ['jquery', 'vue']
  },
  output: {
    path: '/dist/',
    publicPath: '/dist/',
    filename: '[name].js',
    chunkFilename:'[id].chunk.js'
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      {test: /\.js$/, exclude:/node_modules|dist/, loader:'babel'},
      {test: /\.vue$/, loader:'vue'},
      {test: /\.css$/, loader: ExtractTextPlugin.extract("style", "css")},
      {test: /\.scss$/, loader: 'style!css!sass'},
      {test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192'},
      {
         test: /\.(woff2|woff|ttf|eot|svg|otf)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
         loaders: ["url-loader?limit=1000&name=fonts/[name]_[hash].[ext]"]
      }
    ]
  },
  babel: {
    presets: 'es2015',
    plugins: ['transform-runtime']
  },
  resolve : {
    extensions: ['', '.vue', '.js']
  },
  devServer: {
    historyApiFallback: true,
    hot: true,
    inline: true,
    progress: true,
    proxy: {
        "/*": {
            target: PROXY
        },
        "/": {
            target: PROXY
        }
    }
  },
  plugins: [
    new ExtractTextPlugin ('app.css'),
    new webpack.optimize.CommonsChunkPlugin('vendor',  'vendor.js'),
    // new uglifyJsPlugin({
    //     compress: {
    //         warnings: false
    //     }
    // }),
    new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery",
          "window.jQuery": "jquery",
          "root.jQuery": "jquery",
        }),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['index', 'login'],
        minChunks: 2,
    }),
    // new HtmlWebpackPlugin({
    //     title: 'hilshire\'s blog',
    //     filename: path.resolve(ROOT_PATH, 'app.html'),
    //     chunks: [path.resolve(ROOT_PATH, 'app.html'),]
    // }),
    // new HtmlWebpackPlugin({
    //     title: 'manager',
    //     filename: path.resolve(ROOT_PATH, 'manager.html')
    // }),
    // new HtmlWebpackPlugin({
    //     title: 'login',
    //     filename: path.resolve(ROOT_PATH, 'login.html'),
    //     chunks: [name]
    // })
  ],
}
<commit_msg>webpack-dev-server proxy bug<commit_after>var path = require('path'),
    webpack = require('webpack'),
    ExtractTextPlugin = require('extract-text-webpack-plugin'),
    uglifyJsPlugin = webpack.optimize.UglifyJsPlugin
    // HtmlWebpackPlugin = require('html-webpack-plugin')

var ROOT_PATH = __dirname,
    APP_PATH = path.resolve(ROOT_PATH, 'src'),
    BUILD_PATH = path.resolve(ROOT_PATH, 'dist')
var PROXY = 'http://localhost:3000/'

module.exports = {
  entry: {
    app:['webpack/hot/dev-server', path.resolve(APP_PATH, 'app.js')],
    login: path.resolve(APP_PATH, 'login.js'),
    manager: path.resolve(APP_PATH, 'manager.js'),
    vendor: ['jquery', 'vue']
  },
  output: {
    path: '/dist/',
    publicPath: '/dist/',
    filename: '[name].js',
    chunkFilename:'[id].chunk.js'
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      {test: /\.js$/, exclude:/node_modules|dist/, loader:'babel'},
      {test: /\.vue$/, loader:'vue'},
      {test: /\.css$/, loader: ExtractTextPlugin.extract("style", "css")},
      {test: /\.scss$/, loader: 'style!css!sass'},
      {test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192'},
      {
         test: /\.(woff2|woff|ttf|eot|svg|otf)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
         loaders: ["url-loader?limit=1000&name=fonts/[name]_[hash].[ext]"]
      }
    ]
  },
  babel: {
    presets: 'es2015',
    plugins: ['transform-runtime']
  },
  resolve : {
    extensions: ['', '.vue', '.js']
  },
  devServer: {
    historyApiFallback: true,
    hot: true,
    inline: true,
    progress: true,
    proxy: {
        "**": {
            target: PROXY
        }
    }
  },
  plugins: [
    new ExtractTextPlugin ('app.css'),
    new webpack.optimize.CommonsChunkPlugin('vendor',  'vendor.js'),
    // new uglifyJsPlugin({
    //     compress: {
    //         warnings: false
    //     }
    // }),
    new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery",
          "window.jQuery": "jquery",
          "root.jQuery": "jquery",
        }),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['index', 'login'],
        minChunks: 2,
    }),
    // new HtmlWebpackPlugin({
    //     title: 'hilshire\'s blog',
    //     filename: path.resolve(ROOT_PATH, 'app.html'),
    //     chunks: [path.resolve(ROOT_PATH, 'app.html'),]
    // }),
    // new HtmlWebpackPlugin({
    //     title: 'manager',
    //     filename: path.resolve(ROOT_PATH, 'manager.html')
    // }),
    // new HtmlWebpackPlugin({
    //     title: 'login',
    //     filename: path.resolve(ROOT_PATH, 'login.html'),
    //     chunks: [name]
    // })
  ],
}
<|endoftext|>


<commit_before>import c from 'cassowary/bin/c';
//import kiwi from 'kiwi/ts/bin/kiwi';
import Attribute from './Attribute';
import Relation from './Relation';
import SubView from './SubView';

const defaultPriorityStrength = process.env.CASSOWARYJS ? new c.Strength('defaultPriority', 0, 1000, 1000) : kiwi.Strength.create(0, 1000, 1000);

function _getConst(name, value) {
    if (process.env.CASSOWARYJS) {
        const vr = new c.Variable({value: value});
        this._solver.addConstraint(new c.StayConstraint(vr, c.Strength.required, 0));
        return vr;
    }
    else {
        const vr = new kiwi.Variable();
        this._solver.addConstraint(new kiwi.Constraint(vr, kiwi.Operator.Eq, 0));
        return vr;
    }
}

function _getSubView(viewName) {
    if (!viewName) {
        return this._parentSubView;
    }
    else if (viewName.name) {
        this._subViews[viewName.name] = this._subViews[viewName.name] || new SubView({
            name: viewName.name,
            solver: this._solver
        });
        this._subViews[viewName.name]._type = this._subViews[viewName.name]._type || viewName.type;
        return this._subViews[viewName.name];
    }
    else {
        this._subViews[viewName] = this._subViews[viewName] || new SubView({
            name: viewName,
            solver: this._solver
        });
        return this._subViews[viewName];
    }
}

function _getSpacing(constraint) {
    let index = 4;
    if (!constraint.view1 && (constraint.attr1 === 'left')) {
        index = 3;
    }
    else if (!constraint.view1 && (constraint.attr1 === 'top')) {
        index = 0;
    }
    else if (!constraint.view2 && (constraint.attr2 === 'right')) {
        index = 1;
    }
    else if (!constraint.view2 && (constraint.attr2 === 'bottom')) {
        index = 2;
    }
    else {
        switch (constraint.attr1) {
            case 'left':
            case 'right':
            case 'centerX':
            case 'leading':
            case 'trailing':
                index = 4;
                break;
            case 'zIndex':
                index = 6;
                break;
            default:
                index = 5;
        }
    }
    this._spacingVars = this._spacingVars || new Array(7);
    this._spacingExpr = this._spacingExpr || new Array(7);
    if (!this._spacingVars[index]) {
        if (process.env.CASSOWARYJS) {
            this._spacingVars[index] = new c.Variable();
            this._solver.addEditVar(this._spacingVars[index]);
            this._spacingExpr[index] = c.minus(0, this._spacingVars[index]);
        }
        else {
            this._spacingVars[index] = new kiwi.Variable();
            this._solver.addEditVariable(this._spacingVars[index], kiwi.Strength.create(999, 1000, 1000));
            this._spacingExpr[index] = this._spacingVars[index].multiply(-1);
        }
        this._solver.suggestValue(this._spacingVars[index], this._spacing[index]);
    }
    return this._spacingExpr[index];
}

function _addConstraint(constraint) {
    //this.constraints.push(constraint);
    let relation;
    const multiplier = (constraint.multiplier !== undefined) ? constraint.multiplier : 1;
    let constant = (constraint.constant !== undefined) ? constraint.constant : 0;
    if (constant === 'default') {
        constant = _getSpacing.call(this, constraint);
    }
    const attr1 = _getSubView.call(this, constraint.view1)._getAttr(constraint.attr1);
    let attr2;
    if (process.env.CASSOWARYJS) {
        if (constraint.attr2 === Attribute.CONST) {
            attr2 = _getConst.call(this, undefined, constraint.constant);
        }
        else {
            attr2 = _getSubView.call(this, constraint.view2)._getAttr(constraint.attr2);
            if ((multiplier !== 1) && constant) {
                attr2 = c.plus(c.times(attr2, multiplier), constant);
            }
            else if (constant) {
                attr2 = c.plus(attr2, constant);
            }
            else if (multiplier !== 1) {
                attr2 = c.times(attr2, multiplier);
            }
        }
        const strength = ((constraint.priority !== undefined) && (constraint.priority < 1000)) ? new c.Strength('priority', 0, constraint.priority, 1000) : defaultPriorityStrength;
        switch (constraint.relation) {
            case Relation.EQU:
                relation = new c.Equation(attr1, attr2, strength);
                break;
            case Relation.GEQ:
                relation = new c.Inequality(attr1, c.GEQ, attr2, strength);
                break;
            case Relation.LEQ:
                relation = new c.Inequality(attr1, c.LEQ, attr2, strength);
                break;
            default:
                throw 'Invalid relation specified: ' + constraint.relation;
        }
    }
    else {
        if (constraint.attr2 === Attribute.CONST) {
            attr2 = _getConst.call(this, undefined, constraint.constant);
        }
        else {
            attr2 = _getSubView.call(this, constraint.view2)._getAttr(constraint.attr2);
            if ((multiplier !== 1) && constant) {
                attr2 = attr2.multiply(multiplier).plus(constant);
            }
            else if (constant) {
                attr2 = attr2.plus(constant);
            }
            else if (multiplier !== 1) {
                attr2 = attr2.multiply(multiplier);
            }
        }
        const strength = ((constraint.priority !== undefined) && (constraint.priority < 1000)) ? kiwi.Strength.create(0, constraint.priority, 1000) : defaultPriorityStrength;
        switch (constraint.relation) {
            case Relation.EQU:
                relation = new kiwi.Constraint(attr1, kiwi.Operator.Eq, attr2, strength);
                break;
            case Relation.GEQ:
                relation = new kiwi.Constraint(attr1, kiwi.Operator.Ge, attr2, strength);
                break;
            case Relation.LEQ:
                relation = new kiwi.Constraint(attr1, kiwi.Operator.Le, attr2, strength);
                break;
            default:
                throw 'Invalid relation specified: ' + constraint.relation;
        }
    }
    this._solver.addConstraint(relation);
}

/**
 * AutoLayoutJS API reference.
 *
 * ### Index
 *
 * |Entity|Type|Description|
 * |---|---|---|
 * |[AutoLayout](#autolayout)|`namespace`|Top level AutoLayout object.|
 * |[VisualFormat](#autolayoutvisualformat--object)|`namespace`|Parses VFL into constraints.|
 * |[View](#autolayoutview)|`class`|Main entity for adding & evaluating constraints.|
 * |[SubView](#autolayoutsubview--object)|`class`|SubView's are automatically created when constraints are added to views. They give access to the evaluated results.|
 * |[Attribute](#autolayoutattribute--enum)|`enum`|Attribute types that are supported when adding constraints.|
 * |[Relation](#autolayoutrelation--enum)|`enum`|Relationship types that are supported when adding constraints.|
 * |[Priority](#autolayoutpriority--enum)|`enum`|Default priority values for when adding constraints.|
 *
 * ### AutoLayout
 *
 * @module AutoLayout
 */
class View {

    /**
     * @class View
     * @param {Object} [options] Configuration options.
     * @param {Number} [options.width] Initial width of the view.
     * @param {Number} [options.height] Initial height of the view.
     * @param {Number|Object} [options.spacing] Spacing for the view (default: 8) (see `setSpacing`).
     * @param {Array} [options.constraints] One or more constraint definitions (see `addConstraints`).
     */
    constructor(options) {
        this._solver = process.env.CASSOWARYJS ? new c.SimplexSolver() : new kiwi.Solver();
        this._subViews = {};
        //this._variables = {};
        this._spacing = {};
        this._parentSubView = new SubView({
            solver: this._solver
        });
        this.setSpacing((options && (options.spacing !== undefined)) ? options.spacing : 8);
        //this.constraints = [];
        if (options) {
            if ((options.width !== undefined) || (options.height !== undefined)) {
                this.setSize(options.width, options.height);
            }
            if (options.constraints) {
                this.addConstraints(options.constraints);
            }
        }
    }

    /**
     * Sets the width and height of the view.
     *
     * @param {Number} width Width of the view.
     * @param {Number} height Height of the view.
     * @return {View} this
     */
    setSize(width, height /*, depth*/) {
        this._parentSubView.intrinsicWidth = width;
        this._parentSubView.intrinsicHeight = height;
        return this;
    }

    /**
     * Width that was set using `setSize`.
     * @readonly
     * @type {Number}
     */
    get width() {
        return this._parentSubView.intrinsicWidth;
    }

    /**
     * Height that was set using `setSize`.
     * @readonly
     * @type {Number}
     */
    get height() {
        return this._parentSubView.intrinsicHeight;
    }

    /**
     * Width that is calculated from the constraints and the `.intrinsicWidth` of
     * the sub-views.
     *
     * When the width has been explicitely set using `setSize`, the fittingWidth
     * will **always** be the same as the explicitely set width. To calculate the size
     * based on the content, use:
     * ```javascript
     * var view = new AutoLayout.View({
     *   constraints: VisualFormat.parse('|-[view1]-[view2]-'),
     *   spacing: 20
     * });
     * view.subViews.view1.intrinsicWidth = 100;
     * view.subViews.view2.intrinsicWidth = 100;
     * console.log('fittingWidth: ' + view.fittingWidth); // 260
     * ```
     *
     * @readonly
     * @type {Number}
     */
    get fittingWidth() {
        return this._parentSubView.width;
    }

    /**
     * Height that is calculated from the constraints and the `.intrinsicHeight` of
     * the sub-views.
     *
     * See `.fittingWidth`.
     *
     * @readonly
     * @type {Number}
     */
    get fittingHeight() {
        return this._parentSubView.height;
    }

    /**
     * Sets the spacing for the view.
     *
     * The spacing can be set for 7 different variables:
     * `top`, `right`, `bottom`, `left`, `width`, `height` and `zIndex`. The `left`-spacing is
     * used when a spacer is used between the parent-view and a sub-view (e.g. `|-[subView]`).
     * The same is true for the `right`, `top` and `bottom` spacers. The `width` and `height` are
     * used for spacers in between sub-views (e.g. `[view1]-[view2]`).
     *
     * Instead of using the full spacing syntax, it is also possible to use shorthand notations:
     *
     * |Syntax|Type|Description|
     * |---|---|---|
     * |`[top, right, bottom, left, width, height, zIndex]`|Array(7)|Full syntax including z-index **(clockwise order)**.|
     * |`[top, right, bottom, left, width, height]`|Array(6)|Full horizontal & vertical spacing syntax (no z-index) **(clockwise order)**.|
     * |`[horizontal, vertical, zIndex]`|Array(3)|Horizontal = left, right, width, vertical = top, bottom, height.|
     * |`[horizontal, vertical]`|Array(2)|Horizontal = left, right, width, vertical = top, bottom, height, z-index = 1.|
     * |`spacing`|Number|Horizontal & vertical spacing are all the same, z-index = 1.|
     *
     * Examples:
     * ```javascript
     * view.setSpacing(10); // horizontal & vertical spacing 10
     * view.setSpacing([10, 15, 2]); // horizontal spacing 10, vertical spacing 15, z-axis spacing 2
     * view.setSpacing([10, 20, 10, 20, 5, 5]); // top, right, bottom, left, horizontal, vertical
     * view.setSpacing([10, 20, 10, 20, 5, 5, 1]); // top, right, bottom, left, horizontal, vertical, z
     * ```
     *
     * @param {Number|Array} spacing
     * @return {View} this
     */
    setSpacing(spacing) {
        // convert spacing into array: [top, right, bottom, left, horz, vert, z-index]
        switch (Array.isArray(spacing) ? spacing.length : -1) {
            case -1: spacing = [spacing, spacing, spacing, spacing, spacing, spacing, 1]; break;
            case 1: spacing = [spacing[0], spacing[0], spacing[0], spacing[0], spacing[0], spacing[0], 1]; break;
            case 2: spacing = [spacing[1], spacing[0], spacing[1], spacing[0], spacing[0], spacing[1], 1]; break;
            case 3: spacing = [spacing[1], spacing[0], spacing[1], spacing[0], spacing[0], spacing[1], spacing[2]]; break;
            case 6: spacing = [spacing[0], spacing[1], spacing[2], spacing[3], spacing[4], spacing[5], 1]; break;
            case 7: break;
            default: throw 'Invalid spacing syntax';
        }
        this._spacing = spacing;
        // update spacing variables
        if (this._spacingVars) {
            for (var i = 0; i < this._spacingVars.length; i++) {
                if (this._spacingVars[i]) {
                    this._solver.suggestValue(this._spacingVars[i], this._spacing[i]);
                }
            }
            if (process.env.CASSOWARYJS) {
                this._solver.resolve();
            }
            else {
                this._solver.updateVariables();
            }
        }
        return this;
    }

    /**
     * Adds a constraint definition.
     *
     * A constraint definition has the following format:
     *
     * ```javascript
     * constraint: {
     *   view1: {String},
     *   attr1: {AutoLayout.Attribute},
     *   relation: {AutoLayout.Relation},
     *   view2: {String},
     *   attr2: {AutoLayout.Attribute},
     *   multiplier: {Number},
     *   constant: {Number},
     *   priority: {Number}(0..1000)
     * }
     * ```
     * @param {Object} constraint Constraint definition.
     * @return {View} this
     */
    addConstraint(constraint) {
        _addConstraint.call(this, constraint);
        if (!process.env.CASSOWARYJS) {
            this._solver.updateVariables();
        }
        return this;
    }

    /**
     * Adds one or more constraint definitions.
     *
     * A constraint definition has the following format:
     *
     * ```javascript
     * constraint: {
     *   view1: {String},
     *   attr1: {AutoLayout.Attribute},
     *   relation: {AutoLayout.Relation},
     *   view2: {String},
     *   attr2: {AutoLayout.Attribute},
     *   multiplier: {Number},
     *   constant: {Number},
     *   priority: {Number}(0..1000)
     * }
     * ```
     * @param {Array} constraints One or more constraint definitions.
     * @return {View} this
     */
    addConstraints(constraints) {
        for (var j = 0; j < constraints.length; j++) {
            _addConstraint.call(this, constraints[j]);
        }
        if (!process.env.CASSOWARYJS) {
            this._solver.updateVariables();
        }
        return this;
    }

    /**
     * Dictionary of `SubView` objects that have been created when adding constraints.
     * @readonly
     * @type {Object.SubView}
     */
    get subViews() {
        return this._subViews;
    }

    /**
     * Checks whether the constraints incompletely specify the location
     * of the subViews.
     */
    get hasAmbiguousLayout() {
        // Todo
    }

    /**
     * Dictionary of `Variable` objects that have been created when adding constraints.
     * @type {Object.SubView}
     */
    /*
    get variables() {
        return this._variables;
    }*/
}

export default View;
<commit_msg>Disabled future code<commit_after>import c from 'cassowary/bin/c';
//import kiwi from 'kiwi/ts/bin/kiwi';
import Attribute from './Attribute';
import Relation from './Relation';
import SubView from './SubView';

const defaultPriorityStrength = process.env.CASSOWARYJS ? new c.Strength('defaultPriority', 0, 1000, 1000) : kiwi.Strength.create(0, 1000, 1000);

function _getConst(name, value) {
    if (process.env.CASSOWARYJS) {
        const vr = new c.Variable({value: value});
        this._solver.addConstraint(new c.StayConstraint(vr, c.Strength.required, 0));
        return vr;
    }
    else {
        const vr = new kiwi.Variable();
        this._solver.addConstraint(new kiwi.Constraint(vr, kiwi.Operator.Eq, 0));
        return vr;
    }
}

function _getSubView(viewName) {
    if (!viewName) {
        return this._parentSubView;
    }
    else if (viewName.name) {
        this._subViews[viewName.name] = this._subViews[viewName.name] || new SubView({
            name: viewName.name,
            solver: this._solver
        });
        this._subViews[viewName.name]._type = this._subViews[viewName.name]._type || viewName.type;
        return this._subViews[viewName.name];
    }
    else {
        this._subViews[viewName] = this._subViews[viewName] || new SubView({
            name: viewName,
            solver: this._solver
        });
        return this._subViews[viewName];
    }
}

function _getSpacing(constraint) {
    let index = 4;
    if (!constraint.view1 && (constraint.attr1 === 'left')) {
        index = 3;
    }
    else if (!constraint.view1 && (constraint.attr1 === 'top')) {
        index = 0;
    }
    else if (!constraint.view2 && (constraint.attr2 === 'right')) {
        index = 1;
    }
    else if (!constraint.view2 && (constraint.attr2 === 'bottom')) {
        index = 2;
    }
    else {
        switch (constraint.attr1) {
            case 'left':
            case 'right':
            case 'centerX':
            case 'leading':
            case 'trailing':
                index = 4;
                break;
            case 'zIndex':
                index = 6;
                break;
            default:
                index = 5;
        }
    }
    this._spacingVars = this._spacingVars || new Array(7);
    this._spacingExpr = this._spacingExpr || new Array(7);
    if (!this._spacingVars[index]) {
        if (process.env.CASSOWARYJS) {
            this._spacingVars[index] = new c.Variable();
            this._solver.addEditVar(this._spacingVars[index]);
            this._spacingExpr[index] = c.minus(0, this._spacingVars[index]);
        }
        else {
            this._spacingVars[index] = new kiwi.Variable();
            this._solver.addEditVariable(this._spacingVars[index], kiwi.Strength.create(999, 1000, 1000));
            this._spacingExpr[index] = this._spacingVars[index].multiply(-1);
        }
        this._solver.suggestValue(this._spacingVars[index], this._spacing[index]);
    }
    return this._spacingExpr[index];
}

function _addConstraint(constraint) {
    //this.constraints.push(constraint);
    let relation;
    const multiplier = (constraint.multiplier !== undefined) ? constraint.multiplier : 1;
    let constant = (constraint.constant !== undefined) ? constraint.constant : 0;
    if (constant === 'default') {
        constant = _getSpacing.call(this, constraint);
    }
    const attr1 = _getSubView.call(this, constraint.view1)._getAttr(constraint.attr1);
    let attr2;
    if (process.env.CASSOWARYJS) {
        if (constraint.attr2 === Attribute.CONST) {
            attr2 = _getConst.call(this, undefined, constraint.constant);
        }
        else {
            attr2 = _getSubView.call(this, constraint.view2)._getAttr(constraint.attr2);
            if ((multiplier !== 1) && constant) {
                attr2 = c.plus(c.times(attr2, multiplier), constant);
            }
            else if (constant) {
                attr2 = c.plus(attr2, constant);
            }
            else if (multiplier !== 1) {
                attr2 = c.times(attr2, multiplier);
            }
        }
        const strength = ((constraint.priority !== undefined) && (constraint.priority < 1000)) ? new c.Strength('priority', 0, constraint.priority, 1000) : defaultPriorityStrength;
        switch (constraint.relation) {
            case Relation.EQU:
                relation = new c.Equation(attr1, attr2, strength);
                break;
            case Relation.GEQ:
                relation = new c.Inequality(attr1, c.GEQ, attr2, strength);
                break;
            case Relation.LEQ:
                relation = new c.Inequality(attr1, c.LEQ, attr2, strength);
                break;
            default:
                throw 'Invalid relation specified: ' + constraint.relation;
        }
    }
    else {
        if (constraint.attr2 === Attribute.CONST) {
            attr2 = _getConst.call(this, undefined, constraint.constant);
        }
        else {
            attr2 = _getSubView.call(this, constraint.view2)._getAttr(constraint.attr2);
            if ((multiplier !== 1) && constant) {
                attr2 = attr2.multiply(multiplier).plus(constant);
            }
            else if (constant) {
                attr2 = attr2.plus(constant);
            }
            else if (multiplier !== 1) {
                attr2 = attr2.multiply(multiplier);
            }
        }
        const strength = ((constraint.priority !== undefined) && (constraint.priority < 1000)) ? kiwi.Strength.create(0, constraint.priority, 1000) : defaultPriorityStrength;
        switch (constraint.relation) {
            case Relation.EQU:
                relation = new kiwi.Constraint(attr1, kiwi.Operator.Eq, attr2, strength);
                break;
            case Relation.GEQ:
                relation = new kiwi.Constraint(attr1, kiwi.Operator.Ge, attr2, strength);
                break;
            case Relation.LEQ:
                relation = new kiwi.Constraint(attr1, kiwi.Operator.Le, attr2, strength);
                break;
            default:
                throw 'Invalid relation specified: ' + constraint.relation;
        }
    }
    this._solver.addConstraint(relation);
}

/**
 * AutoLayoutJS API reference.
 *
 * ### Index
 *
 * |Entity|Type|Description|
 * |---|---|---|
 * |[AutoLayout](#autolayout)|`namespace`|Top level AutoLayout object.|
 * |[VisualFormat](#autolayoutvisualformat--object)|`namespace`|Parses VFL into constraints.|
 * |[View](#autolayoutview)|`class`|Main entity for adding & evaluating constraints.|
 * |[SubView](#autolayoutsubview--object)|`class`|SubView's are automatically created when constraints are added to views. They give access to the evaluated results.|
 * |[Attribute](#autolayoutattribute--enum)|`enum`|Attribute types that are supported when adding constraints.|
 * |[Relation](#autolayoutrelation--enum)|`enum`|Relationship types that are supported when adding constraints.|
 * |[Priority](#autolayoutpriority--enum)|`enum`|Default priority values for when adding constraints.|
 *
 * ### AutoLayout
 *
 * @module AutoLayout
 */
class View {

    /**
     * @class View
     * @param {Object} [options] Configuration options.
     * @param {Number} [options.width] Initial width of the view.
     * @param {Number} [options.height] Initial height of the view.
     * @param {Number|Object} [options.spacing] Spacing for the view (default: 8) (see `setSpacing`).
     * @param {Array} [options.constraints] One or more constraint definitions (see `addConstraints`).
     */
    constructor(options) {
        this._solver = process.env.CASSOWARYJS ? new c.SimplexSolver() : new kiwi.Solver();
        this._subViews = {};
        //this._variables = {};
        this._spacing = {};
        this._parentSubView = new SubView({
            solver: this._solver
        });
        this.setSpacing((options && (options.spacing !== undefined)) ? options.spacing : 8);
        //this.constraints = [];
        if (options) {
            if ((options.width !== undefined) || (options.height !== undefined)) {
                this.setSize(options.width, options.height);
            }
            if (options.constraints) {
                this.addConstraints(options.constraints);
            }
        }
    }

    /**
     * Sets the width and height of the view.
     *
     * @param {Number} width Width of the view.
     * @param {Number} height Height of the view.
     * @return {View} this
     */
    setSize(width, height /*, depth*/) {
        this._parentSubView.intrinsicWidth = width;
        this._parentSubView.intrinsicHeight = height;
        return this;
    }

    /**
     * Width that was set using `setSize`.
     * @readonly
     * @type {Number}
     */
    get width() {
        return this._parentSubView.intrinsicWidth;
    }

    /**
     * Height that was set using `setSize`.
     * @readonly
     * @type {Number}
     */
    get height() {
        return this._parentSubView.intrinsicHeight;
    }

    /**
     * Width that is calculated from the constraints and the `.intrinsicWidth` of
     * the sub-views.
     *
     * When the width has been explicitely set using `setSize`, the fittingWidth
     * will **always** be the same as the explicitely set width. To calculate the size
     * based on the content, use:
     * ```javascript
     * var view = new AutoLayout.View({
     *   constraints: VisualFormat.parse('|-[view1]-[view2]-'),
     *   spacing: 20
     * });
     * view.subViews.view1.intrinsicWidth = 100;
     * view.subViews.view2.intrinsicWidth = 100;
     * console.log('fittingWidth: ' + view.fittingWidth); // 260
     * ```
     *
     * @readonly
     * @type {Number}
     */
    get fittingWidth() {
        return this._parentSubView.width;
    }

    /**
     * Height that is calculated from the constraints and the `.intrinsicHeight` of
     * the sub-views.
     *
     * See `.fittingWidth`.
     *
     * @readonly
     * @type {Number}
     */
    get fittingHeight() {
        return this._parentSubView.height;
    }

    /**
     * Sets the spacing for the view.
     *
     * The spacing can be set for 7 different variables:
     * `top`, `right`, `bottom`, `left`, `width`, `height` and `zIndex`. The `left`-spacing is
     * used when a spacer is used between the parent-view and a sub-view (e.g. `|-[subView]`).
     * The same is true for the `right`, `top` and `bottom` spacers. The `width` and `height` are
     * used for spacers in between sub-views (e.g. `[view1]-[view2]`).
     *
     * Instead of using the full spacing syntax, it is also possible to use shorthand notations:
     *
     * |Syntax|Type|Description|
     * |---|---|---|
     * |`[top, right, bottom, left, width, height, zIndex]`|Array(7)|Full syntax including z-index **(clockwise order)**.|
     * |`[top, right, bottom, left, width, height]`|Array(6)|Full horizontal & vertical spacing syntax (no z-index) **(clockwise order)**.|
     * |`[horizontal, vertical, zIndex]`|Array(3)|Horizontal = left, right, width, vertical = top, bottom, height.|
     * |`[horizontal, vertical]`|Array(2)|Horizontal = left, right, width, vertical = top, bottom, height, z-index = 1.|
     * |`spacing`|Number|Horizontal & vertical spacing are all the same, z-index = 1.|
     *
     * Examples:
     * ```javascript
     * view.setSpacing(10); // horizontal & vertical spacing 10
     * view.setSpacing([10, 15, 2]); // horizontal spacing 10, vertical spacing 15, z-axis spacing 2
     * view.setSpacing([10, 20, 10, 20, 5, 5]); // top, right, bottom, left, horizontal, vertical
     * view.setSpacing([10, 20, 10, 20, 5, 5, 1]); // top, right, bottom, left, horizontal, vertical, z
     * ```
     *
     * @param {Number|Array} spacing
     * @return {View} this
     */
    setSpacing(spacing) {
        // convert spacing into array: [top, right, bottom, left, horz, vert, z-index]
        switch (Array.isArray(spacing) ? spacing.length : -1) {
            case -1: spacing = [spacing, spacing, spacing, spacing, spacing, spacing, 1]; break;
            case 1: spacing = [spacing[0], spacing[0], spacing[0], spacing[0], spacing[0], spacing[0], 1]; break;
            case 2: spacing = [spacing[1], spacing[0], spacing[1], spacing[0], spacing[0], spacing[1], 1]; break;
            case 3: spacing = [spacing[1], spacing[0], spacing[1], spacing[0], spacing[0], spacing[1], spacing[2]]; break;
            case 6: spacing = [spacing[0], spacing[1], spacing[2], spacing[3], spacing[4], spacing[5], 1]; break;
            case 7: break;
            default: throw 'Invalid spacing syntax';
        }
        this._spacing = spacing;
        // update spacing variables
        if (this._spacingVars) {
            for (var i = 0; i < this._spacingVars.length; i++) {
                if (this._spacingVars[i]) {
                    this._solver.suggestValue(this._spacingVars[i], this._spacing[i]);
                }
            }
            if (process.env.CASSOWARYJS) {
                this._solver.resolve();
            }
            else {
                this._solver.updateVariables();
            }
        }
        return this;
    }

    /**
     * Adds a constraint definition.
     *
     * A constraint definition has the following format:
     *
     * ```javascript
     * constraint: {
     *   view1: {String},
     *   attr1: {AutoLayout.Attribute},
     *   relation: {AutoLayout.Relation},
     *   view2: {String},
     *   attr2: {AutoLayout.Attribute},
     *   multiplier: {Number},
     *   constant: {Number},
     *   priority: {Number}(0..1000)
     * }
     * ```
     * @param {Object} constraint Constraint definition.
     * @return {View} this
     */
    addConstraint(constraint) {
        _addConstraint.call(this, constraint);
        if (!process.env.CASSOWARYJS) {
            this._solver.updateVariables();
        }
        return this;
    }

    /**
     * Adds one or more constraint definitions.
     *
     * A constraint definition has the following format:
     *
     * ```javascript
     * constraint: {
     *   view1: {String},
     *   attr1: {AutoLayout.Attribute},
     *   relation: {AutoLayout.Relation},
     *   view2: {String},
     *   attr2: {AutoLayout.Attribute},
     *   multiplier: {Number},
     *   constant: {Number},
     *   priority: {Number}(0..1000)
     * }
     * ```
     * @param {Array} constraints One or more constraint definitions.
     * @return {View} this
     */
    addConstraints(constraints) {
        for (var j = 0; j < constraints.length; j++) {
            _addConstraint.call(this, constraints[j]);
        }
        if (!process.env.CASSOWARYJS) {
            this._solver.updateVariables();
        }
        return this;
    }

    /**
     * Dictionary of `SubView` objects that have been created when adding constraints.
     * @readonly
     * @type {Object.SubView}
     */
    get subViews() {
        return this._subViews;
    }

    /**
     * Checks whether the constraints incompletely specify the location
     * of the subViews.
     * @private
     */
    //get hasAmbiguousLayout() {
        // Todo
    //}

    /**
     * Dictionary of `Variable` objects that have been created when adding constraints.
     * @type {Object.SubView}
     */
    /*
    get variables() {
        return this._variables;
    }*/
}

export default View;
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const validate = require('webpack-validator');

const common = {
  debug: true,
  devtool: "#eval-source-map",
  entry: path.resolve(__dirname, 'client/index'),
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/assets/'
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        include: path.resolve(__dirname, 'client'),
        exclude: /(node_modules|bower_components)/,
      },
      // Disabling SCSS thru webpack for now (still gulping)
      // {
      //   test: /\.(scss|css)$/,
      //   loader: 'style!css!sass?sourceMap',
      //   exclude: /node_modules/,
      // },
      {
        test: /\.(jpg|png)$/,
        loader: 'file',
        include: path.resolve(__dirname, 'client/images'),
        exclude: /node_modules/,
      }
    ]
  },
  resolve: {
    root: path.resolve(__dirname, 'client'),
    extensions: [
      '',
      '.js',
      '.jsx',
      // '.sass',
      // '.css',
    ],
  },
}

var config; // Will be our final webpack config

if (process.env.NODE_ENV === 'development') {
  config = merge(common, {
    entry: [
      'react-hot-loader/patch',
      'webpack-hot-middleware/client',
      path.resolve(__dirname, 'client/index')
    ],
    plugins: [
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.HotModuleReplacementPlugin()
    ]
  })
} else {
  config = merge(common, {
    plugins: [
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin()
    ]
  });
}

module.exports = validate(config);

/**
 * devtool: 'eval', // http://webpack.github.io/docs/configuration.html#devtool
 */<commit_msg>update webpack config to minify<commit_after>const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const validate = require('webpack-validator');

const common = {
  debug: true,
  devtool: "#eval-source-map",
  entry: path.resolve(__dirname, 'client/index'),
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/assets/'
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        include: path.resolve(__dirname, 'client'),
        exclude: /(node_modules|bower_components)/,
      },
      // Disabling SCSS thru webpack for now (still gulping)
      // {
      //   test: /\.(scss|css)$/,
      //   loader: 'style!css!sass?sourceMap',
      //   exclude: /node_modules/,
      // },
      {
        test: /\.(jpg|png)$/,
        loader: 'file',
        include: path.resolve(__dirname, 'client/images'),
        exclude: /node_modules/,
      }
    ]
  },
  resolve: {
    root: path.resolve(__dirname, 'client'),
    extensions: [
      '',
      '.js',
      '.jsx',
      // '.sass',
      // '.css',
    ],
  },
}

var config; // Will be our final webpack config

if (process.env.NODE_ENV === 'development') {
  config = merge(common, {
    entry: [
      'react-hot-loader/patch',
      'webpack-hot-middleware/client',
      path.resolve(__dirname, 'client/index')
    ],
    plugins: [
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.HotModuleReplacementPlugin()
    ]
  })
} else {
  config = merge(common, {
    plugins: [
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin()
    ]
  });
}

module.exports = validate(config);

/**
 * devtool: 'eval', // http://webpack.github.io/docs/configuration.html#devtool
 */
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var gulp = require('gulp'),
    del = require('del'),
    wiredep = require('wiredep').stream,
    eventStream = require('event-stream'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    xml2js = require('xml2js'),
    map = require('vinyl-map'),
    fs = require('fs'),
    path = require('path'),
    size = require('gulp-size'),
    s = require('underscore.string'),
    tslint = require('gulp-tslint'),
    argv = require('yargs').argv,
    jsString;

var inProgress = false;

// CONSTANTS

var POM_MAIN_PATH = '../../../pom.xml';
var DIST_TARGET_PATH = '../../../dist/target/';
var WF_CONSOLE_PATH = 'modules/org/hawkular/nest/main/deployments/hawkular-console.war/dist/';

var plugins = gulpLoadPlugins({
  rename: {
    'gulp-if-else': 'gulpif'
  }
});

var pkg = require('./package.json');
var normalSizeOptions = {
    showFiles: true
}, gZippedSizeOptions = {
    showFiles: true,
    gzip: true
};

var config = {
    main: '.',
    ts: ['plugins/**/*.ts'],
    templates: ['plugins/**/*.html'],
    templateModule: pkg.name + '-templates',
    dist: './dist/',
    js: pkg.name + '.js',
    tsProject: plugins.typescript.createProject({
        target: 'ES5',
        module: 'commonjs',
        declarationFiles: true,
        noExternalResolve: false
    }),
    srcPrefix: '../../src/main/scripts/',
    serverPath: DIST_TARGET_PATH + 'hawkular-1.0.0-SNAPSHOT/' + WF_CONSOLE_PATH
};

gulp.task('set-server-path', function(done) {
  var parser = new xml2js.Parser();
  parser.addListener('end', function(result) {
    config.serverPath = DIST_TARGET_PATH + 'hawkular-' + result.project.version + '/hawkular-' + result.project.version + '/' + WF_CONSOLE_PATH;
    done();
  });

  fs.readFile(POM_MAIN_PATH, 'utf8', function (err, xmlString) {
    if (err) throw err;
    parser.parseString(xmlString);
  });
});

gulp.task('bower', function () {
    var cacheBuster = Date.now();

    gulp.src('*.html')
        .pipe(wiredep({
          fileTypes: {
            html: {
              replace: {
                js: '<script src="{{filePath}}?v=' + cacheBuster + '"></script>',
                css: '<link rel="stylesheet" href="{{filePath}}?v=' + cacheBuster + '" />'
              }
            }
          }
        }))
        .pipe(gulp.dest('.'));
});

/** Adjust the reference path of any typescript-built plugin this project depends on
 * the hawt.io projects need this */
gulp.task('path-adjust', function () {
    gulp.src('libs/**/includes.d.ts')
        .pipe(map(function (buf, filename) {
            var textContent = buf.toString();
            var newTextContent = textContent.replace(/"\.\.\/libs/gm, '"../../../libs');
            // console.log("Filename: ", filename, " old: ", textContent, " new:", newTextContent);
            return newTextContent;
        }))
        .pipe(gulp.dest('libs'));
});

gulp.task('clean-defs', function () {
    del(['defs.d.ts/**']);
});

gulp.task('git-sha', function(cb) {
  var versionFile = 'version.js';

  if(!jsString) {
    plugins.git.exec({args: "log -n 1 --pretty='%h'"}, function (err, stdout) {
      if (err) throw err;
      var gitSha = stdout.slice(0, -1);
      jsString = 'var HawkularVersion = \"' + gitSha + '\";';
      fs.writeFileSync(versionFile, jsString);
      cb();
    });
  } else {
    fs.writeFileSync(versionFile, jsString);
    cb();
  }
});

var gulpTsc = function(done) {
  var cwd = process.cwd();
  var tsResult = gulp.src(config.ts)
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.typescript(config.tsProject))
    .on('error', plugins.notify.onError({
      message: '<%= error.message %>',
      title: 'Typescript compilation error'
    }));

  return eventStream.merge(
    tsResult.js
      .pipe(plugins.concat('compiled.js'))
      .pipe(plugins.sourcemaps.write())
      .pipe(gulp.dest('.')),
    tsResult.dts
      .pipe(gulp.dest('d.ts')))
    .pipe(map(function (buf, filename) {
      if (!s.endsWith(filename, 'd.ts')) {
        return buf;
      }
      var relative = path.relative(cwd, filename);
      fs.appendFileSync('defs.d.ts', '/// <reference path="' + relative + '"/>\n');
      return buf;
    })).on('end', function(){
      done && done();
    });
};

gulp.task('tsc', ['clean-defs' ], function (done) {
  gulpTsc(done);
});

gulp.task('tsc-live', ['copy-sources','clean-defs' ], function (done) {
  gulpTsc(done);
});

gulp.task('tslint', function () {
    gulp.src(config.ts)
        .pipe(tslint())
        .pipe(tslint.report('verbose'));
});

gulp.task('tslint-watch', ['copy-sources'], function () {
    gulp.src(config.ts)
        .pipe(tslint())
        .pipe(tslint.report('prose', {
            emitError: false
        }));
});

var gulpTemplate = function(){
  return gulp.src(config.templates)
    .pipe(plugins.angularTemplatecache({
      filename: 'templates.js',
      root: '',
      base: function(file){
        var filename = /[^/]*$/.exec( file.relative).input;
        return 'plugins/' + filename;
      },
      standalone: true,
      module: config.templateModule,
      templateFooter: '}]); hawtioPluginLoader.addModule("' + config.templateModule + '");'
    }))
    .pipe(gulp.dest('.'));
};

gulp.task('template', ['tsc'], function () {
  return gulpTemplate();
});

gulp.task('template-live', ['tsc-live', 'copy-sources'], function () {
  return gulpTemplate();
});

var gulpLess = function(done) {
  gulp.src(['plugins/**/*.less'])
    .pipe(plugins.less())
    .pipe(plugins.concat('hawkular-console.css'))
    .pipe(gulp.dest(config.dist))
    .on('end', function(){
      done && done();
    });
};

gulp.task('less', function(){
  gulpLess();
});

gulp.task('less-live', ['copy-sources'], function(done){
  gulpLess(done);
});

var gulpConcat = function() {
  var gZipSize = size(gZippedSizeOptions);

  return gulp.src(['compiled.js', 'templates.js', 'version.js'])
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.concat(config.js))
    .pipe(plugins.sourcemaps.write())
    .pipe(plugins.gulpif(argv.production, plugins.uglify))
    .pipe(gulp.dest(config.dist))
    .pipe(size(normalSizeOptions))
    .pipe(gZipSize);
};

gulp.task('concat', ['template', 'tsc', 'git-sha'], function () {
  return gulpConcat();
});

gulp.task('concat-live', ['template-live', 'tsc-live', 'git-sha'], function () {
  return gulpConcat();
});

gulp.task('clean', ['concat'], function () {
    del(['templates.js', 'compiled.js']);
});

gulp.task('watch-server', ['build-live', 'copy-kettle-js', 'copy-kettle-css'], function () {
    plugins.watch([config.srcPrefix + 'plugins/**/*.ts', config.srcPrefix + '/plugins/**/*.html'], function () {
        gulp.start('copy-kettle-js');
    });

    plugins.watch([config.srcPrefix + '/plugins/**/*.less'], function () {
      gulp.start('copy-kettle-css');
    });
});

gulp.task('clean-sources', function(done) {
  if (!inProgress) {
    inProgress = true;
    del(['./plugins/**/*.ts', './plugins/**/*.less', './plugins/**/*.html']).then(done());
  }
  else {
    done();
  }
});

gulp.task('copy-sources', ['clean-sources'], function(done) {
  var src = [config.srcPrefix + 'plugins/**/*'];

  gulp.src(src)
  .pipe(gulp.dest('./plugins')).on('end', function() {
    done();
  });
});

gulp.task('copy-kettle-js', ['build-live','set-server-path'] , function() {
  inProgress = false;
  gulp.src(['dist/hawkular-console.js'])
    .pipe(gulp.dest(config.serverPath));
});

gulp.task('copy-vendor-fonts', function(done) {
  var src = [config.srcPrefix + 'plugins/**/vendor/fonts/*.*'];

  gulp.src(src)
    .pipe(gulp.dest(config.dist)).on('end', function(){
      done();
    });
});

gulp.task('copy-vendor-js', function(done) {
  var src = [config.srcPrefix + 'plugins/**/vendor/**/*.js'];

  gulp.src(src)
    .pipe(gulp.dest(config.dist)).on('end', function(){
      done();
    });
});

gulp.task('copy-vendor-css', function(done) {
  var src = [config.srcPrefix + 'plugins/**/vendor/**/*.css'];

  gulp.src(src)
    .pipe(gulp.dest(config.dist)).on('end', function(){
      done();
    });
});

gulp.task('copy-kettle-css', ['less-live','set-server-path'] , function() {
  inProgress = false;
  gulp.src(['dist/hawkular-console.css'])
    .pipe(gulp.dest(config.serverPath));
});

gulp.task('build', ['bower', 'path-adjust', 'tslint', 'tsc', 'less', 'template', 'concat', 'copy-vendor-js', 'copy-vendor-css', 'copy-vendor-fonts', 'clean']);
gulp.task('build-live', ['copy-sources', 'bower', 'path-adjust', 'tslint-watch', 'tsc-live', 'less-live', 'template-live', 'concat-live', 'copy-vendor-js', 'copy-vendor-css', 'copy-vendor-fonts']);
<commit_msg>Adapt gulp-watch dist target to new location<commit_after>/*
 * Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var gulp = require('gulp'),
    del = require('del'),
    wiredep = require('wiredep').stream,
    eventStream = require('event-stream'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    xml2js = require('xml2js'),
    map = require('vinyl-map'),
    fs = require('fs'),
    path = require('path'),
    size = require('gulp-size'),
    s = require('underscore.string'),
    tslint = require('gulp-tslint'),
    argv = require('yargs').argv,
    jsString;

var inProgress = false;

// CONSTANTS

var POM_MAIN_PATH = '../../../pom.xml';
var DIST_TARGET_PATH = '../../../dist/target/';
var WF_CONSOLE_PATH = 'modules/org/hawkular/nest/main/deployments/hawkular-console.war/dist/';

var plugins = gulpLoadPlugins({
  rename: {
    'gulp-if-else': 'gulpif'
  }
});

var pkg = require('./package.json');
var normalSizeOptions = {
    showFiles: true
}, gZippedSizeOptions = {
    showFiles: true,
    gzip: true
};

var config = {
    main: '.',
    ts: ['plugins/**/*.ts'],
    templates: ['plugins/**/*.html'],
    templateModule: pkg.name + '-templates',
    dist: './dist/',
    js: pkg.name + '.js',
    tsProject: plugins.typescript.createProject({
        target: 'ES5',
        module: 'commonjs',
        declarationFiles: true,
        noExternalResolve: false
    }),
    srcPrefix: '../../src/main/scripts/',
    serverPath: DIST_TARGET_PATH + 'hawkular-1.0.0-SNAPSHOT/' + WF_CONSOLE_PATH
};

gulp.task('set-server-path', function(done) {
  var parser = new xml2js.Parser();
  parser.addListener('end', function(result) {
    config.serverPath = DIST_TARGET_PATH + 'hawkular-' + result.project.version + '/' + WF_CONSOLE_PATH;
    done();
  });

  fs.readFile(POM_MAIN_PATH, 'utf8', function (err, xmlString) {
    if (err) throw err;
    parser.parseString(xmlString);
  });
});

gulp.task('bower', function () {
    var cacheBuster = Date.now();

    gulp.src('*.html')
        .pipe(wiredep({
          fileTypes: {
            html: {
              replace: {
                js: '<script src="{{filePath}}?v=' + cacheBuster + '"></script>',
                css: '<link rel="stylesheet" href="{{filePath}}?v=' + cacheBuster + '" />'
              }
            }
          }
        }))
        .pipe(gulp.dest('.'));
});

/** Adjust the reference path of any typescript-built plugin this project depends on
 * the hawt.io projects need this */
gulp.task('path-adjust', function () {
    gulp.src('libs/**/includes.d.ts')
        .pipe(map(function (buf, filename) {
            var textContent = buf.toString();
            var newTextContent = textContent.replace(/"\.\.\/libs/gm, '"../../../libs');
            // console.log("Filename: ", filename, " old: ", textContent, " new:", newTextContent);
            return newTextContent;
        }))
        .pipe(gulp.dest('libs'));
});

gulp.task('clean-defs', function () {
    del(['defs.d.ts/**']);
});

gulp.task('git-sha', function(cb) {
  var versionFile = 'version.js';

  if(!jsString) {
    plugins.git.exec({args: "log -n 1 --pretty='%h'"}, function (err, stdout) {
      if (err) throw err;
      var gitSha = stdout.slice(0, -1);
      jsString = 'var HawkularVersion = \"' + gitSha + '\";';
      fs.writeFileSync(versionFile, jsString);
      cb();
    });
  } else {
    fs.writeFileSync(versionFile, jsString);
    cb();
  }
});

var gulpTsc = function(done) {
  var cwd = process.cwd();
  var tsResult = gulp.src(config.ts)
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.typescript(config.tsProject))
    .on('error', plugins.notify.onError({
      message: '<%= error.message %>',
      title: 'Typescript compilation error'
    }));

  return eventStream.merge(
    tsResult.js
      .pipe(plugins.concat('compiled.js'))
      .pipe(plugins.sourcemaps.write())
      .pipe(gulp.dest('.')),
    tsResult.dts
      .pipe(gulp.dest('d.ts')))
    .pipe(map(function (buf, filename) {
      if (!s.endsWith(filename, 'd.ts')) {
        return buf;
      }
      var relative = path.relative(cwd, filename);
      fs.appendFileSync('defs.d.ts', '/// <reference path="' + relative + '"/>\n');
      return buf;
    })).on('end', function(){
      done && done();
    });
};

gulp.task('tsc', ['clean-defs' ], function (done) {
  gulpTsc(done);
});

gulp.task('tsc-live', ['copy-sources','clean-defs' ], function (done) {
  gulpTsc(done);
});

gulp.task('tslint', function () {
    gulp.src(config.ts)
        .pipe(tslint())
        .pipe(tslint.report('verbose'));
});

gulp.task('tslint-watch', ['copy-sources'], function () {
    gulp.src(config.ts)
        .pipe(tslint())
        .pipe(tslint.report('prose', {
            emitError: false
        }));
});

var gulpTemplate = function(){
  return gulp.src(config.templates)
    .pipe(plugins.angularTemplatecache({
      filename: 'templates.js',
      root: '',
      base: function(file){
        var filename = /[^/]*$/.exec( file.relative).input;
        return 'plugins/' + filename;
      },
      standalone: true,
      module: config.templateModule,
      templateFooter: '}]); hawtioPluginLoader.addModule("' + config.templateModule + '");'
    }))
    .pipe(gulp.dest('.'));
};

gulp.task('template', ['tsc'], function () {
  return gulpTemplate();
});

gulp.task('template-live', ['tsc-live', 'copy-sources'], function () {
  return gulpTemplate();
});

var gulpLess = function(done) {
  gulp.src(['plugins/**/*.less'])
    .pipe(plugins.less())
    .pipe(plugins.concat('hawkular-console.css'))
    .pipe(gulp.dest(config.dist))
    .on('end', function(){
      done && done();
    });
};

gulp.task('less', function(){
  gulpLess();
});

gulp.task('less-live', ['copy-sources'], function(done){
  gulpLess(done);
});

var gulpConcat = function() {
  var gZipSize = size(gZippedSizeOptions);

  return gulp.src(['compiled.js', 'templates.js', 'version.js'])
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.concat(config.js))
    .pipe(plugins.sourcemaps.write())
    .pipe(plugins.gulpif(argv.production, plugins.uglify))
    .pipe(gulp.dest(config.dist))
    .pipe(size(normalSizeOptions))
    .pipe(gZipSize);
};

gulp.task('concat', ['template', 'tsc', 'git-sha'], function () {
  return gulpConcat();
});

gulp.task('concat-live', ['template-live', 'tsc-live', 'git-sha'], function () {
  return gulpConcat();
});

gulp.task('clean', ['concat'], function () {
    del(['templates.js', 'compiled.js']);
});

gulp.task('watch-server', ['build-live', 'copy-kettle-js', 'copy-kettle-css'], function () {
    plugins.watch([config.srcPrefix + 'plugins/**/*.ts', config.srcPrefix + '/plugins/**/*.html'], function () {
        gulp.start('copy-kettle-js');
    });

    plugins.watch([config.srcPrefix + '/plugins/**/*.less'], function () {
      gulp.start('copy-kettle-css');
    });
});

gulp.task('clean-sources', function(done) {
  if (!inProgress) {
    inProgress = true;
    del(['./plugins/**/*.ts', './plugins/**/*.less', './plugins/**/*.html']).then(done());
  }
  else {
    done();
  }
});

gulp.task('copy-sources', ['clean-sources'], function(done) {
  var src = [config.srcPrefix + 'plugins/**/*'];

  gulp.src(src)
  .pipe(gulp.dest('./plugins')).on('end', function() {
    done();
  });
});

gulp.task('copy-kettle-js', ['build-live','set-server-path'] , function() {
  inProgress = false;
  gulp.src(['dist/hawkular-console.js'])
    .pipe(gulp.dest(config.serverPath));
});

gulp.task('copy-vendor-fonts', function(done) {
  var src = [config.srcPrefix + 'plugins/**/vendor/fonts/*.*'];

  gulp.src(src)
    .pipe(gulp.dest(config.dist)).on('end', function(){
      done();
    });
});

gulp.task('copy-vendor-js', function(done) {
  var src = [config.srcPrefix + 'plugins/**/vendor/**/*.js'];

  gulp.src(src)
    .pipe(gulp.dest(config.dist)).on('end', function(){
      done();
    });
});

gulp.task('copy-vendor-css', function(done) {
  var src = [config.srcPrefix + 'plugins/**/vendor/**/*.css'];

  gulp.src(src)
    .pipe(gulp.dest(config.dist)).on('end', function(){
      done();
    });
});

gulp.task('copy-kettle-css', ['less-live','set-server-path'] , function() {
  inProgress = false;
  gulp.src(['dist/hawkular-console.css'])
    .pipe(gulp.dest(config.serverPath));
});

gulp.task('build', ['bower', 'path-adjust', 'tslint', 'tsc', 'less', 'template', 'concat', 'copy-vendor-js', 'copy-vendor-css', 'copy-vendor-fonts', 'clean']);
gulp.task('build-live', ['copy-sources', 'bower', 'path-adjust', 'tslint-watch', 'tsc-live', 'less-live', 'template-live', 'concat-live', 'copy-vendor-js', 'copy-vendor-css', 'copy-vendor-fonts']);
<|endoftext|>


<commit_before>define(function (require) {

    var text = require('text');
    var urlDecoder = require('urlDecoder');

    var cachedNext, _this, maxErrorDepth = 5, currentErrorDepth = 0;

    return {
        onError: function (error) {

            ++currentErrorDepth;

            if (currentErrorDepth > maxErrorDepth) {
                alert(error);
                return;
            }

            // TODO: Remove hardcoded val
            _this.load('/docs/404.md', cachedNext);
        },

        load: function (href, next) {

            _this = this;
            cachedNext = next;

            if (window && window.wikiCfg && window.wikiCfg.wikiVirtualDir) {
                href = window.wikiCfg.wikiVirtualDir + href;
            }

            var decodedUrl = urlDecoder.replaceUrlDelimiterToDefault(href);
            console.log('Loading: ', decodedUrl);

            text.get(decodedUrl, function (source) {

                next(source);

            }, this.onError);
        }
    };

});<commit_msg>handling 404s<commit_after>define(function (require) {

    var text = require('text');
    var urlDecoder = require('urlDecoder');

    var cachedNext,
        cachedHref,
        _this,
        maxErrorDepth = 5,
        currentErrorDepth = 0;

    var notFoundText = '# Sorry, 404...\n ' +
        'This page ($URL$) was not found. Please be careful with URLs. ([go to Index](/))';

    return {
        onError: function (error) {

            ++currentErrorDepth;

            if (currentErrorDepth > maxErrorDepth) {
                console.error(error);
                cachedNext(notFoundText.replace('$URL$',urlDecoder.replaceUrlDelimiterToDefault(cachedHref)));
                return;
            }

            // TODO: Remove hardcoded val
            _this.load('/docs/404.md', cachedNext);
        },

        load: function (href, next) {

            _this = this;
            cachedNext = next;
            cachedHref = href;

            if (window && window.wikiCfg && window.wikiCfg.wikiVirtualDir) {
                href = window.wikiCfg.wikiVirtualDir + href;
            }

            var decodedUrl = urlDecoder.replaceUrlDelimiterToDefault(href);
            console.log('Loading: ', decodedUrl);

            text.get(decodedUrl, function (source) {

                next(source);

            }, this.onError);
        }
    };

});<|endoftext|>


<commit_before>require('dotenv').load();
const path = require('path');
const webpack = require('webpack');
const MinifyPlugin = require('babel-minify-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

const inDevelopmentMode = (process.env.NODE_ENV === 'development');
const enableHMR = (process.env.ENABLE_WEBPACK_HMR === 'true' &&
  process.env.NODE_ENV !== 'production');

const envVars = ['NODE_ENV', 'ENABLE_WEBPACK_HMR', 'ENABLE_SERVE_DIST'];

let outputFilename = 'js/[name].min.js';

const hmrLibs = [
  'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
  'react-hot-loader/patch',
];

const entry = {
  vendor: [
    'classnames',
    'fetch-ponyfill',
    'react',
    'react-dom',
    'react-router',
    'react-router-redux',
    'redux-thunk',
    'react-async-component',
    'react-async-bootstrapper',
    'prop-types',
    'styled-components',
  ],
  app: [],
};

const babelPlugins = [
  ['styled-components', {
    ssr: true,
  }],
  'transform-react-jsx',
  'transform-runtime',
  'transform-es2015-spread',
  'transform-object-rest-spread',
];

let plugins = [
  new webpack.EnvironmentPlugin(envVars),
  new webpack.optimize.OccurrenceOrderPlugin(),
  new webpack.NoEmitOnErrorsPlugin(),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
  }),
  new MinifyPlugin(),
  new CompressionPlugin(),
];

if (enableHMR) {
  outputFilename = 'js/[name].js';

  entry.app = entry.app.concat(hmrLibs);

  babelPlugins.push('react-hot-loader/babel');

  plugins = [
    new webpack.EnvironmentPlugin(envVars),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
    }),
  ];
}

entry.app.push('./src/client/AppWrapper.js');

const clientConfig = {
  target: 'web',
  entry,
  output: {
    path: path.resolve(__dirname, './dist/assets/'),
    filename: outputFilename,
    chunkFilename: outputFilename,
    publicPath: '/assets/',
  },
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'eslint-loader',
      enforce: 'pre',
      include: [path.resolve(__dirname, './src/client')],
      options: {
        configFile: './.eslintrc.js',
        formatter: require('eslint-friendly-formatter')
      }
    }, {
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['env', {
              targets: {
                browsers: [
                  'last 2 versions',
                ],
              },
              modules: false,
            }],
            'react',
          ],
          plugins: babelPlugins,
        },
      }
    }, {
      test: /\.(png|jpg|jpeg|svg|gif|otf|ttf)$/,
      use: {
        loader: 'file-loader',
        options: {
          context: path.resolve(__dirname, 'src/client/assets'),
          name: '[path][name].[ext]',
        },
      },
    }]
  },
  plugins,
};

/*
if (inDevelopmentMode) {
  clientConfig.devtool = "eval-source-map";
}
*/

module.exports = [clientConfig];
<commit_msg>refactor config<commit_after>require('dotenv').load();
const path = require('path');
const webpack = require('webpack');
const MinifyPlugin = require('babel-minify-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const SWPrecachePlugin = require('sw-precache-webpack-plugin');

const inDevelopmentMode = (process.env.NODE_ENV === 'development');
const enableHMR = (process.env.ENABLE_WEBPACK_HMR === 'true' &&
  process.env.NODE_ENV !== 'production');

const envVars = ['NODE_ENV', 'ENABLE_WEBPACK_HMR', 'ENABLE_SERVE_DIST'];

let outputFilename = 'js/[name].min.js';

const hmrLibs = [
  'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
  'react-hot-loader/patch',
];

const entry = {
  vendor: [
    'classnames',
    'fetch-ponyfill',
    'react',
    'react-dom',
    'react-router',
    'react-router-redux',
    'redux-thunk',
    'react-async-component',
    'react-async-bootstrapper',
    'prop-types',
    'styled-components',
  ],
  app: [],
};

const babelPlugins = [
  ['styled-components', {
    ssr: true,
  }],
  'transform-react-jsx',
  'transform-runtime',
  'transform-es2015-spread',
  'transform-object-rest-spread',
];

const commonChunkPlugin = new webpack.optimize.CommonsChunkPlugin({
  name: 'vendor',
});

let plugins = [
  new webpack.EnvironmentPlugin(envVars),
  new webpack.optimize.OccurrenceOrderPlugin(),
  new webpack.NoEmitOnErrorsPlugin(),
  commonChunkPlugin,
  new MinifyPlugin(),
  new CompressionPlugin(),
];

if (enableHMR) {
  outputFilename = 'js/[name].js';

  entry.app = entry.app.concat(hmrLibs);

  babelPlugins.push('react-hot-loader/babel');

  plugins = [
    new webpack.EnvironmentPlugin(envVars),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    commonChunkPlugin,
  ];
}

entry.app.push('./src/client/AppWrapper.js');

const clientConfig = {
  target: 'web',
  entry,
  output: {
    path: path.resolve(__dirname, './dist/assets/'),
    filename: outputFilename,
    chunkFilename: outputFilename,
    publicPath: '/assets/',
  },
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'eslint-loader',
      enforce: 'pre',
      include: [path.resolve(__dirname, './src/client')],
      options: {
        configFile: './.eslintrc.js',
        formatter: require('eslint-friendly-formatter')
      }
    }, {
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['env', {
              targets: {
                browsers: [
                  'last 2 versions',
                ],
              },
              modules: false,
            }],
            'react',
          ],
          plugins: babelPlugins,
        },
      }
    }, {
      test: /\.(png|jpg|jpeg|svg|gif|otf|ttf)$/,
      use: {
        loader: 'file-loader',
        options: {
          context: path.resolve(__dirname, 'src/client/assets'),
          name: '[path][name].[ext]',
        },
      },
    }]
  },
  plugins,
};

/*
if (inDevelopmentMode) {
  clientConfig.devtool = "eval-source-map";
}
*/

module.exports = [clientConfig];
<|endoftext|>


<commit_before>// these tests run in node even though
// that's kind of a silly thing to do ¯\_(ツ)_/¯

var throttle = require('./throttle');

// TOOD: solve this like a real engineer
// cuz jasmine doesn't patch Date.now
var temporalPatchification = (function () {
  var dateConst = Date.now();
  var originalDateNow = Date.now;
  var originalJasmineTick = jasmine.Clock.tick;
  function dateNowPatchify () {
    Date.now = function () {
      return dateConst;
    };
    jasmine.Clock.tick = function (ticks) {
      dateConst += ticks;
      return originalJasmineTick(ticks);
    };
  }

  function dateNowDepatchify () {
    Date.now = originalDateNow;
    jasmine.Clock.tick = originalJasmineTick;
  }

  return function patchify (fn) {
    return function () {
      var returns;
      dateNowPatchify();
      returns = fn();
      dateNowDepatchify();
      return returns;
    };
  };
}());

describe('throttle', function() {

  var delegate;

  beforeEach(function () {
    jasmine.Clock.useMock();
    delegate = jasmine.createSpy('delegate');
  });

  describe('when the timeout is zero', function () {
    var wrapped;

    beforeEach(function () {
      wrapped = throttle(delegate, 0);
    });

    it('should return the delegate when timeout is zero', function() {
      expect(wrapped).toBe(delegate);
    });

    it('should immediately call the delegate when timeout is zero', function() {
      wrapped();
      expect(delegate).toHaveBeenCalled();
    });
  });

  describe('when the timeout is non-zero', function () {
    var wrapped;

    beforeEach(function () {
      wrapped = throttle(delegate, 100);
    });

    it('should call the delegate immediately', function() {
      wrapped();
      expect(delegate).toHaveBeenCalled();
    });

    it('should call the delegate once with the same args', function() {
      wrapped(1);
      wrapped(1);
      expect(delegate.callCount).toBe(1);
    });

    it('should call the delegate again after the timeout', temporalPatchification(function() {
      wrapped(1);
      expect(delegate.callCount).toBe(1);

      jasmine.Clock.tick(101);
      wrapped(1);
      expect(delegate.callCount).toBe(2);
    }));

    it('should call the delegate immediately with different args', function() {
      wrapped(1);
      expect(delegate).toHaveBeenCalledWith(1);
      wrapped(2);
      expect(delegate).toHaveBeenCalledWith(2);
    });
  });

});
<commit_msg>docs: typo like a real engineer<commit_after>// these tests run in node even though
// that's kind of a silly thing to do ¯\_(ツ)_/¯

var throttle = require('./throttle');

// TODO: solve this like a real engineer
// cuz jasmine doesn't patch Date.now
var temporalPatchification = (function () {
  var dateConst = Date.now();
  var originalDateNow = Date.now;
  var originalJasmineTick = jasmine.Clock.tick;
  function dateNowPatchify () {
    Date.now = function () {
      return dateConst;
    };
    jasmine.Clock.tick = function (ticks) {
      dateConst += ticks;
      return originalJasmineTick(ticks);
    };
  }

  function dateNowDepatchify () {
    Date.now = originalDateNow;
    jasmine.Clock.tick = originalJasmineTick;
  }

  return function patchify (fn) {
    return function () {
      var returns;
      dateNowPatchify();
      returns = fn();
      dateNowDepatchify();
      return returns;
    };
  };
}());

describe('throttle', function() {

  var delegate;

  beforeEach(function () {
    jasmine.Clock.useMock();
    delegate = jasmine.createSpy('delegate');
  });

  describe('when the timeout is zero', function () {
    var wrapped;

    beforeEach(function () {
      wrapped = throttle(delegate, 0);
    });

    it('should return the delegate when timeout is zero', function() {
      expect(wrapped).toBe(delegate);
    });

    it('should immediately call the delegate when timeout is zero', function() {
      wrapped();
      expect(delegate).toHaveBeenCalled();
    });
  });

  describe('when the timeout is non-zero', function () {
    var wrapped;

    beforeEach(function () {
      wrapped = throttle(delegate, 100);
    });

    it('should call the delegate immediately', function() {
      wrapped();
      expect(delegate).toHaveBeenCalled();
    });

    it('should call the delegate once with the same args', function() {
      wrapped(1);
      wrapped(1);
      expect(delegate.callCount).toBe(1);
    });

    it('should call the delegate again after the timeout', temporalPatchification(function() {
      wrapped(1);
      expect(delegate.callCount).toBe(1);

      jasmine.Clock.tick(101);
      wrapped(1);
      expect(delegate.callCount).toBe(2);
    }));

    it('should call the delegate immediately with different args', function() {
      wrapped(1);
      expect(delegate).toHaveBeenCalledWith(1);
      wrapped(2);
      expect(delegate).toHaveBeenCalledWith(2);
    });
  });

});
<|endoftext|>


<commit_before>/**
 * Webpack Configuration
 */

const webpack        = require("webpack"),
      UglifyJSPlugin = require('uglifyjs-webpack-plugin'),
      //ClosureCompilerPlugin = require('webpack-closure-compiler'),
      path           = require('path')

module.exports = {
    entry: {
        'uibuilderfe': path.join(__dirname, 'nodes', 'src', 'uibuilderfe.js')
    },
    devtool: "source-map",
    output: {
        path: path.join(__dirname, 'nodes', 'dist'),
        filename: '[name].min.js'
    },
    plugins: [
        /*
        new UglifyJSPlugin({
            sourceMap: true,
            uglifyOptions: {
                compress: {
                    keep_fnames: true
                },
                //mangle: false /*,
                mangle: {
                    keep_fnames: true,
                    reserved: ['uibuilder']
                }

            }
        })
        */
        /*
        new ClosureCompilerPlugin({
            compiler: {
              language_in: 'ECMASCRIPT6',
              language_out: 'ECMASCRIPT5',
              compilation_level: 'ADVANCED'
            },
            jsCompiler: true,
            //concurrency: 3,
        })
        // */
    ],
    resolve: {
        extensions: [‘’, ‘.js’]
    }
}
<commit_msg>Incorrectly committed a webpack config - not needed<commit_after><|endoftext|>


<commit_before>/*
These are routes as defined in https://docs.google.com/document/d/1337m6i7Y0GPULKLsKpyHR4NRzRwhoxJnAZNnDFCigkc/edit#
Each route implementes a basic parameter/payload validation and a swagger API documentation description
*/
'use strict';

const Joi = require('joi'),
  handlers = require('./controllers/handler');

const fanout = require('./controllers/fanout');

module.exports = function(server) {

  //Count activities of certain type, group by deck/slide ids and return max
  server.route({
    method: 'GET',
    path: '/activities/maxCount',
    handler: handlers.getActivitiesMaxCount,
    config: {
      validate: {
        query: {
          activity_type: [Joi.array().items(Joi.string()), Joi.string()],//an array or a single string
          all_revisions: Joi.string().description('Set to true to search for activities regardles of the content revision'),
          limit: Joi.string().description('If defined, return only this number of results'),
          content_kind: [Joi.array().items(Joi.string()), Joi.string()],//an array or a single string
        }
      },
      tags: ['api'],
      description: 'Count activities of certain type, grouped by deck/slide ids and return max results'
    }
  });

  //Get activities with content id id from database and return the entire list (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/activities/{content_kind}/{id}',
    handler: handlers.getActivities,
    config: {
      validate: {
        params: {
          content_kind: Joi.string().valid('deck', 'slide', 'user'),
          id: Joi.string().description('The id of the deck/slide/user')
        },
        query: {
          metaonly: Joi.string().description('Set to true to return only metadata without the list of activities'),
          activity_type: [Joi.array().items(Joi.string()), Joi.string()],//an array or a single string
          include_subdecks_and_slides: Joi.string().description('Set to true to include activities of subdecks and slides'),
          all_revisions: Joi.string().description('Set to true to search for activities regardles of the content revision'),
          start: Joi.string().description('If defined, return activities starting from this index'),
          limit: Joi.string().description('If defined, return only this number of activities')
        }
      },
      tags: ['api'],
      description: 'Get a list of activities'
    }
  });

  //Create new activity (by payload) and return it (...). Validate payload
  server.route({
    method: 'POST',
    path: '/activity/new',
    handler: handlers.newActivity,
    config: {
      auth: {
        mode: 'optional',
        strategy: 'jwt'
      },
      pre: [
        { method: fanout.forwardActivity },
      ],
      validate: {
        payload: Joi.object().keys({
          activity_type: Joi.string(),
          user_id: Joi.string(),
          content_id: Joi.string(),
          content_kind: Joi.string().valid('deck', 'slide', 'group'),
          content_name: Joi.string().allow(''),
          content_owner_id: Joi.string(),
          translation_info: Joi.object().keys({
            content_id: Joi.string(),
            language: Joi.string()
          }),
          share_info: Joi.object().keys({
            // postURI: Joi.string(),
            platform: Joi.string()
          }),
          comment_info: Joi.object().keys({
            comment_id: Joi.string(),
            text: Joi.string()
          }),
          use_info: Joi.object().keys({
            target_id: Joi.string(),
            target_name: Joi.string().allow('')
          }),
          exam_info: Joi.object().keys({
            score: Joi.number()
          }),
          fork_info: Joi.object().keys({
            content_id: Joi.string()
          }),
          delete_info: Joi.object().keys({
            content_id: Joi.string(),
            content_kind: Joi.string().valid('deck', 'slide', 'group'),
            content_name: Joi.string().allow('')
          }),
          move_info: Joi.object().keys({
            source_id: Joi.string(),
            target_id: Joi.string()
          }),
          react_type: Joi.string(),
          rate_type: Joi.string()
        }).requiredKeys('content_id', 'user_id', 'activity_type'),
        headers: Joi.object({
          '----jwt----': Joi.string().description('JWT header provided by /login')
        }).unknown(),
      },
      tags: ['api'],
      description: 'Create a new activity'
    }
  });

  //Create new activities (by payload) and return them (...). Validate payload
  server.route({
    method: 'POST',
    path: '/activities/new',
    handler: handlers.newActivities,
    config: {
      auth: {
        mode: 'optional',
        strategy: 'jwt'
      },
      pre: [
        { method: fanout.forwardActivity },
      ],
      validate: {
        payload: Joi.array().items(
          Joi.object().keys({
            activity_type: Joi.string(),
            user_id: Joi.string(),
            content_id: Joi.string(),
            content_kind: Joi.string().valid('deck', 'slide', 'group'),
            content_name: Joi.string().allow(''),
            content_owner_id: Joi.string(),
            translation_info: Joi.object().keys({
              content_id: Joi.string(),
              language: Joi.string()
            }),
            share_info: Joi.object().keys({
              // postURI: Joi.string(),
              platform: Joi.string()
            }),
            comment_info: Joi.object().keys({
              comment_id: Joi.string(),
              text: Joi.string()
            }),
            use_info: Joi.object().keys({
              target_id: Joi.string(),
              target_name: Joi.string()
            }),
            exam_info: Joi.object().keys({
              score: Joi.number()
            }),
            fork_info: Joi.object().keys({
              content_id: Joi.string()
            }),
            delete_info: Joi.object().keys({
              content_id: Joi.string(),
              content_kind: Joi.string().valid('deck', 'slide', 'group'),
              content_name: Joi.string().allow('')
            }),
            move_info: Joi.object().keys({
              source_id: Joi.string(),
              target_id: Joi.string()
            }),
            react_type: Joi.string(),
            rate_type: Joi.string()
          }).requiredKeys('content_id', 'user_id', 'activity_type')
        ),
        headers: Joi.object({
          '----jwt----': Joi.string().description('JWT header provided by /login')
        }).unknown(),
      },
      tags: ['api'],
      description: 'Create new activities'
    }
  });

  //Delete activity with id id (by payload). Validate payload
  server.route({
    method: 'DELETE',
    path: '/activity/delete',
    handler: handlers.deleteActivity,
    config: {
      validate: {
        payload: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Delete an activity'
    }
  });

  //Delete activities with content id id (by payload). Validate payload
  server.route({
    method: 'DELETE',
    path: '/activities/delete',
    handler: handlers.deleteActivities,
    config: {
      validate: {
        payload: {
          content_kind: Joi.string().valid('deck', 'slide', 'group'),
          content_id: Joi.string(),
          activity_type: Joi.string(),
          user_id: Joi.string(),
          all_revisions:  Joi.boolean()
        },
      },
      tags: ['api'],
      description: 'Delete all activities for the specified content, type, user'
    }
  });
};
<commit_msg>SWIK-1474 fixed routes<commit_after>/*
These are routes as defined in https://docs.google.com/document/d/1337m6i7Y0GPULKLsKpyHR4NRzRwhoxJnAZNnDFCigkc/edit#
Each route implementes a basic parameter/payload validation and a swagger API documentation description
*/
'use strict';

const Joi = require('joi'),
  handlers = require('./controllers/handler');

const fanout = require('./controllers/fanout');

module.exports = function(server) {

  //Count activities of certain type, group by deck/slide ids and return max
  server.route({
    method: 'GET',
    path: '/activities/maxCount',
    handler: handlers.getActivitiesMaxCount,
    config: {
      validate: {
        query: {
          activity_type: [Joi.array().items(Joi.string()), Joi.string()],//an array or a single string
          all_revisions: Joi.string().description('Set to true to search for activities regardles of the content revision'),
          limit: Joi.string().description('If defined, return only this number of results'),
          content_kind: [Joi.array().items(Joi.string()), Joi.string()],//an array or a single string
        }
      },
      tags: ['api'],
      description: 'Count activities of certain type, grouped by deck/slide ids and return max results'
    }
  });

  //Get activities with content id id from database and return the entire list (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/activities/{content_kind}/{id}',
    handler: handlers.getActivities,
    config: {
      validate: {
        params: {
          content_kind: Joi.string().valid('deck', 'slide', 'user'),
          id: Joi.string().description('The id of the deck/slide/user')
        },
        query: {
          metaonly: Joi.string().description('Set to true to return only metadata without the list of activities'),
          activity_type: [Joi.array().items(Joi.string()), Joi.string()],//an array or a single string
          include_subdecks_and_slides: Joi.string().description('Set to true to include activities of subdecks and slides'),
          all_revisions: Joi.string().description('Set to true to search for activities regardles of the content revision'),
          start: Joi.string().description('If defined, return activities starting from this index'),
          limit: Joi.string().description('If defined, return only this number of activities')
        }
      },
      tags: ['api'],
      description: 'Get a list of activities'
    }
  });

  //Create new activity (by payload) and return it (...). Validate payload
  server.route({
    method: 'POST',
    path: '/activity/new',
    handler: handlers.newActivity,
    config: {
      auth: {
        mode: 'optional',
        strategy: 'jwt'
      },
      pre: [
        { method: fanout.forwardActivity },
      ],
      validate: {
        payload: Joi.object().keys({
          activity_type: Joi.string(),
          user_id: Joi.string(),
          content_id: Joi.string(),
          content_kind: Joi.string().valid('deck', 'slide', 'group'),
          content_name: Joi.string().allow(''),
          content_owner_id: Joi.string(),
          translation_info: Joi.object().keys({
            content_id: Joi.string(),
            language: Joi.string()
          }),
          share_info: Joi.object().keys({
            // postURI: Joi.string(),
            platform: Joi.string()
          }),
          comment_info: Joi.object().keys({
            comment_id: Joi.string(),
            text: Joi.string(),
            parent_comment_owner_id: Joi.string()
          }),
          use_info: Joi.object().keys({
            target_id: Joi.string(),
            target_name: Joi.string().allow('')
          }),
          exam_info: Joi.object().keys({
            score: Joi.number()
          }),
          fork_info: Joi.object().keys({
            content_id: Joi.string()
          }),
          delete_info: Joi.object().keys({
            content_id: Joi.string(),
            content_kind: Joi.string().valid('deck', 'slide', 'group'),
            content_name: Joi.string().allow('')
          }),
          move_info: Joi.object().keys({
            source_id: Joi.string(),
            target_id: Joi.string()
          }),
          react_type: Joi.string(),
          rate_type: Joi.string()
        }).requiredKeys('content_id', 'user_id', 'activity_type'),
        headers: Joi.object({
          '----jwt----': Joi.string().description('JWT header provided by /login')
        }).unknown(),
      },
      tags: ['api'],
      description: 'Create a new activity'
    }
  });

  //Create new activities (by payload) and return them (...). Validate payload
  server.route({
    method: 'POST',
    path: '/activities/new',
    handler: handlers.newActivities,
    config: {
      auth: {
        mode: 'optional',
        strategy: 'jwt'
      },
      pre: [
        { method: fanout.forwardActivity },
      ],
      validate: {
        payload: Joi.array().items(
          Joi.object().keys({
            activity_type: Joi.string(),
            user_id: Joi.string(),
            content_id: Joi.string(),
            content_kind: Joi.string().valid('deck', 'slide', 'group'),
            content_name: Joi.string().allow(''),
            content_owner_id: Joi.string(),
            translation_info: Joi.object().keys({
              content_id: Joi.string(),
              language: Joi.string()
            }),
            share_info: Joi.object().keys({
              // postURI: Joi.string(),
              platform: Joi.string()
            }),
            comment_info: Joi.object().keys({
              comment_id: Joi.string(),
              text: Joi.string(),
              parent_comment_owner_id: Joi.string()
            }),
            use_info: Joi.object().keys({
              target_id: Joi.string(),
              target_name: Joi.string()
            }),
            exam_info: Joi.object().keys({
              score: Joi.number()
            }),
            fork_info: Joi.object().keys({
              content_id: Joi.string()
            }),
            delete_info: Joi.object().keys({
              content_id: Joi.string(),
              content_kind: Joi.string().valid('deck', 'slide', 'group'),
              content_name: Joi.string().allow('')
            }),
            move_info: Joi.object().keys({
              source_id: Joi.string(),
              target_id: Joi.string()
            }),
            react_type: Joi.string(),
            rate_type: Joi.string()
          }).requiredKeys('content_id', 'user_id', 'activity_type')
        ),
        headers: Joi.object({
          '----jwt----': Joi.string().description('JWT header provided by /login')
        }).unknown(),
      },
      tags: ['api'],
      description: 'Create new activities'
    }
  });

  //Delete activity with id id (by payload). Validate payload
  server.route({
    method: 'DELETE',
    path: '/activity/delete',
    handler: handlers.deleteActivity,
    config: {
      validate: {
        payload: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Delete an activity'
    }
  });

  //Delete activities with content id id (by payload). Validate payload
  server.route({
    method: 'DELETE',
    path: '/activities/delete',
    handler: handlers.deleteActivities,
    config: {
      validate: {
        payload: {
          content_kind: Joi.string().valid('deck', 'slide', 'group'),
          content_id: Joi.string(),
          activity_type: Joi.string(),
          user_id: Joi.string(),
          all_revisions:  Joi.boolean()
        },
      },
      tags: ['api'],
      description: 'Delete all activities for the specified content, type, user'
    }
  });
};
<|endoftext|>