<commit_before>// -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';

var trexControllers = angular.module('trex.controllers', []);

trexControllers.controller('ProjectListCtrl', ['$scope', 'Project',
    function($scope, Project) {
        $scope.projects_loading = true;

        $scope.projects = Project.query();

        $scope.order = "name";
        $scope.orderreverse = false;

        $scope.$watch('projects.$resolved', function(value) {
            $scope.projects_loading = !value;
        });

        $scope.setOrder = function(name) {
            if (name == $scope.order) {
                $scope.orderreverse = !$scope.orderreverse;
            }
            $scope.order = name;
        };
    }
]);

trexControllers.controller('ProjectCreateCtrl', ['$scope', '$location',
        '$timeout', 'Project', function($scope, $location, $timeout, Project) {

        $scope.succes = false;
        $scope.error = false;

        $scope.successCreate = function(value, headers) {
            $scope.success = true;
            $timeout(function() {
                $location.path('/projects/' + value.id);
            }, 2000);
        };

        $scope.failCreate = function(response) {
            console.error(response);
            $scope.error = true;
            $("#error-frame").html(response.data);
        };

        $scope.createProject = function() {
            $scope.succes = false;
            $scope.error = false;

            var project = new Project();

            project.name = $scope.name;
            project.description = $scope.description;
            project.active = true;

            Project.save(project, $scope.successCreate, $scope.failCreate);
        };

    }
]);

trexControllers.controller('ProjectDetailCtrl',
    ['$scope', '$routeParams', 'Project', '$http', 'Conf', 'Utils',
    function($scope, $routeParams, Project, $http, Conf, Utils) {
        $scope.alerts = [];

        $scope.addAlert = function(type, msg) {
            $scope.alerts.push({type: type, msg: msg });
        };

        $scope.closeAlert = function(index) {
            $scope.alerts.splice(index, 1);
        };

        $scope.project = Project.get({projectId: $routeParams.id});
        $scope.entries = Project.entries({projectId: $routeParams.id});

        $scope.search = {};

        $scope.search.entries_tags = [];
        $scope.search.entries_user_abbr = [];

        $scope.order = "id";
        $scope.orderreverse = false;

        $scope.entries_chart = {};
        $scope.entries_chart.data = [];
        $scope.entries_chart.types = ["Line", "Bar", "Radar"];
        $scope.entries_chart.current_type = 0;
        $scope.entries_chart.series = ["Duration"];
        $scope.entries_chart.labels = [];
        $scope.entries_chart.loaded = false;
        $scope.entries_chart.type = "Line";
        $scope.entries_chart.options = {
            animation: false,
            pointHitDetectionRadius: 5
        };

        $scope.setOrder = function(name) {
            if (name == $scope.order) {
                $scope.orderreverse = !$scope.orderreverse;
            }
            $scope.order = name;
        };

        $scope.tagList = function(tags, attr) {
            var search = "";
            angular.forEach(tags, function(value, key) {
                search += value[attr] + ',';

            });
            return search;
        };

        $scope.searchEntries = function() {
            $scope.entries = Project.entries(
                    {
                        projectId: $routeParams.id,
                        from_date: $scope.dateToString(
                            $scope.search.entries_from_date),
                        to_date: $scope.dateToString(
                            $scope.search.entries_to_date),
                        state: $scope.search.entries_state,
                        user_abbr: $scope.tagList(
                            $scope.search.entries_user_abbr, "user_abbr"),
                        tag: $scope.tagList($scope.search.entries_tags, "name"),
                        tag_like: $scope.search.entries_tags_like,
                        description: $scope.search.entries_description,
                        workpackage_like: $scope.search.entries_workpackage
                    }
                );
            $scope.entries_loading = true;

            if ($scope.entries_chart.loaded) {
                $scope.loadChartData();
            }
        };

        $scope.addSearchTag = function(tag) {
            for (var i = 0; i < $scope.search.entries_tags.length; i++) {
                var value = $scope.search.entries_tags[i];
                if (value.name == tag) {
                    return;
                }
            }
            $scope.search.entries_tags.push({'name': tag});
        };

        $scope.addSearchUser = function(user) {
            for (var i = 0; i < $scope.search.entries_user_abbr.length; i++) {
                var value = $scope.search.entries_user_abbr[i];
                if (value.user_abbr == user.user_abbr) {
                    return;
                }
            }
            $scope.search.entries_user_abbr.push(user);
        };

        $scope.completeTag = function(query) {
            return Project.tags(
                    {
                        projectId: $routeParams.id,
                        name_like: query
                    }).$promise;
        };

        $scope.completeUser = function(query) {
            return Project.users(
                    {
                        projectId: $routeParams.id,
                        user_abbr_like: query
                    }).$promise;
        };

        $scope.zeiterfassung_files = [];

        $scope.$on("fileSelected", function(event, args) {
            $scope.$apply(function() {
                $scope.zeiterfassung_files.push(args.file);
            });
        });

        $scope.uploadFiles = function() {
             var fileReader = new FileReader();
             fileReader.onload = function(e) {
                 console.log(e.target.result);
                 $http({
                     method: 'POST',
                     headers: { 'Content-Type': 'text/plain'},
                     url: Conf.apiBase + '/projects/' + $routeParams.id +
                     '/zeiterfassung/',
                     data: e.target.result
                 }).
                 success(function(data, status, headers, config) {
                     $scope.zeiterfassung_files = [];
                     $scope.addAlert("success",
                         'Upload successfull. ' + data['written'].length +
                         ' new entries loaded. ' + data['skipped'].length +
                         ' entries skipped.');
                     $scope.searchEntries();
                 }).
                 error(function(data, status, headers, config) {
                     $scope.addAlert("error", "Upload failed");
                 });
             };
             for (var i = 0; i < $scope.zeiterfassung_files.length; i++) {
                fileReader.readAsBinaryString($scope.zeiterfassung_files[i]);
             }

        };

        $scope.openFromDatepicker = function($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.opened_from = true;
        };

        $scope.openToDatepicker = function($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.opened_to = true;
        };

        $scope.dateToString = Utils.dateToString
        $scope.loadChartData = function() {
            Project.entries_sums(
                {
                    projectId: $routeParams.id,
                    from_date: $scope.dateToString(
                        $scope.search.entries_from_date),
                    to_date: $scope.dateToString(
                        $scope.search.entries_to_date),
                    state: $scope.search.entries_state,
                    user_abbr: $scope.tagList(
                        $scope.search.entries_user_abbr, "user_abbr"),
                    tag: $scope.tagList($scope.search.entries_tags, "name"),
                    tag_like: $scope.search.entries_tags_like,
                    description: $scope.search.entries_description,
                    workpackage_like: $scope.search.entries_workpackage
                }
            ).$promise.then(function(data) {

                var chart_data = [];
                $scope.entries_chart.data = [chart_data];
                $scope.entries_chart.labels = [];
                $scope.entries_chart.loaded = true;

                var workpackage_sums = data["workpackage_sums"];
                for (var i = 0; i < workpackage_sums.length; i++) {
                    var sum = workpackage_sums[i];
                    chart_data.push(sum["duration"]);
                    $scope.entries_chart.labels.push(sum["name"]);
                }
            });

        };

        $scope.entriesChartToggle = function() {
            $scope.entries_chart.current_type += 1;
            if ($scope.entries_chart.current_type >=
                    $scope.entries_chart.types.length) {
                        $scope.entries_chart.current_type = 0;
            }
            $scope.entries_chart.type =
               $scope.entries_chart.types[$scope.entries_chart.current_type];
        };

    }
]);

trexControllers.controller('EntryDetailCtrl',
    ['$scope', '$routeParams', 'Entry',
    function($scope, $routeParams, Entry) {
        $scope.entry = Entry.get({entryId: $routeParams.id});

        $scope.order = "id";
        $scope.orderreverse = false;

        $scope.setOrder = function(name) {
            if (name == $scope.order) {
                $scope.orderreverse = !$scope.orderreverse;
            }
            $scope.order = name;
        };
    }
]);
<commit_msg>Remove obsolete entries_loading<commit_after>// -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';

var trexControllers = angular.module('trex.controllers', []);

trexControllers.controller('ProjectListCtrl', ['$scope', 'Project',
    function($scope, Project) {
        $scope.projects_loading = true;

        $scope.projects = Project.query();

        $scope.order = "name";
        $scope.orderreverse = false;

        $scope.$watch('projects.$resolved', function(value) {
            $scope.projects_loading = !value;
        });

        $scope.setOrder = function(name) {
            if (name == $scope.order) {
                $scope.orderreverse = !$scope.orderreverse;
            }
            $scope.order = name;
        };
    }
]);

trexControllers.controller('ProjectCreateCtrl', ['$scope', '$location',
        '$timeout', 'Project', function($scope, $location, $timeout, Project) {

        $scope.succes = false;
        $scope.error = false;

        $scope.successCreate = function(value, headers) {
            $scope.success = true;
            $timeout(function() {
                $location.path('/projects/' + value.id);
            }, 2000);
        };

        $scope.failCreate = function(response) {
            console.error(response);
            $scope.error = true;
            $("#error-frame").html(response.data);
        };

        $scope.createProject = function() {
            $scope.succes = false;
            $scope.error = false;

            var project = new Project();

            project.name = $scope.name;
            project.description = $scope.description;
            project.active = true;

            Project.save(project, $scope.successCreate, $scope.failCreate);
        };

    }
]);

trexControllers.controller('ProjectDetailCtrl',
    ['$scope', '$routeParams', 'Project', '$http', 'Conf', 'Utils',
    function($scope, $routeParams, Project, $http, Conf, Utils) {
        $scope.alerts = [];

        $scope.addAlert = function(type, msg) {
            $scope.alerts.push({type: type, msg: msg });
        };

        $scope.closeAlert = function(index) {
            $scope.alerts.splice(index, 1);
        };

        $scope.project = Project.get({projectId: $routeParams.id});
        $scope.entries = Project.entries({projectId: $routeParams.id});

        $scope.search = {};

        $scope.search.entries_tags = [];
        $scope.search.entries_user_abbr = [];

        $scope.order = "id";
        $scope.orderreverse = false;

        $scope.entries_chart = {};
        $scope.entries_chart.data = [];
        $scope.entries_chart.types = ["Line", "Bar", "Radar"];
        $scope.entries_chart.current_type = 0;
        $scope.entries_chart.series = ["Duration"];
        $scope.entries_chart.labels = [];
        $scope.entries_chart.loaded = false;
        $scope.entries_chart.type = "Line";
        $scope.entries_chart.options = {
            animation: false,
            pointHitDetectionRadius: 5
        };

        $scope.setOrder = function(name) {
            if (name == $scope.order) {
                $scope.orderreverse = !$scope.orderreverse;
            }
            $scope.order = name;
        };

        $scope.tagList = function(tags, attr) {
            var search = "";
            angular.forEach(tags, function(value, key) {
                search += value[attr] + ',';

            });
            return search;
        };

        $scope.searchEntries = function() {
            $scope.entries = Project.entries(
                    {
                        projectId: $routeParams.id,
                        from_date: $scope.dateToString(
                            $scope.search.entries_from_date),
                        to_date: $scope.dateToString(
                            $scope.search.entries_to_date),
                        state: $scope.search.entries_state,
                        user_abbr: $scope.tagList(
                            $scope.search.entries_user_abbr, "user_abbr"),
                        tag: $scope.tagList($scope.search.entries_tags, "name"),
                        tag_like: $scope.search.entries_tags_like,
                        description: $scope.search.entries_description,
                        workpackage_like: $scope.search.entries_workpackage
                    }
                );

            if ($scope.entries_chart.loaded) {
                $scope.loadChartData();
            }
        };

        $scope.addSearchTag = function(tag) {
            for (var i = 0; i < $scope.search.entries_tags.length; i++) {
                var value = $scope.search.entries_tags[i];
                if (value.name == tag) {
                    return;
                }
            }
            $scope.search.entries_tags.push({'name': tag});
        };

        $scope.addSearchUser = function(user) {
            for (var i = 0; i < $scope.search.entries_user_abbr.length; i++) {
                var value = $scope.search.entries_user_abbr[i];
                if (value.user_abbr == user.user_abbr) {
                    return;
                }
            }
            $scope.search.entries_user_abbr.push(user);
        };

        $scope.completeTag = function(query) {
            return Project.tags(
                    {
                        projectId: $routeParams.id,
                        name_like: query
                    }).$promise;
        };

        $scope.completeUser = function(query) {
            return Project.users(
                    {
                        projectId: $routeParams.id,
                        user_abbr_like: query
                    }).$promise;
        };

        $scope.zeiterfassung_files = [];

        $scope.$on("fileSelected", function(event, args) {
            $scope.$apply(function() {
                $scope.zeiterfassung_files.push(args.file);
            });
        });

        $scope.uploadFiles = function() {
             var fileReader = new FileReader();
             fileReader.onload = function(e) {
                 console.log(e.target.result);
                 $http({
                     method: 'POST',
                     headers: { 'Content-Type': 'text/plain'},
                     url: Conf.apiBase + '/projects/' + $routeParams.id +
                     '/zeiterfassung/',
                     data: e.target.result
                 }).
                 success(function(data, status, headers, config) {
                     $scope.zeiterfassung_files = [];
                     $scope.addAlert("success",
                         'Upload successfull. ' + data['written'].length +
                         ' new entries loaded. ' + data['skipped'].length +
                         ' entries skipped.');
                     $scope.searchEntries();
                 }).
                 error(function(data, status, headers, config) {
                     $scope.addAlert("error", "Upload failed");
                 });
             };
             for (var i = 0; i < $scope.zeiterfassung_files.length; i++) {
                fileReader.readAsBinaryString($scope.zeiterfassung_files[i]);
             }

        };

        $scope.openFromDatepicker = function($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.opened_from = true;
        };

        $scope.openToDatepicker = function($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.opened_to = true;
        };

        $scope.dateToString = Utils.dateToString
        $scope.loadChartData = function() {
            Project.entries_sums(
                {
                    projectId: $routeParams.id,
                    from_date: $scope.dateToString(
                        $scope.search.entries_from_date),
                    to_date: $scope.dateToString(
                        $scope.search.entries_to_date),
                    state: $scope.search.entries_state,
                    user_abbr: $scope.tagList(
                        $scope.search.entries_user_abbr, "user_abbr"),
                    tag: $scope.tagList($scope.search.entries_tags, "name"),
                    tag_like: $scope.search.entries_tags_like,
                    description: $scope.search.entries_description,
                    workpackage_like: $scope.search.entries_workpackage
                }
            ).$promise.then(function(data) {

                var chart_data = [];
                $scope.entries_chart.data = [chart_data];
                $scope.entries_chart.labels = [];
                $scope.entries_chart.loaded = true;

                var workpackage_sums = data["workpackage_sums"];
                for (var i = 0; i < workpackage_sums.length; i++) {
                    var sum = workpackage_sums[i];
                    chart_data.push(sum["duration"]);
                    $scope.entries_chart.labels.push(sum["name"]);
                }
            });

        };

        $scope.entriesChartToggle = function() {
            $scope.entries_chart.current_type += 1;
            if ($scope.entries_chart.current_type >=
                    $scope.entries_chart.types.length) {
                        $scope.entries_chart.current_type = 0;
            }
            $scope.entries_chart.type =
               $scope.entries_chart.types[$scope.entries_chart.current_type];
        };

    }
]);

trexControllers.controller('EntryDetailCtrl',
    ['$scope', '$routeParams', 'Entry',
    function($scope, $routeParams, Entry) {
        $scope.entry = Entry.get({entryId: $routeParams.id});

        $scope.order = "id";
        $scope.orderreverse = false;

        $scope.setOrder = function(name) {
            if (name == $scope.order) {
                $scope.orderreverse = !$scope.orderreverse;
            }
            $scope.order = name;
        };
    }
]);
<|endoftext|>


<commit_before>/**
 * Static class that will be imported
 * by users to register routes to for
 * their web app.
 */
class Route {

    /**
     * Contructor method
     * @param {Express} express - Instance of Express.js
     */
    constructor(express) {
        this.projectPath = process.cwd();
        this.controllerPath = 'app/controllers';
        this.express = express;
        this.controllers = [];
        this.controllerMapping = {};
    }

    /**
     * Our HTTP GET method for setting up a new routes
     * linked to a controller
     * @param {String} path - Url path of the webapp to point to
     * @param {String} controllerString - String containing controller and
     * action  seperated by an @;
     */
    get(path, controllerString) {
        this.express.get(path, this.getControllerMethod(controllerString));
    }

    /**
     * Our HTTP PUT method for setting up a new routes
     * @param {String} path - url path of the webapp to point to
     * @param {String} controllerString
     */
    put(path, controllerString) {
        this.express.put(path, this.getControllerMethod(controllerString));
    }

    /**
     * Our HTTP POST method for setting up a new routes
     * @param {String} path - url path of the webapp to point to
     * @param {String} controllerString
     */
    post(path, controllerString) {
        this.express.post(path, this.getControllerMethod(controllerString));
    }

    /**
     * Our HTTP DELETE method for setting up a new routes
     * @param {String} path - url path of the webapp to point to
     * @param {String} controllerString
     */
    delete(path, controllerString) {
        this.express.delete(path, this.getControllerMethod(controllerString));
    }

    /**
     * Method for grabbing the method mentioned in the
     * controller string and caching existing controllers
     * @param {String} controllerString
     * @return {Function} - The method from the controller
     */
    getControllerMethod(controllerString) {
        let controllerConfig = this.parseControllerString(controllerString);
        let path = controllerConfig.path;
        let method = controllerConfig.method;
        let arrayIndex = this.controllerMapping[path];

        if(arrayIndex != undefined) {
            return this.controllers[arrayIndex][method];
        }else {
            this.controllerMapping[path] = this.controllers.length;
            let Controller = require(path);
            this.controllers.push(new Controller);
            return this.controllers[this.controllers.length-1][method];
        }
    }

    /**
     * Method to parse out the controller string
     * in to an object with path and method
     * string property
     * @param {String} controllerString - The string passed in to the route
     * class containing the controller and method.
     * @return {Object} - Object with path and method string properties;
     */
    parseControllerString(controllerString) {
        let stringArgs = controllerString.split('@');

        let controller = {
            path: this.projectPath+'/'+this.controllerPath+'/'+stringArgs[0],
            method: stringArgs[1],
        };

        return controller;
    }
}

module.exports = Route;
<commit_msg>Whoops, missed a class; refactored that too, mostly for JSDOC/code style updates for now<commit_after>/**
 * Static class that will be imported by users to register routes to for their
 * web app.
 */
class Route {

    /**
     * Contructor method
     *
     * @param {Express} express - Instance of Express.js
     */
    constructor(express) {
        this.projectPath = process.cwd();
        this.controllerPath = 'app/controllers';
        this.express = express;
        this.controllers = [];
        this.controllerMapping = {};
    }

    /**
     * Our HTTP GET method for setting up a new routes linked to a controller
     *
     * @param {String} path - Url path of the webapp to point to
     *
     * @param {String} controllerString - String containing controller and
     * action seperated by an @
     */
    get(path, controllerString) {
        this.express.get(path, this.getControllerMethod(controllerString));
    }

    /**
     * Our HTTP PUT method for setting up a new routes
     *
     * @param {String} path - url path of the webapp to point to
     *
     * @param {String} controllerString
     */
    put(path, controllerString) {
        this.express.put(path, this.getControllerMethod(controllerString));
    }

    /**
     * Our HTTP POST method for setting up a new routes
     *
     * @param {String} path - url path of the webapp to point to
     *
     * @param {String} controllerString
     */
    post(path, controllerString) {
        this.express.post(path, this.getControllerMethod(controllerString));
    }

    /**
     * Our HTTP DELETE method for setting up a new routes
     *
     * @param {String} path - url path of the webapp to point to
     *
     * @param {String} controllerString
     */
    delete(path, controllerString) {
        this.express.delete(path, this.getControllerMethod(controllerString));
    }

    /**
     * Method for grabbing the method mentioned in the controller string and
     * caching existing controllers
     *
     * @param {String} controllerString
     *
     * @return {Function} - The method from the controller
     */
    getControllerMethod(controllerString) {
        let controllerConfig = this.parseControllerString(controllerString);
        let path = controllerConfig.path;
        let method = controllerConfig.method;
        let arrayIndex = this.controllerMapping[path];

        if(arrayIndex != undefined) {
            return this.controllers[arrayIndex][method];
        }else {
            this.controllerMapping[path] = this.controllers.length;
            let Controller = require(path);
            this.controllers.push(new Controller);
            return this.controllers[this.controllers.length-1][method];
        }
    }

    /**
     * Method to parse out the controller string in to an object with path and
     * method string property
     * @param {String} controllerString - The string passed in to the route
     * class containing the controller and method.
     *
     * @return {Object} - Object with path and method string properties
     */
    parseControllerString(controllerString) {
        let stringArgs = controllerString.split('@');

        let controller = {
            path: this.projectPath+'/'+this.controllerPath+'/'+stringArgs[0],
            method: stringArgs[1],
        };

        return controller;
    }
}

module.exports = Route;
<|endoftext|>


<commit_before>'use strict';

var config       = require('../config');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var gutil        = require('gulp-util');
var source       = require('vinyl-source-stream');
var sourcemaps   = require('gulp-sourcemaps');
var buffer       = require('vinyl-buffer');
var streamify    = require('gulp-streamify');
var watchify     = require('watchify');
var browserify   = require('browserify');
var babelify     = require('babelify');
var uglify       = require('gulp-uglify');
var handleErrors = require('../util/handleErrors');
var browserSync  = require('browser-sync');
var debowerify   = require('debowerify');
var ngAnnotate   = require('browserify-ngannotate');

// Based on: http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/
function buildScript(file) {

  var bundler = browserify({
    entries: config.browserify.entries,
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: !global.isProd
  });

  if ( !global.isProd ) {
    bundler = watchify(bundler);
    bundler.on('update', function() {
      rebundle();
    });
  }

  var transforms = [
    babelify,
    debowerify,
    ngAnnotate,
    'brfs',
    'bulkify'
  ];

  transforms.forEach(function(transform) {
    bundler.transform(transform);
  });

  function rebundle() {
    var stream = bundler.bundle();
    var createSourcemap = global.isProd && config.browserify.prodSourcemap;

    gutil.log('Rebundle...');

    return stream.on('error', handleErrors)
      .pipe(source(file))
      .pipe(gulpif(createSourcemap, buffer()))
      .pipe(gulpif(createSourcemap, sourcemaps.init()))
      .pipe(gulpif(global.isProd, streamify(uglify({
        compress: { drop_console: true }
      }))))
      .pipe(gulpif(createSourcemap, sourcemaps.write('./')))
      .pipe(gulp.dest(config.scripts.dest))
      .pipe(browserSync.stream({ once: true }));
  }

  return rebundle();

}

gulp.task('browserify', function() {

  return buildScript('main.js');

});
<commit_msg>Added transform options to browserify gulp task<commit_after>'use strict';

var config       = require('../config');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var gutil        = require('gulp-util');
var source       = require('vinyl-source-stream');
var sourcemaps   = require('gulp-sourcemaps');
var buffer       = require('vinyl-buffer');
var streamify    = require('gulp-streamify');
var watchify     = require('watchify');
var browserify   = require('browserify');
var babelify     = require('babelify');
var uglify       = require('gulp-uglify');
var handleErrors = require('../util/handleErrors');
var browserSync  = require('browser-sync');
var debowerify   = require('debowerify');
var ngAnnotate   = require('browserify-ngannotate');

// Based on: http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/
function buildScript(file) {

  var bundler = browserify({
    entries: config.browserify.entries,
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: !global.isProd
  });

  if ( !global.isProd ) {
    bundler = watchify(bundler);
    bundler.on('update', function() {
      rebundle();
    });
  }

  var transforms = [
    { 'name':babelify, 'options': {}},
    { 'name':debowerify, 'options': {}},
    { 'name':ngAnnotate, 'options': {}},
    { 'name':'brfs', 'options': {}},
    { 'name':'bulkify', 'options': {}}
  ];

  transforms.forEach(function(transform) {
    bundler.transform(transform.name, transform.options);
  });

  function rebundle() {
    var stream = bundler.bundle();
    var createSourcemap = global.isProd && config.browserify.prodSourcemap;

    gutil.log('Rebundle...');

    return stream.on('error', handleErrors)
      .pipe(source(file))
      .pipe(gulpif(createSourcemap, buffer()))
      .pipe(gulpif(createSourcemap, sourcemaps.init()))
      .pipe(gulpif(global.isProd, streamify(uglify({
        compress: { drop_console: true }
      }))))
      .pipe(gulpif(createSourcemap, sourcemaps.write('./')))
      .pipe(gulp.dest(config.scripts.dest))
      .pipe(browserSync.stream({ once: true }));
  }

  return rebundle();

}

gulp.task('browserify', function() {

  return buildScript('main.js');

});
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean, number } from '@storybook/addon-knobs';
import BigNumber from 'bignumber.js';
import StoryDecorator from '../_support/StoryDecorator';
import StoryProvider from '../_support/StoryProvider';
import VotingRegistrationStepsChooseWallet from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsChooseWallet';
import VotingRegistrationStepsRegister from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsRegister';
import VotingRegistrationStepsConfirm from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsConfirm';
import VotingRegistrationStepsEnterPinCode from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsEnterPinCode';
import VotingRegistrationStepsQrCode from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsQrCode';
import VotingInfo from '../../../source/renderer/app/components/voting/voting-info/VotingInfo';
import { VotingFooterLinks } from '../../../source/renderer/app/components/voting/VotingFooterLinks';
import {
  LANGUAGE_OPTIONS,
  DATE_ENGLISH_OPTIONS,
  TIME_OPTIONS,
} from '../../../source/renderer/app/config/profileConfig';
import {
  VOTING_REGISTRATION_MIN_TRANSACTION_CONFIRMATIONS,
  VOTING_REGISTRATION_MIN_WALLET_FUNDS,
} from '../../../source/renderer/app/config/votingConfig';
import {
  generateHash,
  generatePolicyIdHash,
  generateWallet,
} from '../_support/utils';
import { HwDeviceStatuses } from '../../../source/renderer/app/domains/Wallet';
import VerticalFlexContainer from '../../../source/renderer/app/components/layout/VerticalFlexContainer';

const assets = {
  available: [
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
  ],
  total: [
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
  ],
};

const WALLETS = [
  generateWallet('Wallet 1', '100000000000000', assets, 0),
  generateWallet(
    'Wallet 2',
    '500000000',
    assets,
    0,
    undefined,
    true,
    'syncing'
  ),
];

const stepsList = ['Wallet', 'Sign', 'Confirm', 'PIN code', 'QR code'];

storiesOf('Voting|Voting Registration Wizard', module)
  .addDecorator((story) => (
    <StoryProvider>
      <StoryDecorator>{story()}</StoryDecorator>
    </StoryProvider>
  ))
  .addDecorator(withKnobs)

  // ====== Stories ======

  .add('Voting Registration - Step 1', () => (
    <VotingRegistrationStepsChooseWallet
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={1}
      numberOfStakePools={number('numberOfStakePools', 100)}
      onSelectWallet={action('onSelectWallet')}
      wallets={WALLETS}
      minVotingRegistrationFunds={VOTING_REGISTRATION_MIN_WALLET_FUNDS}
      selectedWalletId={WALLETS[0].id}
      isWalletAcceptable={action('isWalletAcceptable')}
      getStakePoolById={action('getStakePoolById')}
    />
  ))

  .add('Voting Registration - Step 2', () => (
    <VotingRegistrationStepsRegister
      onClose={action('onClose')}
      onBack={action('onBack')}
      stepsList={stepsList}
      activeStep={2}
      transactionFee={
        new BigNumber(
          number('transactionFee', 0.3, {
            min: 0,
            max: 1000000,
          })
        )
      }
      isSubmitting={boolean('isSubmitting')}
      onConfirm={action('onConfirm')}
      onExternalLinkClick={action('onExternalLinkClick')}
      hwDeviceStatus={HwDeviceStatuses.CONNECTING}
      isHardwareWallet={boolean('isHardwareWallet', false)}
      isTrezor={boolean('isTrezor', false)}
      selectedWallet={WALLETS[0]}
    />
  ))

  .add('Voting Registration - Step 3', () => (
    <VotingRegistrationStepsConfirm
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={3}
      isTransactionPending={boolean('isTransactionPending', true)}
      isTransactionConfirmed={boolean('isTransactionConfirmed', false)}
      transactionConfirmations={number('transactionConfirmations', 0, {
        range: true,
        max: VOTING_REGISTRATION_MIN_TRANSACTION_CONFIRMATIONS,
      })}
      onConfirm={action('onConfirm')}
      onRestart={action('onRestart')}
      transactionError={boolean('transactionError', false)}
    />
  ))

  .add('Voting Registration - Step 4', () => (
    <VotingRegistrationStepsEnterPinCode
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={4}
      onSetPinCode={action('onSetPinCode')}
    />
  ))

  .add('Voting Registration - Step 5', () => (
    <VotingRegistrationStepsQrCode
      onClose={action('onClose')}
      onDownloadPDF={action('onDownloadPDF')}
      stepsList={stepsList}
      activeStep={2}
      qrCode="djkhfkwdjhfkwdhfkwjdhfkwdhf9wdyf9wdh9u3h03hd0f3hd0h30hf30dhf03dhf03dhf03dhf03dhf0u3dhf0u3dhf0u3dfh30uhfd30uh"
    />
  ));

storiesOf('Voting|Voting Info', module)
  .addDecorator((story) => <StoryDecorator>{story()}</StoryDecorator>)
  .addDecorator(withKnobs)

  // ====== Stories ======

  .add('Voting Info', () => (
    <VerticalFlexContainer>
      <VotingInfo
        currentLocale={LANGUAGE_OPTIONS[0].value}
        currentDateFormat={DATE_ENGLISH_OPTIONS[0].value}
        currentTimeFormat={TIME_OPTIONS[0].value}
        onRegisterToVoteClick={action('onRegisterToVoteClick')}
        onExternalLinkClick={action('onExternalLinkClick')}
      />
      <VotingFooterLinks />
    </VerticalFlexContainer>
  ));
<commit_msg>[DDW-796] Update story<commit_after>// @flow
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean, number, select } from '@storybook/addon-knobs';
import BigNumber from 'bignumber.js';
import StoryDecorator from '../_support/StoryDecorator';
import StoryProvider from '../_support/StoryProvider';
import VotingRegistrationStepsChooseWallet from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsChooseWallet';
import VotingRegistrationStepsRegister from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsRegister';
import VotingRegistrationStepsConfirm from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsConfirm';
import VotingRegistrationStepsEnterPinCode from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsEnterPinCode';
import VotingRegistrationStepsQrCode from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsQrCode';
import VotingInfo from '../../../source/renderer/app/components/voting/voting-info/VotingInfo';
import { FundPhases } from '../../../source/renderer/app/stores/VotingStore';
import { VotingFooterLinks } from '../../../source/renderer/app/components/voting/VotingFooterLinks';
import {
  LANGUAGE_OPTIONS,
  DATE_ENGLISH_OPTIONS,
  TIME_OPTIONS,
} from '../../../source/renderer/app/config/profileConfig';
import {
  VOTING_REGISTRATION_MIN_TRANSACTION_CONFIRMATIONS,
  VOTING_REGISTRATION_MIN_WALLET_FUNDS,
} from '../../../source/renderer/app/config/votingConfig';
import {
  generateHash,
  generatePolicyIdHash,
  generateWallet,
} from '../_support/utils';
import { HwDeviceStatuses } from '../../../source/renderer/app/domains/Wallet';
import VerticalFlexContainer from '../../../source/renderer/app/components/layout/VerticalFlexContainer';

const assets = {
  available: [
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
  ],
  total: [
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
  ],
};

const WALLETS = [
  generateWallet('Wallet 1', '100000000000000', assets, 0),
  generateWallet(
    'Wallet 2',
    '500000000',
    assets,
    0,
    undefined,
    true,
    'syncing'
  ),
];

const stepsList = ['Wallet', 'Sign', 'Confirm', 'PIN code', 'QR code'];

storiesOf('Voting|Voting Registration Wizard', module)
  .addDecorator((story) => (
    <StoryProvider>
      <StoryDecorator>{story()}</StoryDecorator>
    </StoryProvider>
  ))
  .addDecorator(withKnobs)

  // ====== Stories ======

  .add('Voting Registration - Step 1', () => (
    <VotingRegistrationStepsChooseWallet
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={1}
      numberOfStakePools={number('numberOfStakePools', 100)}
      onSelectWallet={action('onSelectWallet')}
      wallets={WALLETS}
      minVotingRegistrationFunds={VOTING_REGISTRATION_MIN_WALLET_FUNDS}
      selectedWalletId={WALLETS[0].id}
      isWalletAcceptable={action('isWalletAcceptable')}
      getStakePoolById={action('getStakePoolById')}
    />
  ))

  .add('Voting Registration - Step 2', () => (
    <VotingRegistrationStepsRegister
      onClose={action('onClose')}
      onBack={action('onBack')}
      stepsList={stepsList}
      activeStep={2}
      transactionFee={
        new BigNumber(
          number('transactionFee', 0.3, {
            min: 0,
            max: 1000000,
          })
        )
      }
      isSubmitting={boolean('isSubmitting')}
      onConfirm={action('onConfirm')}
      onExternalLinkClick={action('onExternalLinkClick')}
      hwDeviceStatus={HwDeviceStatuses.CONNECTING}
      isHardwareWallet={boolean('isHardwareWallet', false)}
      isTrezor={boolean('isTrezor', false)}
      selectedWallet={WALLETS[0]}
    />
  ))

  .add('Voting Registration - Step 3', () => (
    <VotingRegistrationStepsConfirm
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={3}
      isTransactionPending={boolean('isTransactionPending', true)}
      isTransactionConfirmed={boolean('isTransactionConfirmed', false)}
      transactionConfirmations={number('transactionConfirmations', 0, {
        range: true,
        max: VOTING_REGISTRATION_MIN_TRANSACTION_CONFIRMATIONS,
      })}
      onConfirm={action('onConfirm')}
      onRestart={action('onRestart')}
      transactionError={boolean('transactionError', false)}
    />
  ))

  .add('Voting Registration - Step 4', () => (
    <VotingRegistrationStepsEnterPinCode
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={4}
      onSetPinCode={action('onSetPinCode')}
    />
  ))

  .add('Voting Registration - Step 5', () => (
    <VotingRegistrationStepsQrCode
      onClose={action('onClose')}
      onDownloadPDF={action('onDownloadPDF')}
      stepsList={stepsList}
      activeStep={2}
      qrCode="djkhfkwdjhfkwdhfkwjdhfkwdhf9wdyf9wdh9u3h03hd0f3hd0h30hf30dhf03dhf03dhf03dhf03dhf0u3dhf0u3dhf0u3dfh30uhfd30uh"
    />
  ));

storiesOf('Voting|Voting Info', module)
  .addDecorator((story) => <StoryDecorator>{story()}</StoryDecorator>)
  .addDecorator(withKnobs)

  // ====== Stories ======

  .add('Voting Info', () => (
    <VerticalFlexContainer>
      <VotingInfo
        fundPhase={select('Fund phase', [
          FundPhases.SNAPSHOT,
          FundPhases.VOTING,
          FundPhases.TALLYING,
          FundPhases.RESULTS,
        ])}
        currentLocale={LANGUAGE_OPTIONS[0].value}
        currentDateFormat={DATE_ENGLISH_OPTIONS[0].value}
        currentTimeFormat={TIME_OPTIONS[0].value}
        onRegisterToVoteClick={action('onRegisterToVoteClick')}
        onExternalLinkClick={action('onExternalLinkClick')}
      />
      <VotingFooterLinks />
    </VerticalFlexContainer>
  ));
<|endoftext|>


<commit_before>/* @flow */

import fs from 'fs';
import path from 'path';
import zlib from 'zlib';

let lumo = require('../lumo');

jest.mock('jszip');
// this needs to be here or tests start randomly failing with `can't find .babelrc`
require('jszip');

describe('lumo', () => {
  const readFileSync = fs.readFileSync;
  const existsSync = fs.existsSync;

  beforeEach(() => {
    fs.readFileSync = jest.fn((p: string) => {
      if (/foo/.test(p)) {
        return 'fooContents';
      }
      throw new Error(`file doesn't exist: ${p}`);
    });
  });

  afterEach(() => {
    fs.readFileSync = readFileSync;
    fs.existsSync = existsSync;
  });

  describe('load', () => {
    describe('in __DEV__', () => {
      fs.existsSync = jest.fn(() => true);
      it('returns the contents of a (bundled) file when it exists', () => {
        expect(lumo.load('foo')).toBe('fooContents');
      });

      it("returns null when a file doesn't exist", () => {
        expect(lumo.load('nonExistent')).toBe(null);
      });
    });

    describe('in production', () => {
      const inflateSync = zlib.inflateSync;

      beforeEach(() => {
        jest.resetModules();
        zlib.inflateSync = jest.fn((x: string) => x);
        global.lumo = {
          internal: {
            embedded: {
              keys: jest.fn(() => ['foo']),
              get: jest.fn((resource: string) => {
                if (resource === 'foo') {
                  return 'fooContents';
                }
                return null;
              }),
            },
          },
        };

        __DEV__ = false;
        lumo = require('../lumo'); // eslint-disable-line global-require
      });

      afterEach(() => {
        __DEV__ = true;
        zlib.inflateSync = inflateSync;
        delete global.lumo;
      });

      it('returns the contents of a (bundled) file when it exists', () => {
        expect(lumo.load('foo')).toBe('fooContents');
      });

      it("returns null when a file doesn't exist", () => {
        expect(lumo.load('nonExistent')).toBe(null);
      });
    });
  });

  describe('readCache', () => {
    it('returns the contents of a (cached) file when it exists', () => {
      expect(lumo.readCache('foo')).toEqual({
        source: 'fooContents',
        modified: expect.any(Number),
      });
    });

    it("returns null when a file doesn't exist", () => {
      expect(lumo.readCache('nonExistent')).toBe(null);
    });
  });

  describe('writeCache', () => {
    const writeFileSync = fs.writeFileSync;
    beforeEach(() => {
      fs.writeFileSync = jest.fn(
        (fname: string, contents: string, encoding: string) => {
          if (/foo/.test(fname)) {
            return;
          }
          throw new Error('some error');
        },
      );
    });

    afterEach(() => {
      fs.writeFileSync = writeFileSync;
    });

    it('writes correctly if directory exists', () => {
      expect(lumo.writeCache('foo', 'bar')).toBeUndefined();
    });

    it("catches and returns an error if it can't write", () => {
      expect(lumo.writeCache('nonExistent', 'contents')).toBeInstanceOf(Error);
    });
  });

  describe('readSource', () => {
    beforeEach(() => {
      jest.resetModules();
      lumo = require('../lumo'); // eslint-disable-line global-require
    });

    afterEach(() => {});

    it('cycles through the source paths', () => {
      const srcPaths = ['a', 'b', 'c'];
      lumo.addSourcePaths(srcPaths);
      const lumoPaths = ['', ...srcPaths];

      fs.readFileSync = jest.fn((filename: string) => {
        throw new Error(`file doesn't exist: ${filename}`);
      });

      const source = lumo.readSource('bar/baz');
      const mockCalls = fs.readFileSync.mock.calls;

      expect(source).toBe(null);
      expect(fs.readFileSync).toHaveBeenCalledTimes(4);
      expect(mockCalls.map((x: string[]) => x[0])).toEqual(
        lumoPaths.map((p: string) => path.join(p, 'bar/baz')),
      );
    });

    describe('reads JAR archives', () => {
      it('should return the source when JAR has the source', () => {
        const srcPaths = ['foo.jar'];
        lumo.addSourcePaths(srcPaths);

        const source = lumo.readSource('some/thing');

        expect(source).toEqual({
          source: 'zipContents',
          modified: expect.any(Number),
        });
      });

      it("should return null when the JAR doesn't have the source", () => {
        const source = lumo.readSource('some/thing');

        expect(source).toBe(null);
      });
    });
  });

  describe('loadUpstreamForeignLibs', () => {
    beforeEach(() => {
      jest.resetModules();
      lumo = require('../lumo'); // eslint-disable-line global-require
    });

    it('should return an array with the file contents when JAR has deps.cljs', () => {
      const srcPaths = ['foo.jar'];
      lumo.addSourcePaths(srcPaths);

      const source = lumo.loadUpstreamForeignLibs('some/thing');

      expect(source).toEqual(['zipContents']);
    });

    it("should return an empty array when the JAR doesn't have deps.cljs", () => {
      const source = lumo.loadUpstreamForeignLibs('some/thing');

      expect(source).toEqual([]);
    });

    it("shouldn't crash when a JAR isn't found", () => {
      const srcPaths = ['bar.jar'];
      lumo.addSourcePaths(srcPaths);

      const source = lumo.loadUpstreamForeignLibs('some/thing');

      expect(source).toEqual([]);
    });
  });

  describe('resource', () => {
    beforeEach(() => {
      jest.resetModules();
      lumo = require('../lumo'); // eslint-disable-line global-require
    });

    it('cycles through the source paths', () => {
      const srcPaths = ['a', 'b', 'c'];
      lumo.addSourcePaths(srcPaths);
      const lumoPaths = ['', ...srcPaths];

      fs.existsSync = jest.fn((_: string) => false);

      const exists = lumo.resource('bar/baz');
      const mockCalls = fs.existsSync.mock.calls;

      expect(exists).toBe(null);
      expect(fs.existsSync).toHaveBeenCalledTimes(5);
      expect(mockCalls.map((x: string[]) => x[0])).toEqual(
        ['./target/bar/baz'].concat(
          lumoPaths.map((p: string) => path.join(p, 'bar/baz')),
        ),
      );
    });

    it('returns the representation for the resource when it exists', () => {
      fs.existsSync = jest.fn((_: string) => true);
      expect(lumo.resource('some-file')).toEqual({
        type: 'bundled',
        src: 'some-file',
      });
    });

    describe('reads JAR archives', () => {
      it('should return true when JAR has the file', () => {
        const srcPaths = ['foo.jar'];
        lumo.addSourcePaths(srcPaths);

        fs.existsSync = jest.fn((fname: string) => /foo/.test(fname));

        expect(lumo.resource('some/thing')).toMatchObject({
          type: 'jar',
          src: 'some/thing',
        });
      });

      it("should return false when the JAR doesn't have the file", () => {
        expect(lumo.resource('some/thing')).toBe(null);
      });
    });
  });
});
<commit_msg>actually fix build by mocking fs.statSync<commit_after>/* @flow */

import fs from 'fs';
import path from 'path';
import zlib from 'zlib';

let lumo = require('../lumo');

jest.mock('jszip');
// this needs to be here or tests start randomly failing with `can't find .babelrc`
require('jszip');

describe('lumo', () => {
  const readFileSync = fs.readFileSync;
  const existsSync = fs.existsSync;

  beforeEach(() => {
    fs.readFileSync = jest.fn((p: string) => {
      if (/foo/.test(p)) {
        return 'fooContents';
      }
      throw new Error(`file doesn't exist: ${p}`);
    });
  });

  afterEach(() => {
    fs.readFileSync = readFileSync;
    fs.existsSync = existsSync;
  });

  describe('load', () => {
    describe('in __DEV__', () => {
      fs.existsSync = jest.fn(() => true);
      it('returns the contents of a (bundled) file when it exists', () => {
        expect(lumo.load('foo')).toBe('fooContents');
      });

      it("returns null when a file doesn't exist", () => {
        expect(lumo.load('nonExistent')).toBe(null);
      });
    });

    describe('in production', () => {
      const inflateSync = zlib.inflateSync;

      beforeEach(() => {
        jest.resetModules();
        zlib.inflateSync = jest.fn((x: string) => x);
        global.lumo = {
          internal: {
            embedded: {
              keys: jest.fn(() => ['foo']),
              get: jest.fn((resource: string) => {
                if (resource === 'foo') {
                  return 'fooContents';
                }
                return null;
              }),
            },
          },
        };

        __DEV__ = false;
        lumo = require('../lumo'); // eslint-disable-line global-require
      });

      afterEach(() => {
        __DEV__ = true;
        zlib.inflateSync = inflateSync;
        delete global.lumo;
      });

      it('returns the contents of a (bundled) file when it exists', () => {
        expect(lumo.load('foo')).toBe('fooContents');
      });

      it("returns null when a file doesn't exist", () => {
        expect(lumo.load('nonExistent')).toBe(null);
      });
    });
  });

  describe('readCache', () => {
    const statSync = fs.statSync;
    beforeEach(() => {
      fs.statSync = jest.fn((filename: string) => ({
        mtime: new Date(),
      }));
    });

    afterEach(() => {
      fs.statSync = statSync;
    });

    it('returns the contents of a (cached) file when it exists', () => {
      expect(lumo.readCache('foo')).toEqual({
        source: 'fooContents',
        modified: expect.any(Number),
      });
    });

    it("returns null when a file doesn't exist", () => {
      expect(lumo.readCache('nonExistent')).toBe(null);
    });
  });

  describe('writeCache', () => {
    const writeFileSync = fs.writeFileSync;
    beforeEach(() => {
      fs.writeFileSync = jest.fn(
        (fname: string, contents: string, encoding: string) => {
          if (/foo/.test(fname)) {
            return;
          }
          throw new Error('some error');
        },
      );
    });

    afterEach(() => {
      fs.writeFileSync = writeFileSync;
    });

    it('writes correctly if directory exists', () => {
      expect(lumo.writeCache('foo', 'bar')).toBeUndefined();
    });

    it("catches and returns an error if it can't write", () => {
      expect(lumo.writeCache('nonExistent', 'contents')).toBeInstanceOf(Error);
    });
  });

  describe('readSource', () => {
    beforeEach(() => {
      jest.resetModules();
      lumo = require('../lumo'); // eslint-disable-line global-require
    });

    afterEach(() => {});

    it('cycles through the source paths', () => {
      const srcPaths = ['a', 'b', 'c'];
      lumo.addSourcePaths(srcPaths);
      const lumoPaths = ['', ...srcPaths];

      fs.readFileSync = jest.fn((filename: string) => {
        throw new Error(`file doesn't exist: ${filename}`);
      });

      const source = lumo.readSource('bar/baz');
      const mockCalls = fs.readFileSync.mock.calls;

      expect(source).toBe(null);
      expect(fs.readFileSync).toHaveBeenCalledTimes(4);
      expect(mockCalls.map((x: string[]) => x[0])).toEqual(
        lumoPaths.map((p: string) => path.join(p, 'bar/baz')),
      );
    });

    describe('reads JAR archives', () => {
      it('should return the source when JAR has the source', () => {
        const srcPaths = ['foo.jar'];
        lumo.addSourcePaths(srcPaths);

        const source = lumo.readSource('some/thing');

        expect(source).toEqual({
          source: 'zipContents',
          modified: expect.any(Number),
        });
      });

      it("should return null when the JAR doesn't have the source", () => {
        const source = lumo.readSource('some/thing');

        expect(source).toBe(null);
      });
    });
  });

  describe('loadUpstreamForeignLibs', () => {
    beforeEach(() => {
      jest.resetModules();
      lumo = require('../lumo'); // eslint-disable-line global-require
    });

    it('should return an array with the file contents when JAR has deps.cljs', () => {
      const srcPaths = ['foo.jar'];
      lumo.addSourcePaths(srcPaths);

      const source = lumo.loadUpstreamForeignLibs('some/thing');

      expect(source).toEqual(['zipContents']);
    });

    it("should return an empty array when the JAR doesn't have deps.cljs", () => {
      const source = lumo.loadUpstreamForeignLibs('some/thing');

      expect(source).toEqual([]);
    });

    it("shouldn't crash when a JAR isn't found", () => {
      const srcPaths = ['bar.jar'];
      lumo.addSourcePaths(srcPaths);

      const source = lumo.loadUpstreamForeignLibs('some/thing');

      expect(source).toEqual([]);
    });
  });

  describe('resource', () => {
    beforeEach(() => {
      jest.resetModules();
      lumo = require('../lumo'); // eslint-disable-line global-require
    });

    it('cycles through the source paths', () => {
      const srcPaths = ['a', 'b', 'c'];
      lumo.addSourcePaths(srcPaths);
      const lumoPaths = ['', ...srcPaths];

      fs.existsSync = jest.fn((_: string) => false);

      const exists = lumo.resource('bar/baz');
      const mockCalls = fs.existsSync.mock.calls;

      expect(exists).toBe(null);
      expect(fs.existsSync).toHaveBeenCalledTimes(5);
      expect(mockCalls.map((x: string[]) => x[0])).toEqual(
        ['./target/bar/baz'].concat(
          lumoPaths.map((p: string) => path.join(p, 'bar/baz')),
        ),
      );
    });

    it('returns the representation for the resource when it exists', () => {
      fs.existsSync = jest.fn((_: string) => true);
      expect(lumo.resource('some-file')).toEqual({
        type: 'bundled',
        src: 'some-file',
      });
    });

    describe('reads JAR archives', () => {
      it('should return true when JAR has the file', () => {
        const srcPaths = ['foo.jar'];
        lumo.addSourcePaths(srcPaths);

        fs.existsSync = jest.fn((fname: string) => /foo/.test(fname));

        expect(lumo.resource('some/thing')).toMatchObject({
          type: 'jar',
          src: 'some/thing',
        });
      });

      it("should return false when the JAR doesn't have the file", () => {
        expect(lumo.resource('some/thing')).toBe(null);
      });
    });
  });
});
<|endoftext|>


<commit_before>const router = require('koa-router');

const userController = require('../controller/user');

exports.init = (router) => {
  router
  .post('/auth/login', userController.login)
  .post('/auth/register', userController.create)
  .get('/users', userController.show)
}
<commit_msg>Update login and signup api url<commit_after>const router = require('koa-router');

const userController = require('../controller/user');

exports.init = (router) => {
  router
  .post('/auth/sessions', userController.login)
  .post('/auth/users', userController.create)
  .get('/users', userController.show)
}
<|endoftext|>


<commit_before>jQuery(function() {
	piggydb.widget.Fragment.init();
});

(function(module) {

	var _messages = piggydb.server.messages;

	var _class = function(node) {
		this.node = jQuery(node);
		this.root = this.node.closest("table.fragment");
	};

	_class.init = function() {
		jQuery("table.fragment").live('mouseenter', function() {
	    jQuery(this).find(".fragment-tools").eq(0).show();
	  });
	  jQuery("table.fragment").live('mouseleave', function() {
	    jQuery(this).find(".fragment-tools").eq(0).hide();
	  });
	  _class.makeFragmentsDroppable("table.fragment", null);
	  _class.makeRelationsDraggable("");
	};

	_class.initForPartial = function(selectorPrefix) {
		_class.makeFragmentsDroppable(selectorPrefix + "table.fragment", null);
	  _class.makeRelationsDraggable(selectorPrefix);
	};

	_class.findInTheSameFragmentNode = function(node, selector) {
		return jQuery(node).closest("table.fragment-node").find(selector);
	};

	_class.highlight = function(id, baseNode) {
	  var selector = ".fragment-header-" + id;
	  var color = "#ff9900";
	  if (baseNode == null)
	  	jQuery(selector).fadingHighlight(color);
	  else
	  	jQuery(baseNode).find(selector).fadingHighlight(color);
	};

	_class.onShowHiddenTags = function(button) {
	  jQuery(button).siblings(".hidden-tags").show();
	  jQuery(button).hide();
	};

	_class.syncTitles = function(id, title, headline) {
		var selector = ".fragment-header-" + id + " span.title";
		jQuery(selector).html(headline);
		jQuery("table.fragment-full > tbody > tr > th.header-cell " + selector).html(title);
	};

	_class.syncCaptions = function(id, caption) {
		jQuery(".fragment-header-" + id + " span.fragment-caption").html(caption.html());
	};

	_class.getHeaders = function(fragmentId) {
	  var headerClass = ".fragment-header";
	  if (fragmentId != null) headerClass = headerClass + "-" + fragmentId;
	  return jQuery(headerClass);
	};

	_class.makeFragmentsDroppable = function(selector, hoverClass) {
	  jQuery(selector).droppable({

	    accept: function(draggable) {
	      if (!draggable.hasClass("droppable-to-fragment")) return false;

	      // check if the relation can be created
	      if (draggable.hasClass("relation-draggable")) {
	        var from = draggable.find(".fragment-id").text();
	        var to = jQuery(this).find(".fragment-id:first").text();
	        if (from == to) return false;
	      }

	      return true;
	    },

	    hoverClass: hoverClass != null ? hoverClass : 'fragment-drophover',

	    greedy: true,

	    tolerance: 'intersect',

	    drop: function(event, ui) {
	      var targetId = jQuery(this).find(".fragment-id:first").text();

	      // add a tag
	      if (ui.draggable.hasClass("tag-palette-draggable")) {
	        var tagId = ui.draggable.find(".tag .id").text();
	        if (isNotBlank(tagId)) {
	          var tags = jQuery("span.tags-placeholder-" + targetId);
	          tags.empty().putLoadingIcon("margin: -2px; margin-left: 5px;");
	          jQuery.get("partial/add-tag.htm", {"fragmentId": targetId, "tagId": tagId},
	            function(html) {
	              tags.empty().append(jQuery(html).children("span.tags"));
	              _class.highlight(targetId, null);
	            });
	        }
	      }

	      // create a relationship
	      if (ui.draggable.hasClass("relation-draggable")) {
	        var fromId = ui.draggable.find(".fragment-id").text();
	        var fromTitle = ui.draggable.find(".fragment-title").text();
	        var toTitle = jQuery(this).find(".fragment-tools .fragment-title:first").text();
	        var message = jQuery(jQuery("#tpl-confirm-create-relation").html());
					message.find(".from-id").text(fromId);
					message.find(".from-title").text(fromTitle);
					message.find(".to-id").text(targetId);
					message.find(".to-title").text(toTitle);
	        var dialog = piggydb.widget.showConfirmDialog(
	        	_messages["create-relation"],
						message.html(),
						_messages["create"],
						function () {
							var forward = jQuery(this).find("input.forward")[0].checked;
							var backward = jQuery(this).find("input.backward")[0].checked;

	            var fm = document.forms['createRelationForm'];
	            fm.fromId.value = fromId;
	            fm.toId.value = targetId;
							if (forward) fm.forward.value = "on";
							if (backward) fm.backward.value = "on";
	            fm.submit();
	          }
					);
	      }
	    }
	  });
	};

	_class.makeRelationsDraggable = function(selectorPrefix) {
	  jQuery(selectorPrefix + ".fragment-tools .relation-draggable").draggable({
	    revert: true,
	    helper: 'clone',
	    appendTo: 'body',
	    opacity: 0.70,
	    zIndex: 120,
	    cursorAt: { bottom: 2, right: 0 }
	  });
	};

	_class.reloadRootChildNodes = function(parentId, newId) {
		var div = jQuery("#children-tree").empty().putLoadingIcon("margin: 5px;");
		jQuery.get("partial/fragment-root-child-nodes.htm", {id: parentId}, function(childrenHtml) {
			div.html(childrenHtml);
			_class.initForPartial("#children-tree ");
			_class.highlight(newId, null);
    });
	};

	_class.prototype = jQuery.extend({

		id: function() {
			return this.root.find("span.fragment-id:first").text();
		},

		header: function() {
			return this.root.find("div.fragment-header:first");
		},

		caption: function() {
			return this.header().find("span.fragment-caption");
		},

		mainTitleSpan: function() {
			return this.header().find("span.title");
		},

		shortTitleSpan: function() {
			return this.header().find(".fragment-tools span.fragment-title");
		},

		headerRow: function() {
			return this.header().closest("tr");
		},

		bodyRow: function() {
			return this.headerRow().siblings("tr.fragment-body");
		},

		hasBodyRow: function() {
			return this.bodyRow().size() > 0;
		},

		setBodyRow: function(rowHtml) {
			this.bodyRow().remove();
			this.headerRow().after(rowHtml);
		},

		textContentDiv: function() {
			return this.bodyRow().find("div.fragment-content-text");
		},

		emptyTextContent: function() {
			var contentToggle = this.contentToggle();
			if (contentToggle != null) contentToggle.setClosed();
			this.contentToggleContainer().hide();
			this.bodyRow().remove();
		},

		isFull: function() {
			return this.root.hasClass("fragment-full");
		},

		isMultirow: function() {
			return this.root.hasClass("multirow");
		},

		isMain: function() {
			return this.root.hasClass("fragment-main");
		},

		isCellCompact: function() {
			return this.root.hasClass("fragment-cell-compact");
		},

		isEditable: function() {
			return this.header().find("a.edit-fragment").size() > 0;
		},

		contentToggleContainer: function() {
			return this.header().find("span.fragment-content-toggle");
		},

		contentToggle: function() {
			var toggle = this.header().find(".fragment-content-toggle a.tool-button");
			return toggle.size() == 0 ? null : new piggydb.widget.ContentToggle(toggle);
		},

		openContentIfClosed: function() {
			var toggle = this.contentToggle();
			if (toggle != null) toggle.open();
		},

		highlight: function() {
			_class.highlight(this.id(), this.root);
		},

		fullEditor: function() {
			var editor = this.root.siblings(".fragment-form-panel");
			return editor.size() > 0 ? editor : null;
		},

		quickEditor: function() {
			return this.bodyRow().find("div.fragment-editor-quick");
		},

		closeQuickEditor: function() {
			this.quickEditor().empty();
		},

		tagsPlaceholder: function() {
			return jQuery("span.tags-placeholder-" + this.id());
		},

		update: function(propertiesHtml) {
			var properties = jQuery(propertiesHtml);

			// caption
			_class.syncCaptions(
				this.id(),
				properties.find("div.prop-caption > div.default > span.fragment-caption"));
			if (this.isCellCompact()) {
				this.caption().html(properties.find(
					"div.prop-caption > div.cell-compact > span.fragment-caption").html());
			}

			// title
			_class.syncTitles(
				this.id(),
				properties.find("div.prop-title > span.title").html(),
				properties.find("div.prop-title > span.headline").html());

			this.shortTitleSpan().html(
				properties.find("div.prop-title > span.title-short").html());

			// body row
	  	var bodyRow = properties.children("div.prop-body-row");
	  	if (isNotBlank(bodyRow.find("div.fragment-content").html())) {
	  		if (this.hasBodyRow() || this.isFull()) {
	  			this.setBodyRow(bodyRow.find("tbody.body-row-container").html());
	  			prettyPrint();
		  	}
	  		else {
	  			this.contentToggleContainer().show();
			  	this.openContentIfClosed();
	  		}
	  	}
	  	else {
		  	this.emptyTextContent();
		  }

	  	// update info
	  	this.header().find("span.update-info").html(
	  		properties.find("div.prop-update-info > span.update-info").html());

	  	// tags
	  	var tags = properties.find("div.prop-tags span.tags");
	  	var placeholder = this.tagsPlaceholder().empty();
	  	if (tags.size() > 0) {
	  		placeholder.append(tags);
	  	}
		}
	}, module.Widget.prototype);

	module.Fragment = _class;

})(piggydb.widget);
<commit_msg>#refactoring: #javascript: changed the arg of piggydb.widget.Fragment.initForPartial<commit_after>jQuery(function() {
	piggydb.widget.Fragment.init();
});

(function(module) {

	var _messages = piggydb.server.messages;

	var _class = function(node) {
		this.node = jQuery(node);
		this.root = this.node.closest("table.fragment");
	};

	_class.init = function() {
		jQuery("table.fragment").live('mouseenter', function() {
	    jQuery(this).find(".fragment-tools").eq(0).show();
	  });
	  jQuery("table.fragment").live('mouseleave', function() {
	    jQuery(this).find(".fragment-tools").eq(0).hide();
	  });
	  _class.makeFragmentsDroppable("table.fragment", null);
	  _class.makeRelationsDraggable("");
	};

	_class.initForPartial = function(partialSelector) {
		_class.makeFragmentsDroppable(partialSelector + " table.fragment", null);
	  _class.makeRelationsDraggable(partialSelector + " ");
	};

	_class.findInTheSameFragmentNode = function(node, selector) {
		return jQuery(node).closest("table.fragment-node").find(selector);
	};

	_class.highlight = function(id, baseNode) {
	  var selector = ".fragment-header-" + id;
	  var color = "#ff9900";
	  if (baseNode == null)
	  	jQuery(selector).fadingHighlight(color);
	  else
	  	jQuery(baseNode).find(selector).fadingHighlight(color);
	};

	_class.onShowHiddenTags = function(button) {
	  jQuery(button).siblings(".hidden-tags").show();
	  jQuery(button).hide();
	};

	_class.syncTitles = function(id, title, headline) {
		var selector = ".fragment-header-" + id + " span.title";
		jQuery(selector).html(headline);
		jQuery("table.fragment-full > tbody > tr > th.header-cell " + selector).html(title);
	};

	_class.syncCaptions = function(id, caption) {
		jQuery(".fragment-header-" + id + " span.fragment-caption").html(caption.html());
	};

	_class.getHeaders = function(fragmentId) {
	  var headerClass = ".fragment-header";
	  if (fragmentId != null) headerClass = headerClass + "-" + fragmentId;
	  return jQuery(headerClass);
	};

	_class.makeFragmentsDroppable = function(selector, hoverClass) {
	  jQuery(selector).droppable({

	    accept: function(draggable) {
	      if (!draggable.hasClass("droppable-to-fragment")) return false;

	      // check if the relation can be created
	      if (draggable.hasClass("relation-draggable")) {
	        var from = draggable.find(".fragment-id").text();
	        var to = jQuery(this).find(".fragment-id:first").text();
	        if (from == to) return false;
	      }

	      return true;
	    },

	    hoverClass: hoverClass != null ? hoverClass : 'fragment-drophover',

	    greedy: true,

	    tolerance: 'intersect',

	    drop: function(event, ui) {
	      var targetId = jQuery(this).find(".fragment-id:first").text();

	      // add a tag
	      if (ui.draggable.hasClass("tag-palette-draggable")) {
	        var tagId = ui.draggable.find(".tag .id").text();
	        if (isNotBlank(tagId)) {
	          var tags = jQuery("span.tags-placeholder-" + targetId);
	          tags.empty().putLoadingIcon("margin: -2px; margin-left: 5px;");
	          jQuery.get("partial/add-tag.htm", {"fragmentId": targetId, "tagId": tagId},
	            function(html) {
	              tags.empty().append(jQuery(html).children("span.tags"));
	              _class.highlight(targetId, null);
	            });
	        }
	      }

	      // create a relationship
	      if (ui.draggable.hasClass("relation-draggable")) {
	        var fromId = ui.draggable.find(".fragment-id").text();
	        var fromTitle = ui.draggable.find(".fragment-title").text();
	        var toTitle = jQuery(this).find(".fragment-tools .fragment-title:first").text();
	        var message = jQuery(jQuery("#tpl-confirm-create-relation").html());
					message.find(".from-id").text(fromId);
					message.find(".from-title").text(fromTitle);
					message.find(".to-id").text(targetId);
					message.find(".to-title").text(toTitle);
	        var dialog = piggydb.widget.showConfirmDialog(
	        	_messages["create-relation"],
						message.html(),
						_messages["create"],
						function () {
							var forward = jQuery(this).find("input.forward")[0].checked;
							var backward = jQuery(this).find("input.backward")[0].checked;

	            var fm = document.forms['createRelationForm'];
	            fm.fromId.value = fromId;
	            fm.toId.value = targetId;
							if (forward) fm.forward.value = "on";
							if (backward) fm.backward.value = "on";
	            fm.submit();
	          }
					);
	      }
	    }
	  });
	};

	_class.makeRelationsDraggable = function(selectorPrefix) {
	  jQuery(selectorPrefix + ".fragment-tools .relation-draggable").draggable({
	    revert: true,
	    helper: 'clone',
	    appendTo: 'body',
	    opacity: 0.70,
	    zIndex: 120,
	    cursorAt: { bottom: 2, right: 0 }
	  });
	};

	_class.reloadRootChildNodes = function(parentId, newId) {
		var div = jQuery("#children-tree").empty().putLoadingIcon("margin: 5px;");
		jQuery.get("partial/fragment-root-child-nodes.htm", {id: parentId}, function(childrenHtml) {
			div.html(childrenHtml);
			_class.initForPartial("#children-tree");
			_class.highlight(newId, null);
    });
	};

	_class.prototype = jQuery.extend({

		id: function() {
			return this.root.find("span.fragment-id:first").text();
		},

		header: function() {
			return this.root.find("div.fragment-header:first");
		},

		caption: function() {
			return this.header().find("span.fragment-caption");
		},

		mainTitleSpan: function() {
			return this.header().find("span.title");
		},

		shortTitleSpan: function() {
			return this.header().find(".fragment-tools span.fragment-title");
		},

		headerRow: function() {
			return this.header().closest("tr");
		},

		bodyRow: function() {
			return this.headerRow().siblings("tr.fragment-body");
		},

		hasBodyRow: function() {
			return this.bodyRow().size() > 0;
		},

		setBodyRow: function(rowHtml) {
			this.bodyRow().remove();
			this.headerRow().after(rowHtml);
		},

		textContentDiv: function() {
			return this.bodyRow().find("div.fragment-content-text");
		},

		emptyTextContent: function() {
			var contentToggle = this.contentToggle();
			if (contentToggle != null) contentToggle.setClosed();
			this.contentToggleContainer().hide();
			this.bodyRow().remove();
		},

		isFull: function() {
			return this.root.hasClass("fragment-full");
		},

		isMultirow: function() {
			return this.root.hasClass("multirow");
		},

		isMain: function() {
			return this.root.hasClass("fragment-main");
		},

		isCellCompact: function() {
			return this.root.hasClass("fragment-cell-compact");
		},

		isEditable: function() {
			return this.header().find("a.edit-fragment").size() > 0;
		},

		contentToggleContainer: function() {
			return this.header().find("span.fragment-content-toggle");
		},

		contentToggle: function() {
			var toggle = this.header().find(".fragment-content-toggle a.tool-button");
			return toggle.size() == 0 ? null : new piggydb.widget.ContentToggle(toggle);
		},

		openContentIfClosed: function() {
			var toggle = this.contentToggle();
			if (toggle != null) toggle.open();
		},

		highlight: function() {
			_class.highlight(this.id(), this.root);
		},

		fullEditor: function() {
			var editor = this.root.siblings(".fragment-form-panel");
			return editor.size() > 0 ? editor : null;
		},

		quickEditor: function() {
			return this.bodyRow().find("div.fragment-editor-quick");
		},

		closeQuickEditor: function() {
			this.quickEditor().empty();
		},

		tagsPlaceholder: function() {
			return jQuery("span.tags-placeholder-" + this.id());
		},

		update: function(propertiesHtml) {
			var properties = jQuery(propertiesHtml);

			// caption
			_class.syncCaptions(
				this.id(),
				properties.find("div.prop-caption > div.default > span.fragment-caption"));
			if (this.isCellCompact()) {
				this.caption().html(properties.find(
					"div.prop-caption > div.cell-compact > span.fragment-caption").html());
			}

			// title
			_class.syncTitles(
				this.id(),
				properties.find("div.prop-title > span.title").html(),
				properties.find("div.prop-title > span.headline").html());

			this.shortTitleSpan().html(
				properties.find("div.prop-title > span.title-short").html());

			// body row
	  	var bodyRow = properties.children("div.prop-body-row");
	  	if (isNotBlank(bodyRow.find("div.fragment-content").html())) {
	  		if (this.hasBodyRow() || this.isFull()) {
	  			this.setBodyRow(bodyRow.find("tbody.body-row-container").html());
	  			prettyPrint();
		  	}
	  		else {
	  			this.contentToggleContainer().show();
			  	this.openContentIfClosed();
	  		}
	  	}
	  	else {
		  	this.emptyTextContent();
		  }

	  	// update info
	  	this.header().find("span.update-info").html(
	  		properties.find("div.prop-update-info > span.update-info").html());

	  	// tags
	  	var tags = properties.find("div.prop-tags span.tags");
	  	var placeholder = this.tagsPlaceholder().empty();
	  	if (tags.size() > 0) {
	  		placeholder.append(tags);
	  	}
		}
	}, module.Widget.prototype);

	module.Fragment = _class;

})(piggydb.widget);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var onBabelError = require('./babel-error.js');
var rename = require('gulp-rename');
var webpackStream = require('webpack-stream');
var webpack2 = require('webpack');
var named = require('vinyl-named');

var CONFIG = require('../config.js');

// ----- WEBPACK CONFIGURATION -----
//
// The following sets up all imports from within Foundation as externals, for the purpose
// of replicating the "drop in dist file" approach of prior versions.
// THIS IS NOT RECOMMENDED FOR MOST USERS. Chances are you either want everything
// (just throw in foundation.js or foundation.min.js) or you should be using a build
// system.

// Convert an external config object for UMD modules
// See: https://webpack.js.org/configuration/externals/#object
function umdExternals(externals, options) {
  options = Object.assign({ namespace: '' }, options);
  const umdExternalPath = (...args) => [...args].filter(v => v && !!v.length);

  return Object.keys(externals).reduce(function(obj, k) {
    obj[k] = {
      root: umdExternalPath(options.namespace, externals[k]),
      amd: k,
      commonjs: k,
      commonjs2: k,
    };
    return obj;
  }, {});
};

// Generate plugin Externals config for UMD modules
var pluginsAsExternals = Object.assign(
  umdExternals({
    'jquery': 'jQuery',
  }),
  umdExternals({
    // Import path                    | Exported file
    './foundation.core':              'foundation.core',
    './foundation.core.utils':        'foundation.core',
    './foundation.core.plugin':       'foundation.core',
    './foundation.util.imageLoader':  'foundation.util.imageLoader',
    './foundation.util.keyboard':     'foundation.util.keyboard',
    './foundation.util.mediaQuery':   'foundation.util.mediaQuery',
    './foundation.util.motion':       'foundation.util.motion',
    './foundation.util.nest':         'foundation.util.nest',
    './foundation.util.timer':        'foundation.util.timer',
    './foundation.util.touch':        'foundation.util.touch',
    './foundation.util.box':          'foundation.util.box',
    './foundation.dropdownMenu':      'foundation.dropdownMenu',
    './foundation.drilldown':         'foundation.drilldown',
    './foundation.accordionMenu':     'foundation.accordionMenu',
    './foundation.accordion':         'foundation.accordion',
    './foundation.tabs':              'foundation.tabs',
    './foundation.smoothScroll':      'foundation.smoothScroll',
  }, { namespace: CONFIG.JS_BUNDLE_NAMESPACE })
);

var webpackConfig = {
  externals: umdExternals({
    'jquery': 'jQuery'
  }),
  module: {
    rules: [
      {
        test: /.js$/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  },
  output: {
    library: [CONFIG.JS_BUNDLE_NAMESPACE, '[name]'],
    libraryTarget: 'umd',
  }
}

// ----- TASKS -----
//

// Compiles JavaScript into a single file
gulp.task('javascript', ['javascript:foundation', 'javascript:deps', 'javascript:docs']);

// Core has to be dealt with slightly differently due to bootstrapping externals
// and the dependency on foundation.core.utils
//
gulp.task('javascript:plugin-core', function() {
  return gulp.src('js/entries/plugins/foundation.core.js')
    .pipe(named())
    .pipe(webpackStream(webpackConfig, webpack2))
    .pipe(gulp.dest('_build/assets/js/plugins'));
});
gulp.task('javascript:plugins', ['javascript:plugin-core'], function () {
  return gulp.src(['js/entries/plugins/*.js', '!js/entries/plugins/foundation.core.js'])
    .pipe(named())
    .pipe(webpackStream(Object.assign({}, webpackConfig, { externals: pluginsAsExternals }), webpack2))
    .pipe(gulp.dest('_build/assets/js/plugins'));
});

gulp.task('javascript:foundation', ['javascript:plugins'], function() {
  return gulp.src('js/entries/foundation.js')
    .pipe(named())
    .pipe(webpackStream(webpackConfig, webpack2))
    .pipe(gulp.dest('_build/assets/js'));
});

gulp.task('javascript:deps', function() {
  return gulp.src(CONFIG.JS_DEPS)
    .pipe(concat('vendor.js'))
    .pipe(gulp.dest('_build/assets/js'));
});

gulp.task('javascript:docs', function() {
  return gulp.src(CONFIG.JS_DOCS)
    .pipe(concat('docs.js'))
    .pipe(gulp.dest('_build/assets/js'));
});
<commit_msg>chore: prevent the main JS bundle to be exported as an unused external<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var onBabelError = require('./babel-error.js');
var rename = require('gulp-rename');
var webpackStream = require('webpack-stream');
var webpack2 = require('webpack');
var named = require('vinyl-named');

var CONFIG = require('../config.js');

// ----- WEBPACK CONFIGURATION -----
//
// The following sets up all imports from within Foundation as externals, for the purpose
// of replicating the "drop in dist file" approach of prior versions.
// THIS IS NOT RECOMMENDED FOR MOST USERS. Chances are you either want everything
// (just throw in foundation.js or foundation.min.js) or you should be using a build
// system.

// Convert an external config object for UMD modules
// See: https://webpack.js.org/configuration/externals/#object
function umdExternals(externals, options) {
  options = Object.assign({ namespace: '' }, options);
  const umdExternalPath = (...args) => [...args].filter(v => v && !!v.length);

  return Object.keys(externals).reduce(function(obj, k) {
    obj[k] = {
      root: umdExternalPath(options.namespace, externals[k]),
      amd: k,
      commonjs: k,
      commonjs2: k,
    };
    return obj;
  }, {});
};

// Generate plugin Externals config for UMD modules
const webpackExternalPlugins = Object.assign(
  umdExternals({
    'jquery': 'jQuery',
  }),
  umdExternals({
    // Import path                    | Exported file
    './foundation.core':              'foundation.core',
    './foundation.core.utils':        'foundation.core',
    './foundation.core.plugin':       'foundation.core',
    './foundation.util.imageLoader':  'foundation.util.imageLoader',
    './foundation.util.keyboard':     'foundation.util.keyboard',
    './foundation.util.mediaQuery':   'foundation.util.mediaQuery',
    './foundation.util.motion':       'foundation.util.motion',
    './foundation.util.nest':         'foundation.util.nest',
    './foundation.util.timer':        'foundation.util.timer',
    './foundation.util.touch':        'foundation.util.touch',
    './foundation.util.box':          'foundation.util.box',
    './foundation.dropdownMenu':      'foundation.dropdownMenu',
    './foundation.drilldown':         'foundation.drilldown',
    './foundation.accordionMenu':     'foundation.accordionMenu',
    './foundation.accordion':         'foundation.accordion',
    './foundation.tabs':              'foundation.tabs',
    './foundation.smoothScroll':      'foundation.smoothScroll',
  }, { namespace: CONFIG.JS_BUNDLE_NAMESPACE })
);

const webpackOutputAsExternal = {
  library: [CONFIG.JS_BUNDLE_NAMESPACE, '[name]'],
  libraryTarget: 'umd',
};

var webpackConfig = {
  externals: umdExternals({
    'jquery': 'jQuery'
  }),
  module: {
    rules: [
      {
        test: /.js$/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  },
  output: {
    libraryTarget: 'umd',
  }
}

// ----- TASKS -----
//

// Compiles JavaScript into a single file
gulp.task('javascript', ['javascript:foundation', 'javascript:deps', 'javascript:docs']);

// Core has to be dealt with slightly differently due to bootstrapping externals
// and the dependency on foundation.core.utils
//
gulp.task('javascript:plugin-core', function() {
  return gulp.src('js/entries/plugins/foundation.core.js')
    .pipe(named())
    .pipe(webpackStream(Object.assign({}, webpackConfig, {
        output: webpackOutputAsExternal,
      }), webpack2))
    .pipe(gulp.dest('_build/assets/js/plugins'));
});
gulp.task('javascript:plugins', ['javascript:plugin-core'], function () {
  return gulp.src(['js/entries/plugins/*.js', '!js/entries/plugins/foundation.core.js'])
    .pipe(named())
    .pipe(webpackStream(Object.assign({}, webpackConfig, {
        externals: webpackExternalPlugins,
        output: webpackOutputAsExternal,
      }), webpack2))
    .pipe(gulp.dest('_build/assets/js/plugins'));
});

gulp.task('javascript:foundation', ['javascript:plugins'], function() {
  return gulp.src('js/entries/foundation.js')
    .pipe(named())
    .pipe(webpackStream(webpackConfig, webpack2))
    .pipe(gulp.dest('_build/assets/js'));
});

gulp.task('javascript:deps', function() {
  return gulp.src(CONFIG.JS_DEPS)
    .pipe(concat('vendor.js'))
    .pipe(gulp.dest('_build/assets/js'));
});

gulp.task('javascript:docs', function() {
  return gulp.src(CONFIG.JS_DOCS)
    .pipe(concat('docs.js'))
    .pipe(gulp.dest('_build/assets/js'));
});
<|endoftext|>