<commit_before>/*jshint node: true*/

var through = require("through");
var Handlebars = require("handlebars");
var xtend = require("xtend");

var defaultExtensions = {
  hbs: true,
  handlebar: true,
  handlebars: true
};

// Convert string or array of extensions to a object
function toExtensionsOb(arr) {
  var ob = {};

  if (typeof arr === "string") {
    arr = arr.split(",");
  }

  if (Array.isArray(arr)) {
    arr.filter(Boolean).forEach(function(ext) {
      ob[ext] = true;
    });
  } else {
    // Already in the correct format
    return arr;
  }

  return ob;
}

function hbsfy(file, opts) {
  var extensions = defaultExtensions;

  if (opts && opts.extensions) {
    extensions = toExtensionsOb(opts.extensions);
  }

  if (!extensions[file.split(".").pop()]) return through();

  var buffer = "";

  return through(function(chunk) {
    buffer += chunk.toString();
  },
  function() {
    var js = Handlebars.precompile(buffer);
    // Compile only with the runtime dependency.
    var compiled = "// hbsfy compiled Handlebars template\n";
    compiled += "var Handlebars = require('hbsfy/runtime');\n";
    compiled += "module.exports = Handlebars.template(" + js.toString() + ");\n";
    this.queue(compiled);
    this.queue(null);
  });

}

// Return new hbsfy transform with custom default options
hbsfy.configure = function(rootOpts) {
  return function(file, opts) {
    return hbsfy(file, xtend({}, rootOpts, opts));
  };
};

module.exports = hbsfy;

<commit_msg>Support -e subarg too<commit_after>/*jshint node: true*/

var through = require("through");
var Handlebars = require("handlebars");
var xtend = require("xtend");

var defaultExtensions = {
  hbs: true,
  handlebar: true,
  handlebars: true
};

// Convert string or array of extensions to a object
function toExtensionsOb(arr) {
  var ob = {};

  if (typeof arr === "string") {
    arr = arr.split(",");
  }

  if (Array.isArray(arr)) {
    arr.filter(Boolean).forEach(function(ext) {
      ob[ext] = true;
    });
  } else {
    // Already in the correct format
    return arr;
  }

  return ob;
}

function hbsfy(file, opts) {
  var extensions = defaultExtensions;

  if (opts && opts.e) {
    extensions = toExtensionsOb(opts.e);
  }

  if (opts && opts.extensions) {
    extensions = toExtensionsOb(opts.extensions);
  }

  if (!extensions[file.split(".").pop()]) return through();

  var buffer = "";

  return through(function(chunk) {
    buffer += chunk.toString();
  },
  function() {
    var js = Handlebars.precompile(buffer);
    // Compile only with the runtime dependency.
    var compiled = "// hbsfy compiled Handlebars template\n";
    compiled += "var Handlebars = require('hbsfy/runtime');\n";
    compiled += "module.exports = Handlebars.template(" + js.toString() + ");\n";
    this.queue(compiled);
    this.queue(null);
  });

}

// Return new hbsfy transform with custom default options
hbsfy.configure = function(rootOpts) {
  return function(file, opts) {
    return hbsfy(file, xtend({}, rootOpts, opts));
  };
};

module.exports = hbsfy;

<|endoftext|>


<commit_before>var moduleName = 'ngSimpleGrid';

angular.module(moduleName, ['ng']).directive('simpleGrid', function($compile) {

  'ngInject';

  return {
    restrict: 'E',
    scope: {
      ngDataList: '=ngDataList',
      ngDataClick: '=ngDataClick',
      ngDataPagination: '=ngDataPagination',
      ngDataPaginationEnabled: '=ngDataPaginationEnabled',
      ngDataPaginationEvents: '=ngDataPaginationEvents',
      ngDataLength: '@ngDataLength',
      ngDataSingleOrdering: '@ngDataSingleOrdering',
      $ctrl: '=ngDataCtrl'
    },
    link: function($scope, elmt) {

      var Pagination = function(dataLength, fnEvent) {
        var length = [].map.call(dataLength.split(','), function(line) {
          return {value: line.trim(), label: line.trim()};
        });

        this.fnEvent = fnEvent;
        this.length = length;
        this.selectLength = length[0].value;
        this.page = 0;
        this.sortableMap = {};
      };

      Pagination.prototype = {

        /**
         * [Previous]
         */
        previous: function() {
          this.page--;
          this.fnEvent({
            status: 'previous',
            page: this.page,
            length: this.selectLength
          });
        },

        /**
         * [Next]
         */
        next: function() {
          this.page++;
          this.fnEvent({
            status: 'next',
            page: this.page,
            length: this.selectLength
          });
        },

        /**
         * [setSelectLength]
         */
        setSelectLength: function() {
          this.fnEvent({
            status: 'change-length',
            page: this.page,
            length: this.selectLength
          });
        },

        /**
         * To Camel Case
         * @param  {[String]} str
         * @return {[String]}
         */
        getCamelCase(str) {
          return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
            return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
          }).replace(/\s+/g, '');
        },

        /**
         * [sort]
         * @param  {[type]} column [description]
         * @return {[type]}        [description]
         */
        sortable: function(column) {
          if ($scope.ngDataSingleOrdering === 'true') {
            var statusTmp = {name: column, value: this.sortableMap[column]};
            this.sortableMap = {};
            this.sortableMap[statusTmp.name] = statusTmp.value;
          }
          if (this.sortableMap[column] === false) {
            delete this.sortableMap[column];
          } else {
            this.sortableMap[column] = this.sortableMap[column] === undefined ? true : !this.sortableMap[column];
          }
          var sortableMap = {};
          for (var key in this.sortableMap) {
            sortableMap[this.getCamelCase(key)] = this.sortableMap[key] ? 'desc' : 'asc';
          }
          this.fnEvent({
            status: 'sortable',
            page: this.page,
            length: this.selectLength,
            sortableMap: sortableMap
          });
        }
      };

      var $this = {

        /**
         * Main method
         * @return {[type]} [description]
         */
        main: function() {
          $this.init(function() {
            $this.load($this.addEventListeners);
          });
        },

        /**
         * Init method
         * @param Function
         * @return
         */
        init: function(callback) {
          $scope.pagination = new Pagination($scope.ngDataLength, $scope.ngDataPaginationEvents);
          callback && callback();
        },

        /**
         * Load method
         * @param Function
         * @return
         */
        load: function(callback) {
          $this.setTemplate();
          callback && callback();
        },

        /**
         * Add EventListeners method
         * @param
         * @return
         */
        addEventListeners: function() {
          $scope.getStatusSortable = $this.getStatusSortable.bind($this);
        },

        /**
         * Render method
         * @param  {[type]} template [description]
         * @return {[type]}          [description]
         */
        render: function(template) {
          $compile(elmt.html(template).contents())($scope);
        },

        /**
         * Get Status Sortable
         * @param  {[String]} columnName
         * @return {[String]}
         */
        getStatusSortable: function(columnName) {
          if ($scope.pagination.sortableMap.hasOwnProperty(columnName)) {
            return $scope.pagination.sortableMap[columnName] ? 'arrow_drop_down' : 'arrow_drop_up';
          }
        },

        /**
         * Get columns header
         * @return {[String]} [Template Header]
         */
        getColumnsHeader: function() {
          return [].map.call(elmt[0].querySelectorAll('header column'), function(data) {
            var sortable = '<md-icon>{{getStatusSortable(\'' + data.innerHTML + '\')}}</md-icon>';
            var column = '';
            column += '';
            column += data.dataset.sortable ? '
<md-icon>sort</md-icon>' + data.innerHTML + sortable + '
' : data.innerHTML;
            column += '	';
            return column;
          }).join('');
        },

        /**
         * Get columns body
         * @return {[String]} [Template Header]
         */
        getColumnsBody: function() {
          var line = '';
          line += '
';
          line += [].map.call(elmt[0].querySelectorAll('list column'), function(data) {
            var column = '';
            column += data.dataset.bind ? '{{$line.' + data.dataset.bind + '}}' : data.innerHTML;
            column += '	';
            return column;
          }).join('');
          line += '
';
          return line;
        },

        /**
         * Set template
         * @return {[type]} [description]
         */
        setTemplate: function() {
          var template = '';
          template += '
';
          template += '
';
          template += '
';
          template += '      ' + $this.getColumnsHeader();
          template += '
';
          template += '
';
          template += '
';
          template += '    ' + $this.getColumnsBody();
          template += '
';
          template += '
';

          template += '
';
          template += '
';
          template += '
Rows per page:
';
          template += '    <md-select class="md-table-select" ng-model="pagination.selectLength" ng-change="pagination.setSelectLength()">';
          template += '      <md-option ng-repeat="opt in pagination.length" ng-value="opt.value">';
          template += '        {{opt.label}}';
          template += '      </md-option>';
          template += '    </md-select>';
          template += '
';
          template += '
';
          template += '
1 - 25 of 26
';
          template += '    <button class="md-icon-button md-button md-ink-ripple" type="button" aria-label="Previous" ng-click="pagination.previous()" ng-disabled="!pagination.page">';
          template += '      <md-icon md-svg-icon="navigate-before.svg" class="ng-scope" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fit="" preserveAspectRatio="xMidYMid meet" focusable="false"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"></path></svg></md-icon>';
          template += '    </button>';
          template += '    <button class="md-icon-button md-button md-ink-ripple" type="button" aria-label="Next" ng-click="pagination.next()" ng-disabled="!ngDataPaginationEnabled()">';
          template += '      <md-icon md-svg-icon="navigate-next.svg" class="ng-scope" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fit="" preserveAspectRatio="xMidYMid meet" focusable="false"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></md-icon>';
          template += '    </button>';
          template += '
';
          template += '
';
          $this.render(template);
        }
      };

      $this.main();
    }
  };
});

module.exports = moduleName;
<commit_msg>Shipping Order in Navigation<commit_after>var moduleName = 'ngSimpleGrid';

angular.module(moduleName, ['ng']).directive('simpleGrid', function($compile) {

  'ngInject';

  return {
    restrict: 'E',
    scope: {
      ngDataList: '=ngDataList',
      ngDataClick: '=ngDataClick',
      ngDataPagination: '=ngDataPagination',
      ngDataPaginationEnabled: '=ngDataPaginationEnabled',
      ngDataPaginationEvents: '=ngDataPaginationEvents',
      ngDataLength: '@ngDataLength',
      ngDataSingleOrdering: '@ngDataSingleOrdering',
      $ctrl: '=ngDataCtrl'
    },
    link: function($scope, elmt) {

      var Pagination = function(dataLength, fnEvent) {
        var length = [].map.call(dataLength.split(','), function(line) {
          return {value: line.trim(), label: line.trim()};
        });

        this.fnEvent = fnEvent;
        this.length = length;
        this.selectLength = length[0].value;
        this.page = 0;
        this.sortableMap = {};
      };

      Pagination.prototype = {

        /**
         * [Previous]
         */
        previous: function() {
          this.page--;
          this.runFnEvent('previous');
        },

        /**
         * [Next]
         */
        next: function() {
          this.page++;
          this.runFnEvent('next');
        },

        /**
         * [Run Fn Event]
         */
        runFnEvent: function(event) {
          var sortableMap = {};
          for (var key in this.sortableMap) {
            sortableMap[this.getCamelCase(key)] = this.sortableMap[key] ? 'desc' : 'asc';
          }
          this.fnEvent({
            status: event,
            page: this.page,
            length: this.selectLength,
            sortableMap: sortableMap
          });
        },

        /**
         * [setSelectLength]
         */
        setSelectLength: function() {
          this.runFnEvent('change-length');
        },

        /**
         * To Camel Case
         * @param  {[String]} str
         * @return {[String]}
         */
        getCamelCase(str) {
          return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
            return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
          }).replace(/\s+/g, '');
        },

        /**
         * [sort]
         * @param  {[type]} column [description]
         * @return {[type]}        [description]
         */
        sortable: function(column) {
          if ($scope.ngDataSingleOrdering === 'true') {
            var statusTmp = {name: column, value: this.sortableMap[column]};
            this.sortableMap = {};
            this.sortableMap[statusTmp.name] = statusTmp.value;
          }
          if (this.sortableMap[column] === false) {
            delete this.sortableMap[column];
          } else {
            this.sortableMap[column] = this.sortableMap[column] === undefined ? true : !this.sortableMap[column];
          }
          this.runFnEvent('sortable');
        }
      };

      var $this = {

        /**
         * Main method
         * @return {[type]} [description]
         */
        main: function() {
          $this.init(function() {
            $this.load($this.addEventListeners);
          });
        },

        /**
         * Init method
         * @param Function
         * @return
         */
        init: function(callback) {
          $scope.pagination = new Pagination($scope.ngDataLength, $scope.ngDataPaginationEvents);
          callback && callback();
        },

        /**
         * Load method
         * @param Function
         * @return
         */
        load: function(callback) {
          $this.setTemplate();
          callback && callback();
        },

        /**
         * Add EventListeners method
         * @param
         * @return
         */
        addEventListeners: function() {
          $scope.getStatusSortable = $this.getStatusSortable.bind($this);
        },

        /**
         * Render method
         * @param  {[type]} template [description]
         * @return {[type]}          [description]
         */
        render: function(template) {
          $compile(elmt.html(template).contents())($scope);
        },

        /**
         * Get Status Sortable
         * @param  {[String]} columnName
         * @return {[String]}
         */
        getStatusSortable: function(columnName) {
          if ($scope.pagination.sortableMap.hasOwnProperty(columnName)) {
            return $scope.pagination.sortableMap[columnName] ? 'arrow_drop_down' : 'arrow_drop_up';
          }
        },

        /**
         * Get columns header
         * @return {[String]} [Template Header]
         */
        getColumnsHeader: function() {
          return [].map.call(elmt[0].querySelectorAll('header column'), function(data) {
            var sortable = '<md-icon>{{getStatusSortable(\'' + data.innerHTML + '\')}}</md-icon>';
            var column = '';
            column += '';
            column += data.dataset.sortable ? '
<md-icon>sort</md-icon>' + data.innerHTML + sortable + '
' : data.innerHTML;
            column += '	';
            return column;
          }).join('');
        },

        /**
         * Get columns body
         * @return {[String]} [Template Header]
         */
        getColumnsBody: function() {
          var line = '';
          line += '
';
          line += [].map.call(elmt[0].querySelectorAll('list column'), function(data) {
            var column = '';
            column += data.dataset.bind ? '{{$line.' + data.dataset.bind + '}}' : data.innerHTML;
            column += '	';
            return column;
          }).join('');
          line += '
';
          return line;
        },

        /**
         * Set template
         * @return {[type]} [description]
         */
        setTemplate: function() {
          var template = '';
          template += '
';
          template += '
';
          template += '
';
          template += '      ' + $this.getColumnsHeader();
          template += '
';
          template += '
';
          template += '
';
          template += '    ' + $this.getColumnsBody();
          template += '
';
          template += '
';

          template += '
';
          template += '
';
          template += '
Rows per page:
';
          template += '    <md-select class="md-table-select" ng-model="pagination.selectLength" ng-change="pagination.setSelectLength()">';
          template += '      <md-option ng-repeat="opt in pagination.length" ng-value="opt.value">';
          template += '        {{opt.label}}';
          template += '      </md-option>';
          template += '    </md-select>';
          template += '
';
          template += '
';
          template += '
1 - 25 of 26
';
          template += '    <button class="md-icon-button md-button md-ink-ripple" type="button" aria-label="Previous" ng-click="pagination.previous()" ng-disabled="!pagination.page">';
          template += '      <md-icon md-svg-icon="navigate-before.svg" class="ng-scope" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fit="" preserveAspectRatio="xMidYMid meet" focusable="false"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"></path></svg></md-icon>';
          template += '    </button>';
          template += '    <button class="md-icon-button md-button md-ink-ripple" type="button" aria-label="Next" ng-click="pagination.next()" ng-disabled="!ngDataPaginationEnabled()">';
          template += '      <md-icon md-svg-icon="navigate-next.svg" class="ng-scope" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fit="" preserveAspectRatio="xMidYMid meet" focusable="false"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></md-icon>';
          template += '    </button>';
          template += '
';
          template += '
';
          $this.render(template);
        }
      };

      $this.main();
    }
  };
});

module.exports = moduleName;
<|endoftext|>


<commit_before>'use strict'

const cangjie2radicals	= require('./cangjie.json')
const cangjie2hanzi			= require('./data/cangjie2hanzi.json')
const hanzi2cangjie			= require('./data/hanzi2cangjie.json')
const hanzi2definition	= require('./data/hanzi2definition.json')
const hanzi2frequency		= require('./data/hanzi2frequency.json')
const hanzi2pinyin			= require('./data/hanzi2pinyin.json')
const hanzi2strokes			= require('./data/hanzi2strokes.json')
const pinyin2hanzi			= require('./data/pinyin2hanzi.json')

const utils = require('pinyin-utils')

const find = (query, options = {}) => new Promise((yay, nay) => {
	let cangjie = hanzi2cangjie[query]	// Input type: hanzi
	let hanzi = cangjie2hanzi[query]		// Input type: cangjie
	let hanzies = pinyin2hanzi[utils.numberToMark(query)] // Input type: pinyin

	// Input is hanzi
	if (cangjie) {
		const hanzi = query
		const pinyin = hanzi2pinyin[hanzi]
		const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
		const strokes = hanzi2strokes[hanzi]
		const frequency = hanzi2frequency[hanzi]
		const definition = hanzi2definition[hanzi]
		yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
		return
	}

	// Input is cangjie
	if (hanzi) {
		cangjie = query
		const pinyin = hanzi2pinyin[hanzi]
		const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
		const strokes = hanzi2strokes[hanzi]
		const frequency = hanzi2frequency[hanzi]
		const definition = hanzi2definition[hanzi]
		yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
		return
	}

	// Input is pinyin
	if (hanzies) {
		const list = []
		for (hanzi of hanzies) {
			cangjie = hanzi2cangjie[hanzi]
			if (!cangjie) continue
			const pinyin = hanzi2pinyin[hanzi] || utils.numberToMark(query)
			const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
			const strokes = hanzi2strokes[hanzi]
			const frequency = hanzi2frequency[hanzi] || 9
			const definition = hanzi2definition[hanzi]
			list.push({hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition})
		}
		yay(list.sort((a, b) => a.frequency - b.frequency))
		return
	}

	nay('Unrecognized input type')
})

module.exports = find
<commit_msg>Remove rejection from promise<commit_after>'use strict'

const cangjie2radicals	= require('./cangjie.json')
const cangjie2hanzi			= require('./data/cangjie2hanzi.json')
const hanzi2cangjie			= require('./data/hanzi2cangjie.json')
const hanzi2definition	= require('./data/hanzi2definition.json')
const hanzi2frequency		= require('./data/hanzi2frequency.json')
const hanzi2pinyin			= require('./data/hanzi2pinyin.json')
const hanzi2strokes			= require('./data/hanzi2strokes.json')
const pinyin2hanzi			= require('./data/pinyin2hanzi.json')

const utils = require('pinyin-utils')

const find = (query, options = {}) => new Promise((yay, nay) => {
	let cangjie = hanzi2cangjie[query]	// Input type: hanzi
	let hanzi = cangjie2hanzi[query]		// Input type: cangjie
	let hanzies = pinyin2hanzi[utils.numberToMark(query)] // Input type: pinyin

	// Input is hanzi
	if (cangjie) {
		const hanzi = query
		const pinyin = hanzi2pinyin[hanzi]
		const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
		const strokes = hanzi2strokes[hanzi]
		const frequency = hanzi2frequency[hanzi]
		const definition = hanzi2definition[hanzi]
		yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
		return
	}

	// Input is cangjie
	if (hanzi) {
		cangjie = query
		const pinyin = hanzi2pinyin[hanzi]
		const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
		const strokes = hanzi2strokes[hanzi]
		const frequency = hanzi2frequency[hanzi]
		const definition = hanzi2definition[hanzi]
		yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
		return
	}

	// Input is pinyin
	if (hanzies) {
		const list = []
		for (hanzi of hanzies) {
			cangjie = hanzi2cangjie[hanzi]
			if (!cangjie) continue
			const pinyin = hanzi2pinyin[hanzi] || utils.numberToMark(query)
			const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
			const strokes = hanzi2strokes[hanzi]
			const frequency = hanzi2frequency[hanzi] || 9
			const definition = hanzi2definition[hanzi]
			list.push({hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition})
		}
		yay(list.sort((a, b) => a.frequency - b.frequency))
		return
	}

	yay([])
})

module.exports = find
<|endoftext|>


<commit_before>//TODO: add tex coords as uvs
function createCube(sx, sy, sz) {
    if (sx === undefined) sx = 1.0;
    if (sy === undefined) sy = sx;
    if (sz === undefined) sz = sx;

    var x = sx / 2;
    var y = sy / 2;
    var z = sz / 2;

    var positions = [
        //+x
        [ x, y, z],
        [ x,-y, z],
        [ x, y,-z],
        [ x,-y,-z],

        //-x
        [-x, y, z],
        [-x, y,-z],
        [-x,-y, z],
        [-x,-y,-z],

        //+y
        [ x, y, z],
        [ x, y,-z],
        [-x, y, z],
        [-x, y,-z],

        //-y
        [ x,-y, z],
        [-x,-y, z],
        [ x,-y,-z],
        [-x,-y,-z],

        //+z
        [ x, y, z],
        [-x, y, z],
        [ x,-y, z],
        [-x,-y, z],

        //-z
        [ x, y,-z],
        [ x,-y,-z],
        [-x, y,-z],
        [-x,-y,-z]
    ];

    var normals = [
        //+x
        [ 1.0, 0.0, 0.0 ],
        [ 1.0, 0.0, 0.0 ],
        [ 1.0, 0.0, 0.0 ],
        [ 1.0, 0.0, 0.0 ],

        //-x
        [-1.0, 0.0, 0.0 ],
        [-1.0, 0.0, 0.0 ],
        [-1.0, 0.0, 0.0 ],
        [-1.0, 0.0, 0.0 ],

        //+y
        [ 0.0, 1.0, 0.0 ],
        [ 0.0, 1.0, 0.0 ],
        [ 0.0, 1.0, 0.0 ],
        [ 0.0, 1.0, 0.0 ],

        //-y
        [ 0.0,-1.0, 0.0 ],
        [ 0.0,-1.0, 0.0 ],
        [ 0.0,-1.0, 0.0 ],
        [ 0.0,-1.0, 0.0 ],

        //+z
        [ 0.0, 0.0, 1.0 ],
        [ 0.0, 0.0, 1.0 ],
        [ 0.0, 0.0, 1.0 ],
        [ 0.0, 0.0, 1.0 ],

        //-z
        [ 0.0, 0.0,-1.0 ],
        [ 0.0, 0.0,-1.0 ],
        [ 0.0, 0.0,-1.0 ],
        [ 0.0, 0.0,-1.0 ]
    ];

    var uvs = [
        //+x
        [ 0, 0 ],
        [ 0, 1 ],
        [ 1, 0 ],
        [ 1, 1 ],

        //-x
        [ 1, 0 ],
        [ 0, 0 ],
        [ 1, 1 ],
        [ 0, 1 ],

        //+y
        [ 1, 1 ],
        [ 1, 0 ],
        [ 0, 1 ],
        [ 0, 0 ],

        //-y
        [ 1, 0],
        [ 0, 0],
        [ 1, 1],
        [ 0, 1],

        //+z
        [ 1, 0 ],
        [ 0, 0 ],
        [ 1, 1 ],
        [ 0, 1 ],

        //-z
        [ 0, 0 ],
        [ 0, 1 ],
        [ 1, 0 ],
        [ 1, 1 ]
    ];

    var cells = [
        [ 0, 1, 2], [ 2, 1, 3],
        [ 4, 5, 6], [ 6, 5, 7],
        [ 8, 9,10], [10, 9,11],
        [12,13,14], [14,13,15],
        [16,17,18], [18,17,19],
        [20,21,22], [22,21,23]
    ]

    return {
        positions: positions,
        normals: normals,
        uvs: uvs,
        cells: cells
    }
}

module.exports = createCube;
<commit_msg>Removed outdated comment<commit_after>function createCube(sx, sy, sz) {
    if (sx === undefined) sx = 1.0;
    if (sy === undefined) sy = sx;
    if (sz === undefined) sz = sx;

    var x = sx / 2;
    var y = sy / 2;
    var z = sz / 2;

    var positions = [
        //+x
        [ x, y, z],
        [ x,-y, z],
        [ x, y,-z],
        [ x,-y,-z],

        //-x
        [-x, y, z],
        [-x, y,-z],
        [-x,-y, z],
        [-x,-y,-z],

        //+y
        [ x, y, z],
        [ x, y,-z],
        [-x, y, z],
        [-x, y,-z],

        //-y
        [ x,-y, z],
        [-x,-y, z],
        [ x,-y,-z],
        [-x,-y,-z],

        //+z
        [ x, y, z],
        [-x, y, z],
        [ x,-y, z],
        [-x,-y, z],

        //-z
        [ x, y,-z],
        [ x,-y,-z],
        [-x, y,-z],
        [-x,-y,-z]
    ];

    var normals = [
        //+x
        [ 1.0, 0.0, 0.0 ],
        [ 1.0, 0.0, 0.0 ],
        [ 1.0, 0.0, 0.0 ],
        [ 1.0, 0.0, 0.0 ],

        //-x
        [-1.0, 0.0, 0.0 ],
        [-1.0, 0.0, 0.0 ],
        [-1.0, 0.0, 0.0 ],
        [-1.0, 0.0, 0.0 ],

        //+y
        [ 0.0, 1.0, 0.0 ],
        [ 0.0, 1.0, 0.0 ],
        [ 0.0, 1.0, 0.0 ],
        [ 0.0, 1.0, 0.0 ],

        //-y
        [ 0.0,-1.0, 0.0 ],
        [ 0.0,-1.0, 0.0 ],
        [ 0.0,-1.0, 0.0 ],
        [ 0.0,-1.0, 0.0 ],

        //+z
        [ 0.0, 0.0, 1.0 ],
        [ 0.0, 0.0, 1.0 ],
        [ 0.0, 0.0, 1.0 ],
        [ 0.0, 0.0, 1.0 ],

        //-z
        [ 0.0, 0.0,-1.0 ],
        [ 0.0, 0.0,-1.0 ],
        [ 0.0, 0.0,-1.0 ],
        [ 0.0, 0.0,-1.0 ]
    ];

    var uvs = [
        //+x
        [ 0, 0 ],
        [ 0, 1 ],
        [ 1, 0 ],
        [ 1, 1 ],

        //-x
        [ 1, 0 ],
        [ 0, 0 ],
        [ 1, 1 ],
        [ 0, 1 ],

        //+y
        [ 1, 1 ],
        [ 1, 0 ],
        [ 0, 1 ],
        [ 0, 0 ],

        //-y
        [ 1, 0],
        [ 0, 0],
        [ 1, 1],
        [ 0, 1],

        //+z
        [ 1, 0 ],
        [ 0, 0 ],
        [ 1, 1 ],
        [ 0, 1 ],

        //-z
        [ 0, 0 ],
        [ 0, 1 ],
        [ 1, 0 ],
        [ 1, 1 ]
    ];

    var cells = [
        [ 0, 1, 2], [ 2, 1, 3],
        [ 4, 5, 6], [ 6, 5, 7],
        [ 8, 9,10], [10, 9,11],
        [12,13,14], [14,13,15],
        [16,17,18], [18,17,19],
        [20,21,22], [22,21,23]
    ]

    return {
        positions: positions,
        normals: normals,
        uvs: uvs,
        cells: cells
    }
}

module.exports = createCube;
<|endoftext|>


<commit_before>'use strict'

const crypto = require('crypto')
const { deprecate } = require('util')

function _serialize(obj) {
  if (Array.isArray(obj)) {
    for (let i = 0; i < obj.length; i++) {
        obj[i] = _serialize(obj[i])
    }
    return obj
  } else if (typeof obj == 'object' && obj != null) {
      const sortedKeys = Object.keys(obj).sort()
      for (let i = 0; i < sortedKeys.length; i++) {
        const k = sortedKeys[i]
        obj[k] = _serialize(obj[k])
      }
      return JSON.stringify(obj, sortedKeys)
  }

  return obj
}

/**
 * Serializes a JSON object (not any random JS object).
 *
 * It should be noted that JS objects can have members of
 * specific type (e.g. function), that are not supported
 * by JSON.
 *
 * @param {Object} obj JSON object
 * @returns {String} stringified JSON object.
 */
function serialize (obj) {
  const ser = _serialize(obj)
  return (typeof ser !== 'string') ? JSON.stringify(ser) : ser
}

/**
 * Creates hash of given JSON object.
 *
 * @param {Object} obj JSON object
 * @param {String} hashAlgorithm hash algorithm (e.g. SHA256)
 * @param {String} encoding hash encoding (e.g. base64) or none for buffer
 * @see #serialize
 */
function digest (obj, hashAlgorithm, encoding) {
  const hash = crypto.createHash(hashAlgorithm)
  return hash.update(serialize(obj)).digest(encoding)
}

module.exports = {
  stringify: () => {
    throw new Error('"stringify()" is deprecated, use "serialize()" instead!')
  },
  serialize: serialize,
  digest: digest
}
<commit_msg>Fix standard formatting errors.<commit_after>'use strict'

const crypto = require('crypto')

function _serialize (obj) {
  if (Array.isArray(obj)) {
    for (let i = 0; i < obj.length; i++) {
      obj[i] = _serialize(obj[i])
    }
    return obj
  } else if (typeof obj === 'object' && obj != null) {
    const sortedKeys = Object.keys(obj).sort()
    for (let i = 0; i < sortedKeys.length; i++) {
      const k = sortedKeys[i]
      obj[k] = _serialize(obj[k])
    }
    return JSON.stringify(obj, sortedKeys)
  }

  return obj
}

/**
 * Serializes a JSON object (not any random JS object).
 *
 * It should be noted that JS objects can have members of
 * specific type (e.g. function), that are not supported
 * by JSON.
 *
 * @param {Object} obj JSON object
 * @returns {String} stringified JSON object.
 */
function serialize (obj) {
  const ser = _serialize(obj)
  return (typeof ser !== 'string') ? JSON.stringify(ser) : ser
}

/**
 * Creates hash of given JSON object.
 *
 * @param {Object} obj JSON object
 * @param {String} hashAlgorithm hash algorithm (e.g. SHA256)
 * @param {String} encoding hash encoding (e.g. base64) or none for buffer
 * @see #serialize
 */
function digest (obj, hashAlgorithm, encoding) {
  const hash = crypto.createHash(hashAlgorithm)
  return hash.update(serialize(obj)).digest(encoding)
}

module.exports = {
  stringify: () => {
    throw new Error('"stringify()" is deprecated, use "serialize()" instead!')
  },
  serialize: serialize,
  digest: digest
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('chai').assert;
var E = require('linq');
var dropElement = require('./src/utils').dropElement;
var ArrayEnumerator = require('./src/iterators/array');
require('sugar');
var BabyParse = require('babyparse');

var DataFrame = require('./src/dataframe');
var Index = require('./src/index');

/**
 * Main namespace for Data-Forge.
 *
 * Nodejs:
 *
 * 		npm install --save data-forge
 *
 * 		var dataForge = require('data-forge');
 *
 * Browser:
 *
 * 		bower install --save data-forge
 *
 * 		<script language="javascript" type="text/javascript" src="bower_components/data-forge/data-forge.js"></script>
 */
var dataForge = {

	DataFrame: DataFrame,
	BaseDataFrame: require('./src/basedataframe'),
	Series: require('./src/series'),
	BaseSeries: require('./src/baseseries'),
	Index: Index,
	BaseIndex: require('./src/baseindex'),

	/**
	 * Install a plugin in the dataForge namespace.
	 */
	use: function (plugin) {

		assert.isFunction(plugin, "Expected 'plugin' parameter to 'use' to be a function.");

		var self = this;
		plugin(self);
	},

	/**
	 * Deserialize a data frame from a JSON text string.
	 */
	fromJSON: function (jsonTextString) {
		assert.isString(jsonTextString, "Expected 'jsonTextString' parameter to 'dataForge.fromJSON' to be a string containing data encoded in the JSON format.");

		return new DataFrame({
				rows: JSON.parse(jsonTextString)
			});
	},

	//
	// Deserialize a data from a CSV text string.
	//
	fromCSV: function (csvTextString, config) {
		assert.isString(csvTextString, "Expected 'csvTextString' parameter to 'dataForge.fromCSV' to be a string containing data encoded in the CSV format.");

		var parsed = BabyParse.parse(csvTextString, config);
		var rows = parsed.data;

		/* Old csv parsing.
		var lines = csvTextString.split('\n');
		var rows = E
			.from(lines) // Ignore blank lines.
			.where(function (line) {
				return line.trim().length > 0;
			})
			.select(function (line) {
				return E
					.from(line.split(','))
					.select(function (col) {
						return col.trim();
					})
					.select(function (col) {
						if (col.length === 0) {
							return undefined;
						}
						else {
							return col;
						}
					})
					.toArray();
			})
			.toArray();
		*/

		if (rows.length === 0) {
			return new dataForge.DataFrame({ columnNames: [], rows: [] });
		}

		var columnNames = E.from(E.from(rows).first())
				.select(function (columnName) {
					return columnName.trim();
				})
				.toArray();

		var remaining = E.from(rows)
			.skip(1)
			.select(function (row) {
				return E.from(row)
					.select(function (cell) {
						return cell.trim();
					})
					.toArray()
			})
			.toArray();
		return new dataForge.DataFrame({
				columnNames: columnNames,
				rows: remaining
			});
	},

	/**
	 * Merge data frames by index or a particular column.
	 *
	 * @param {DataFrame} leftDataFrame - One data frame to merge.
	 * @param {DataFrame} rightDataFrame - The other data frame to merge.
	 * @param {string} [columnName] - The name of the column to merge on. Optional, when not specified merge is based on the index.
	 */
	merge: function (leftDataFrame, rightDataFrame, columnName) {
		assert.isObject(leftDataFrame, "Expected 'leftDataFrame' parameter to 'merge' to be an object.");
		assert.isObject(rightDataFrame, "Expected 'rightDataFrame' parameter to 'merge' to be an object.");

		if (columnName) {
			assert.isString(columnName, "Expected optional 'columnName' parameter to 'merge' to be a string.");
		}

		var leftColumnIndex = leftDataFrame.getColumnIndex(columnName);
		if (leftColumnIndex < 0) {
			throw new Error("Column with name '" + columnName + "' doesn't exist in 'leftDataFrame'.");
		}

		var rightColumnIndex = rightDataFrame.getColumnIndex(columnName);
		if (rightColumnIndex < 0) {
			throw new Error("Column with name '" + columnName + "' doesn't exist in 'rightColumnIndex'.");
		}

		var leftRows = leftDataFrame.toValues();
		var rightRows = rightDataFrame.toValues();

		var mergedColumnNames = [columnName]
			.concat(dropElement(leftDataFrame.getColumnNames(), leftColumnIndex))
			.concat(dropElement(rightDataFrame.getColumnNames(), rightColumnIndex));

		var rightMap = E.from(rightRows)
			.groupBy(function (rightRow) {
				return rightRow[rightColumnIndex];
			})
			.toObject(
				function (group) {
					return group.key();
				},
				function (group) {
					return group.getSource();
				}
			);

		var mergedValues = E.from(leftRows) // Merge values, drop index.
			.selectMany(function (leftRow) {
				var rightRows = rightMap[leftRow[leftColumnIndex]] || [];
				return E.from(rightRows)
					.select(function (rightRow) {
						var combined = [leftRow[leftColumnIndex]];

						for (var i = 0; i < leftRow.length; ++i) {
							if (i !== leftColumnIndex) {
								combined.push(leftRow[i]);
							}
						}

						for (var i = 0; i < rightRow.length; ++i) {
							if (i !== rightColumnIndex) {
								combined.push(rightRow[i]);
							}
						}

						return combined;
					});
			})
			.toArray();

		return new DataFrame({
			columnNames: mergedColumnNames,
			rows: {
				getIterator: function () {
					return new ArrayEnumerator(mergedValues);
				},
			},
		});
	},

	/**
	 * Concatenate multiple data frames into a single.
	 *
	 * @param {array} dataFrames - Array of data frames to concatenate.
	 */
	concat: function (dataFrames) {
		assert.isArray(dataFrames, "Expected 'dataFrames' parameter to 'dataForge.concat' to be an array of data frames.");

		var concatenateColumns = function () {
			return E.from(dataFrames)
				.selectMany(function (dataFrame) {
					return dataFrame.getColumnNames();
				})
				.distinct()
				.toArray();
		};

		return new DataFrame({
			columnNames: concatenateColumns(),
			rows: {
				getIterator: function () {
					var concatenatedColumns = concatenateColumns();
					return new ArrayEnumerator(
						E.from(dataFrames)
							.selectMany(function (dataFrame) {
								return dataFrame
									.remapColumns(concatenatedColumns)
									.toValues();
							})
							.toArray()
					);
				},
			},
			index: new Index({
				getIterator: function () {
					return new ArrayEnumerator(E.from(dataFrames)
						.selectMany(function (dataFrame) {
							return dataFrame.getIndex().toValues();
						})
						.toArray()
					);
				},
			}),
		});
	},
};

module.exports = dataForge;<commit_msg>Comment change.<commit_after>'use strict';

var assert = require('chai').assert;
var E = require('linq');
var dropElement = require('./src/utils').dropElement;
var ArrayEnumerator = require('./src/iterators/array');
require('sugar');
var BabyParse = require('babyparse');

var DataFrame = require('./src/dataframe');
var Index = require('./src/index');

/**
 * Main namespace for Data-Forge.
 *
 * Nodejs:
 *
 * 		npm install --save data-forge
 *
 * 		var dataForge = require('data-forge');
 *
 * Browser:
 *
 * 		bower install --save data-forge
 *
 * 		<script language="javascript" type="text/javascript" src="bower_components/data-forge/data-forge.js"></script>
 */
var dataForge = {

	DataFrame: DataFrame,
	BaseDataFrame: require('./src/basedataframe'),
	Series: require('./src/series'),
	BaseSeries: require('./src/baseseries'),
	Index: Index,
	BaseIndex: require('./src/baseindex'),

	/**
	 * Install a plugin in the dataForge namespace.
	 */
	use: function (plugin) {

		assert.isFunction(plugin, "Expected 'plugin' parameter to 'use' to be a function.");

		var self = this;
		plugin(self);
	},

	/**
	 * Deserialize a data frame from a JSON text string.
	 */
	fromJSON: function (jsonTextString) {
		assert.isString(jsonTextString, "Expected 'jsonTextString' parameter to 'dataForge.fromJSON' to be a string containing data encoded in the JSON format.");

		return new DataFrame({
				rows: JSON.parse(jsonTextString)
			});
	},

	//
	// Deserialize a data from a CSV text string.
	//
	fromCSV: function (csvTextString, config) {
		assert.isString(csvTextString, "Expected 'csvTextString' parameter to 'dataForge.fromCSV' to be a string containing data encoded in the CSV format.");

		var parsed = BabyParse.parse(csvTextString, config);
		var rows = parsed.data;

		/* Old csv parsing.
		var lines = csvTextString.split('\n');
		var rows = E
			.from(lines) // Ignore blank lines.
			.where(function (line) {
				return line.trim().length > 0;
			})
			.select(function (line) {
				return E
					.from(line.split(','))
					.select(function (col) {
						return col.trim();
					})
					.select(function (col) {
						if (col.length === 0) {
							return undefined;
						}
						else {
							return col;
						}
					})
					.toArray();
			})
			.toArray();
		*/

		if (rows.length === 0) {
			return new dataForge.DataFrame({ columnNames: [], rows: [] });
		}

		var columnNames = E.from(E.from(rows).first())
				.select(function (columnName) {
					return columnName.trim();
				})
				.toArray();

		var remaining = E.from(rows)
			.skip(1)
			.select(function (row) {
				return E.from(row)
					.select(function (cell) {
						return cell.trim();
					})
					.toArray()
			})
			.toArray();
		return new dataForge.DataFrame({
				columnNames: columnNames,
				rows: remaining
			});
	},

	/**
	 * Merge data-frames by index or a particular column.
	 *
	 * @param {DataFrame} leftDataFrame - One data frame to merge.
	 * @param {DataFrame} rightDataFrame - The other data frame to merge.
	 * @param {string} [columnName] - The name of the column to merge on. Optional, when not specified merge is based on the index.
	 */
	merge: function (leftDataFrame, rightDataFrame, columnName) {
		assert.isObject(leftDataFrame, "Expected 'leftDataFrame' parameter to 'merge' to be an object.");
		assert.isObject(rightDataFrame, "Expected 'rightDataFrame' parameter to 'merge' to be an object.");

		if (columnName) {
			assert.isString(columnName, "Expected optional 'columnName' parameter to 'merge' to be a string.");
		}

		var leftColumnIndex = leftDataFrame.getColumnIndex(columnName);
		if (leftColumnIndex < 0) {
			throw new Error("Column with name '" + columnName + "' doesn't exist in 'leftDataFrame'.");
		}

		var rightColumnIndex = rightDataFrame.getColumnIndex(columnName);
		if (rightColumnIndex < 0) {
			throw new Error("Column with name '" + columnName + "' doesn't exist in 'rightColumnIndex'.");
		}

		var leftRows = leftDataFrame.toValues();
		var rightRows = rightDataFrame.toValues();

		var mergedColumnNames = [columnName]
			.concat(dropElement(leftDataFrame.getColumnNames(), leftColumnIndex))
			.concat(dropElement(rightDataFrame.getColumnNames(), rightColumnIndex));

		var rightMap = E.from(rightRows)
			.groupBy(function (rightRow) {
				return rightRow[rightColumnIndex];
			})
			.toObject(
				function (group) {
					return group.key();
				},
				function (group) {
					return group.getSource();
				}
			);

		var mergedValues = E.from(leftRows) // Merge values, drop index.
			.selectMany(function (leftRow) {
				var rightRows = rightMap[leftRow[leftColumnIndex]] || [];
				return E.from(rightRows)
					.select(function (rightRow) {
						var combined = [leftRow[leftColumnIndex]];

						for (var i = 0; i < leftRow.length; ++i) {
							if (i !== leftColumnIndex) {
								combined.push(leftRow[i]);
							}
						}

						for (var i = 0; i < rightRow.length; ++i) {
							if (i !== rightColumnIndex) {
								combined.push(rightRow[i]);
							}
						}

						return combined;
					});
			})
			.toArray();

		return new DataFrame({
			columnNames: mergedColumnNames,
			rows: {
				getIterator: function () {
					return new ArrayEnumerator(mergedValues);
				},
			},
		});
	},

	/**
	 * Concatenate multiple data frames into a single.
	 *
	 * @param {array} dataFrames - Array of data frames to concatenate.
	 */
	concat: function (dataFrames) {
		assert.isArray(dataFrames, "Expected 'dataFrames' parameter to 'dataForge.concat' to be an array of data frames.");

		var concatenateColumns = function () {
			return E.from(dataFrames)
				.selectMany(function (dataFrame) {
					return dataFrame.getColumnNames();
				})
				.distinct()
				.toArray();
		};

		return new DataFrame({
			columnNames: concatenateColumns(),
			rows: {
				getIterator: function () {
					var concatenatedColumns = concatenateColumns();
					return new ArrayEnumerator(
						E.from(dataFrames)
							.selectMany(function (dataFrame) {
								return dataFrame
									.remapColumns(concatenatedColumns)
									.toValues();
							})
							.toArray()
					);
				},
			},
			index: new Index({
				getIterator: function () {
					return new ArrayEnumerator(E.from(dataFrames)
						.selectMany(function (dataFrame) {
							return dataFrame.getIndex().toValues();
						})
						.toArray()
					);
				},
			}),
		});
	},
};

module.exports = dataForge;<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var path = require('path'),
    util = require('util'),
    extend = util._extend;

var defaultOptions = {
    importBootstrapTheme: false,
    importBootstrapCSS: true,
    importBootstrapFont: true
};

module.exports = {
    name: 'ember-bootstrap',

    included: function included(app) {
        this._super.included(app);

        var emberCLIVersion = app.project.emberCLIVersion();
        if (emberCLIVersion < '0.0.41') {
            throw new Error('ember-cli-bootstrap requires ember-cli version 0.0.41 or greater.\n');
        }

        var options         = extend(defaultOptions, app.options['ember-bootstrap']);
        var bootstrapPath   = path.join(app.bowerDirectory, 'bootstrap/dist');

        // Import css from bootstrap
        if (options.importBootstrapTheme) {
            app.import(path.join(bootstrapPath, 'css/bootstrap-theme.css'));
        }

        if (options.importBootstrapCSS) {
            app.import(path.join(bootstrapPath, 'css/bootstrap.css'));
            app.import(path.join(bootstrapPath, 'css/bootstrap.css.map'), { destDir: 'assets' });
        }

        // Import glyphicons
        if (options.importBootstrapFont) {
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.eot'), { destDir: '/fonts' });
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.svg'), { destDir: '/fonts' });
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.ttf'), { destDir: '/fonts' });
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.woff'), { destDir: '/fonts' });
        }

    }
};<commit_msg>Imports assets from bootstrap's woff2 file<commit_after>/* jshint node: true */
'use strict';

var path = require('path'),
    util = require('util'),
    extend = util._extend;

var defaultOptions = {
    importBootstrapTheme: false,
    importBootstrapCSS: true,
    importBootstrapFont: true
};

module.exports = {
    name: 'ember-bootstrap',

    included: function included(app) {
        this._super.included(app);

        var emberCLIVersion = app.project.emberCLIVersion();
        if (emberCLIVersion < '0.0.41') {
            throw new Error('ember-cli-bootstrap requires ember-cli version 0.0.41 or greater.\n');
        }

        var options         = extend(defaultOptions, app.options['ember-bootstrap']);
        var bootstrapPath   = path.join(app.bowerDirectory, 'bootstrap/dist');

        // Import css from bootstrap
        if (options.importBootstrapTheme) {
            app.import(path.join(bootstrapPath, 'css/bootstrap-theme.css'));
        }

        if (options.importBootstrapCSS) {
            app.import(path.join(bootstrapPath, 'css/bootstrap.css'));
            app.import(path.join(bootstrapPath, 'css/bootstrap.css.map'), { destDir: 'assets' });
        }

        // Import glyphicons
        if (options.importBootstrapFont) {
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.eot'), { destDir: '/fonts' });
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.svg'), { destDir: '/fonts' });
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.ttf'), { destDir: '/fonts' });
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.woff'), { destDir: '/fonts' });
            app.import(path.join(bootstrapPath, 'fonts/glyphicons-halflings-regular.woff2'), { destDir: '/fonts' });
        }

    }
};<|endoftext|>


<commit_before>var params = require('./params.json')
params.genesisState = require('./genesisState.json')

module.exports = params
<commit_msg>export boostrap<commit_after>var params = require('./params.json')
params.genesisState = require('./genesisState.json')
params.bootstrapNodes = require('./bootstrapNodes.json')
module.exports = params
<|endoftext|>


<commit_before>'use strict';

// #region Imports
var fs = require('fs');
var Hashids = require('hashids');
var i18n = require('i18n');
var istype = require('type-check').typeCheck;
var lodash = require('lodash');
var path = require('path');
var requireNew = require('require-new');
// #endregion

function StaticBuild(pathOrOpt, opt) {
  // #region Options
  opt = lodash.assign({
    // Required
    path: (istype('String', pathOrOpt) ?
      String.prototype.trim.call(pathOrOpt) : ''),
    // Optional
    devmode: false,
    verbose: 0,
    restart: false,
    restartDelay: 0
  }, opt);
  // #endregion

  // #region Core
  this.basedir = process.cwd();
  this.data = {};
  this.datafile = '';
  this.destdir = 'dest';
  this.devmode = false;
  this.filename = 'staticbuild.json';
  this.filepath = '';
  this.path = process.cwd();
  this.sourcedir = 'src';
  this.verbose = false;
  this.version = '0.0.0';
  // #endregion

  // #region Hashids
  this.hashids = {
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz',
    minLength: 4,
    salt: 'BpoIsQlrssEz56uUbfgLu5KNBkoCJiyY'
  };
  // #endregion

  // #region Locales
  this.defaultLocale = 'en';
  this.locale = 'en';
  this.locales = ['en'];
  this.localesdir = 'locales';
  // #endregion

  // #region Web Host
  this.favicon = 'favicon.ico';
  this.host = process.env.HOST || undefined;
  this.port = process.env.PORT || 8080;
  this.restart = false;
  this.restartDelay = 0;
  // #endregion

  // #region Template
  this.template = {
    engine: 'nunjucks',
    extension: 'htm',
    extensionsfile: '',
    filtersfile: '',
    functionsfile: '',
    globals: {},
    globalsfile: '',
    indexfile: 'index',
    localsfile: '',
    options: {
      autoescape: true
    }
  };
  // #endregion

  // #region CSS
  this.css = {
    map: {
      enabled: true,
      inline: false
    },
    preprocessor: 'less'
  };
  // #endregion

  // #region Status
  this.info = [];
  this.warnings = [];
  // #endregion

  // #region Ignore Files
  this.ignore = [
    '.gitignore',
    '*.layout.htm',
    '*.part.htm',
    '*.map'
  ];
  // #endregion

  load(this, opt);

  StaticBuild.current = this;
}
module.exports = StaticBuild;

// #region Cache Busting

/** Appends a value to the file name, before the extension. */
function appendFilename(filepath, valueToAppend) {
  var pfile = path.parse(filepath);
  var result = Array.prototype.join.call([
    pfile.dir,
    '/',
    pfile.name,
    valueToAppend,
    pfile.ext
  ], '');
  return result;
}
StaticBuild.appendFilename = appendFilename;

function appendFilenamePart(filepath, part) {
  return StaticBuild.appendFilename(filepath, '-' + part);
}
StaticBuild.appendFilenamePart = appendFilenamePart;

StaticBuild.prototype.appendFilenameVersion = function (filepath, version) {
  var ev = this.encodeVersion(version);
  return StaticBuild.appendFilenamePart(filepath, ev);
};

StaticBuild.prototype.encodeVersion = function (version) {
  var verint = StaticBuild.versionToInt(version);
  return this.hashids.current.encode(verint);
};

function versionToInt(version) {
  version = String.prototype.trim.call(version);
  var parts = String.prototype.split.call(version, '.');
  var i, len = parts.length;
  for (i = 0; i < len; i++)
    parts[i] = lodash.padLeft(parts[i], 3, '0');
  version = parts.join('');
  return parseInt(version, 10);
}
StaticBuild.versionToInt = versionToInt;

// #endregion

// #region Load

function load(build, opt) {

  normalizePathOptions(opt);
  lodash.assign(build, opt);

  var result = {};
  if (!tryRequireNew(build.filepath, result))
    build.warnings.push(result.message);
  else {
    var data = result.obj;
    // priority loaders
    loadVerbosity(build, data);
    loadHashids(build, data);
    loadLocales(build, data);
    loadDirectories(build, data);

    // secondary loaders
    loadCss(build, data);
    loadDataFile(build, data);
    loadTemplates(build, data);
    loadWebHost(build, data);
  }
}

function loadCss(build, data) {
  // css
  var css = data.css;
  if (istype('Object', css)) {
    // preprocessor
    if (istype('String', css.preprocessor))
      build.css.preprocessor = css.preprocessor;
    if (istype('Object', css.map)) {
      // enabled
      if (istype('Boolean', css.map.enabled))
        build.css.map.enabled = css.map.enabled === true;
      // inline
      if (istype('Boolean', css.map.inline))
        build.css.map.inline = css.map.inline === true;
    }
  }
}

function loadDirectories(build, data) {
  // source | sourcedir
  if (istype('String', data.sourcedir))
    build.sourcedir = data.sourcedir;
  else if (istype('String', data.source))
    build.sourcedir = data.source;
  build.sourcedir = build.resolvePath(build.sourcedir);

  // dest | destdir
  if (istype('String', data.destdir))
    build.destdir = data.destdir;
  else if (istype('String', data.dest))
    build.destdir = data.dest;
  build.destdir = build.resolvePath(build.destdir);
}

function loadDataFile(build, cfgdata) {
  // data | datafile
  if (istype('String', cfgdata.data))
    build.datafile = cfgdata.data;
  else if (istype('String', cfgdata.datafile))
    build.datafile = cfgdata.datafile;
  else if (istype('Object', cfgdata.data)) {
    build.datafile = null;
    build.data = cfgdata.data;
  }
  if (!build.datafile)
    return;
  var result = {};
  var fullpath = build.resolvePath(build.datafile);
  if (tryRequireNew(fullpath, result))
    build.data = result.obj;
}

function loadHashids(build, data) {
  var ch = build.hashids;
  var hi = data.hashids;
  if (istype('Object', hi)) {
    // alphabet
    if (istype('String', hi.alphabet))
      ch.alphabet = hi.alphabet;
    // minLength
    if (istype('Number', hi.minLength))
      ch.minLength = hi.minLength;
    // salt
    if (istype('String', hi.salt))
      ch.salt = hi.salt;
  }
  build.hashids.current = new Hashids(
    ch.salt,
    ch.minLength,
    ch.alphabet
  );
}

function loadLocales(build, data) {
  // defaultLocale
  if (istype('String', data.defaultLocale)) {
    build.defaultLocale = data.defaultLocale;
    build.locale = build.defaultLocale;
  }
  // localesdir
  if (istype('String', data.localesdir))
    build.localesdir = data.localesdir;
  build.localesdir = build.resolvePath(build.localesdir);
  // TODO: Read locales array from directory if it exists.
  // locales
  if (istype('Array', data.locales))
    build.locales = Array.prototype.slice.call(data.locales);

  i18n.configure({
    extension: '.json',
    indent: '  ',
    locales: build.locales,
    defaultLocale: build.defaultLocale,
    directory: build.localesdir,
    objectNotation: true,
    prefix: '',
    updateFiles: true
  });
  i18n.setLocale(build.locale);
  currentLocale = build.locale;
}

function loadTemplates(build, data) {
  // template
  var tpl = data.template;
  if (istype('Object', tpl)) {

    // engine
    if (istype('String', tpl.engine))
      build.template.engine = tpl.engine;

    // extension
    if (istype('String', tpl.extension))
      build.template.extension = tpl.extension;

    // index | indexfile
    if (istype('String', tpl.index))
      build.template.indexfile = tpl.index;
    else if (istype('String', tpl.indexfile))
      build.template.indexfile = tpl.indexfile;

    // extensions, filters and functions.
    if (istype('String', tpl.extensions))
      build.template.extensionsfile = tpl.extensions;

    if (istype('String', tpl.filters))
      build.template.filtersfile = tpl.filters;

    if (istype('String', tpl.functions))
      build.template.functionsfile = tpl.functions;

    // globals | globalfiles
    if (istype('String', tpl.globals))
      build.template.globalsfile = tpl.globals;
    else if (istype('String', tpl.globalsfile))
      build.template.globalsfile = tpl.globalsfile;

    // locals | localsfile
    if (tpl.locals === true || tpl.localsfile === true)
      build.template.localsfile = '<filename>.+(js|json)';
    if (istype('String', tpl.locals))
      build.template.localsfile = tpl.locals;
    else if (istype('String', tpl.localsfile))
      build.template.localsfile = tpl.localsfile;

    // options
    if (istype('Object', tpl.options))
      build.template.options = lodash.cloneDeep(tpl.options);
  }
  loadTemplateGlobals(build);
}

function loadTemplateGlobals(build) {
  var tpl = build.template;
  var result = {
    extensions: {},
    filters: {},
    functions: {},
    globals: {}
  };
  // Read extensions, filters and functions.
  if (tpl.extensionsfile)
    tryRequireNew(
      build.resolvePath(tpl.extensionsfile), result.extensions);
  if (tpl.filtersfile)
    tryRequireNew(
      build.resolvePath(tpl.filtersfile), result.filters);
  if (tpl.functionsfile)
    tryRequireNew(
      build.resolvePath(tpl.functionsfile), result.functions);
  // Read globalsfile.
  if (tpl.globalsfile)
    tryRequireNew(
      build.resolvePath(tpl.globalsfile), result.globals);
  // Merge extensions, filters and functions into build.template.globals.
  var g = tpl.globals = lodash.merge(tpl.globals || {}, result.globals.obj);
  g.extensions = lodash.merge(g.extensions || {}, result.extensions.obj);
  g.filters = lodash.merge(g.filters || {}, result.filters.obj);
  g.functions = lodash.merge(g.functions || {}, result.functions.obj);
}

function loadVerbosity(build, data) {
  // verbose
  // - Can only be turned ON from build, not off.
  if (data.verbose === true || data.verbose > 0)
    build.verbose = data.verbose;
}

function loadWebHost(build, data) {
  // host
  if (istype('String', data.host))
    build.host = data.host;
  // port
  if (istype('Number', data.port))
    build.port = data.port;
  // favicon
  if (istype('String', data.favicon))
    build.favicon = data.favicon;
}

// #endregion

// #region Locales

var currentLocale;

StaticBuild.prototype.translate = function (str, etc) {
  /*jshint unused:false*/
  var args = Array.prototype.slice.call(arguments);
  updateLocaleIfChanged(this);
  return i18n.__.apply(i18n, args);
};

StaticBuild.prototype.translateNumeric = function (singular, plural, value) {
  /*jshint unused:false*/
  var args = Array.prototype.slice.call(arguments);
  updateLocaleIfChanged(this);
  return i18n.__n.apply(i18n, args);
};

function updateLocaleIfChanged(build) {
  if (build.locale === currentLocale)
    return;
  i18n.setLocale(build.locale);
  currentLocale = build.locale;
}

// #endregion

// #region Options

function fileFromPathOption(opt) {
  if (opt.filepath !== undefined)
    return true;
  if (opt.path === undefined)
    return false;
  try {
    var stat = fs.statSync(opt.path);
    if (stat.isFile()) {
      opt.filepath = path.resolve(opt.path);
      return true;
    }
  } catch (err) {
  }
  return false;
}

function normalizePathOptions(opt) {
  if (fileFromPathOption(opt)) {
    opt.basedir = path.resolve(path.dirname(opt.filepath));
    opt.filename = path.basename(opt.filepath);
  }
  else if (opt.path !== undefined) {
    opt.filename = opt.filename || 'staticbuild.json';
    opt.basedir = path.resolve(opt.basedir || process.cwd(), opt.path);
    opt.filepath = path.join(opt.basedir, opt.filename);
  }
}

// #endregion

// #region Paths

StaticBuild.prototype.getWatchPaths = function () {
  var paths = [
    this.filepath
  ];
  var tpl = this.template;
  if (tpl.globalsfile)
    paths.push(this.resolvePath(tpl.globalsfile));
  if (tpl.extensionsfile)
    paths.push(this.resolvePath(tpl.extensionsfile));
  if (tpl.filtersfile)
    paths.push(this.resolvePath(tpl.filtersfile));
  if (tpl.functionsfile)
    paths.push(this.resolvePath(tpl.functionsfile));
  if (this.datafile)
    paths.push(this.resolvePath(this.datafile));
  return paths;
};

StaticBuild.prototype.resolvePath = function (to) {
  return path.resolve(this.basedir, to);
};

StaticBuild.prototype.resolveSrcPath = function (to) {
  return path.resolve(this.sourcedir, to);
};

function tryRequireNew(filepath, result) {
  if (filepath === undefined || filepath === null)
    return false;
  try {
    result.obj = requireNew(filepath);
    return true;
  } catch (err) {
    if (err.code === 'MODULE_NOT_FOUND')
      result.message = 'File not found: ' + filepath;
    else
      result.message = err.toString();
  }
  return false;
}
StaticBuild.tryRequireNew = tryRequireNew;

// #endregion

// #region Write

StaticBuild.prototype.writeFileSync = function (tofile) {
  var result;
  var INDENT = 2;

  var config = lodash.cloneDeep(this);

  // Delete object data, make absolute paths relative.
  if (config.verbose !== true && config.verbose < 1)
    delete config.verbose;

  delete config.devmode;

  config.sourcedir = path.relative(config.basedir, config.sourcedir);
  delete config.basedir;
  delete config.path;

  config.data = config.datafile;
  delete config.datafile;

  config.localesdir = path.relative(config.basedir, config.localesdir);
  delete config.locale;

  delete config.filepath;
  delete config.filename;

  delete config.restart;
  delete config.restartDelay;

  delete config.template.globals;

  delete config.warnings;

  result = JSON.stringify(config, null, INDENT);

  fs.writeFileSync(tofile, result);
};

// #endregion
<commit_msg>Formatting.<commit_after>'use strict';

// #region Imports
var fs = require('fs');
var Hashids = require('hashids');
var i18n = require('i18n');
var istype = require('type-check').typeCheck;
var lodash = require('lodash');
var path = require('path');
var requireNew = require('require-new');
// #endregion

function StaticBuild(pathOrOpt, opt) {
  // #region Options
  opt = lodash.assign({
    // Required
    path: (istype('String', pathOrOpt) ?
      String.prototype.trim.call(pathOrOpt) : ''),
    // Optional
    devmode: false,
    verbose: 0,
    restart: false,
    restartDelay: 0
  }, opt);
  // #endregion

  // #region Core
  this.basedir = process.cwd();
  this.data = {};
  this.datafile = '';
  this.destdir = 'dest';
  this.devmode = false;
  this.filename = 'staticbuild.json';
  this.filepath = '';
  this.path = process.cwd();
  this.sourcedir = 'src';
  this.verbose = false;
  this.version = '0.0.0';
  // #endregion

  // #region Hashids
  this.hashids = {
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz',
    minLength: 4,
    salt: 'BpoIsQlrssEz56uUbfgLu5KNBkoCJiyY'
  };
  // #endregion

  // #region Locales
  this.defaultLocale = 'en';
  this.locale = 'en';
  this.locales = ['en'];
  this.localesdir = 'locales';
  // #endregion

  // #region Web Host
  this.favicon = 'favicon.ico';
  this.host = process.env.HOST || undefined;
  this.port = process.env.PORT || 8080;
  this.restart = false;
  this.restartDelay = 0;
  // #endregion

  // #region Template
  this.template = {
    engine: 'nunjucks',
    extension: 'htm',
    extensionsfile: '',
    filtersfile: '',
    functionsfile: '',
    globals: {},
    globalsfile: '',
    indexfile: 'index',
    localsfile: '',
    options: {
      autoescape: true
    }
  };
  // #endregion

  // #region CSS
  this.css = {
    map: {
      enabled: true,
      inline: false
    },
    preprocessor: 'less'
  };
  // #endregion

  // #region Status
  this.info = [];
  this.warnings = [];
  // #endregion

  // #region Ignore Files
  this.ignore = [
    '.gitignore',
    '*.layout.htm',
    '*.part.htm',
    '*.map'
  ];
  // #endregion

  load(this, opt);

  StaticBuild.current = this;
}
module.exports = StaticBuild;

// #region Cache Busting

/** Appends a value to the file name, before the extension. */
function appendFilename(filepath, valueToAppend) {
  var pfile = path.parse(filepath);
  var result = Array.prototype.join.call([
    pfile.dir,
    '/',
    pfile.name,
    valueToAppend,
    pfile.ext
  ], '');
  return result;
}
StaticBuild.appendFilename = appendFilename;

function appendFilenamePart(filepath, part) {
  return StaticBuild.appendFilename(filepath, '-' + part);
}
StaticBuild.appendFilenamePart = appendFilenamePart;

StaticBuild.prototype.appendFilenameVersion =
function (filepath, version) {
  var ev = this.encodeVersion(version);
  return StaticBuild.appendFilenamePart(filepath, ev);
};

StaticBuild.prototype.encodeVersion =
function (version) {
  var verint = StaticBuild.versionToInt(version);
  return this.hashids.current.encode(verint);
};

function versionToInt(version) {
  version = String.prototype.trim.call(version);
  var parts = String.prototype.split.call(version, '.');
  var i, len = parts.length;
  for (i = 0; i < len; i++)
    parts[i] = lodash.padLeft(parts[i], 3, '0');
  version = parts.join('');
  return parseInt(version, 10);
}
StaticBuild.versionToInt = versionToInt;

// #endregion

// #region Load

function load(build, opt) {

  normalizePathOptions(opt);
  lodash.assign(build, opt);

  var result = {};
  if (!tryRequireNew(build.filepath, result))
    build.warnings.push(result.message);
  else {
    var data = result.obj;
    // priority loaders
    loadVerbosity(build, data);
    loadHashids(build, data);
    loadLocales(build, data);
    loadDirectories(build, data);

    // secondary loaders
    loadCss(build, data);
    loadDataFile(build, data);
    loadTemplates(build, data);
    loadWebHost(build, data);
  }
}

function loadCss(build, data) {
  // css
  var css = data.css;
  if (istype('Object', css)) {
    // preprocessor
    if (istype('String', css.preprocessor))
      build.css.preprocessor = css.preprocessor;
    if (istype('Object', css.map)) {
      // enabled
      if (istype('Boolean', css.map.enabled))
        build.css.map.enabled = css.map.enabled === true;
      // inline
      if (istype('Boolean', css.map.inline))
        build.css.map.inline = css.map.inline === true;
    }
  }
}

function loadDirectories(build, data) {
  // source | sourcedir
  if (istype('String', data.sourcedir))
    build.sourcedir = data.sourcedir;
  else if (istype('String', data.source))
    build.sourcedir = data.source;
  build.sourcedir = build.resolvePath(build.sourcedir);

  // dest | destdir
  if (istype('String', data.destdir))
    build.destdir = data.destdir;
  else if (istype('String', data.dest))
    build.destdir = data.dest;
  build.destdir = build.resolvePath(build.destdir);
}

function loadDataFile(build, cfgdata) {
  // data | datafile
  if (istype('String', cfgdata.data))
    build.datafile = cfgdata.data;
  else if (istype('String', cfgdata.datafile))
    build.datafile = cfgdata.datafile;
  else if (istype('Object', cfgdata.data)) {
    build.datafile = null;
    build.data = cfgdata.data;
  }
  if (!build.datafile)
    return;
  var result = {};
  var fullpath = build.resolvePath(build.datafile);
  if (tryRequireNew(fullpath, result))
    build.data = result.obj;
}

function loadHashids(build, data) {
  var ch = build.hashids;
  var hi = data.hashids;
  if (istype('Object', hi)) {
    // alphabet
    if (istype('String', hi.alphabet))
      ch.alphabet = hi.alphabet;
    // minLength
    if (istype('Number', hi.minLength))
      ch.minLength = hi.minLength;
    // salt
    if (istype('String', hi.salt))
      ch.salt = hi.salt;
  }
  build.hashids.current = new Hashids(
    ch.salt,
    ch.minLength,
    ch.alphabet
  );
}

function loadLocales(build, data) {
  // defaultLocale
  if (istype('String', data.defaultLocale)) {
    build.defaultLocale = data.defaultLocale;
    build.locale = build.defaultLocale;
  }
  // localesdir
  if (istype('String', data.localesdir))
    build.localesdir = data.localesdir;
  build.localesdir = build.resolvePath(build.localesdir);
  // TODO: Read locales array from directory if it exists.
  // locales
  if (istype('Array', data.locales))
    build.locales = Array.prototype.slice.call(data.locales);

  i18n.configure({
    extension: '.json',
    indent: '  ',
    locales: build.locales,
    defaultLocale: build.defaultLocale,
    directory: build.localesdir,
    objectNotation: true,
    prefix: '',
    updateFiles: true
  });
  i18n.setLocale(build.locale);
  currentLocale = build.locale;
}

function loadTemplates(build, data) {
  // template
  var tpl = data.template;
  if (istype('Object', tpl)) {

    // engine
    if (istype('String', tpl.engine))
      build.template.engine = tpl.engine;

    // extension
    if (istype('String', tpl.extension))
      build.template.extension = tpl.extension;

    // index | indexfile
    if (istype('String', tpl.index))
      build.template.indexfile = tpl.index;
    else if (istype('String', tpl.indexfile))
      build.template.indexfile = tpl.indexfile;

    // extensions, filters and functions.
    if (istype('String', tpl.extensions))
      build.template.extensionsfile = tpl.extensions;

    if (istype('String', tpl.filters))
      build.template.filtersfile = tpl.filters;

    if (istype('String', tpl.functions))
      build.template.functionsfile = tpl.functions;

    // globals | globalfiles
    if (istype('String', tpl.globals))
      build.template.globalsfile = tpl.globals;
    else if (istype('String', tpl.globalsfile))
      build.template.globalsfile = tpl.globalsfile;

    // locals | localsfile
    if (tpl.locals === true || tpl.localsfile === true)
      build.template.localsfile = '<filename>.+(js|json)';
    if (istype('String', tpl.locals))
      build.template.localsfile = tpl.locals;
    else if (istype('String', tpl.localsfile))
      build.template.localsfile = tpl.localsfile;

    // options
    if (istype('Object', tpl.options))
      build.template.options = lodash.cloneDeep(tpl.options);
  }
  loadTemplateGlobals(build);
}

function loadTemplateGlobals(build) {
  var tpl = build.template;
  var result = {
    extensions: {},
    filters: {},
    functions: {},
    globals: {}
  };
  // Read extensions, filters and functions.
  if (tpl.extensionsfile)
    tryRequireNew(
      build.resolvePath(tpl.extensionsfile), result.extensions);
  if (tpl.filtersfile)
    tryRequireNew(
      build.resolvePath(tpl.filtersfile), result.filters);
  if (tpl.functionsfile)
    tryRequireNew(
      build.resolvePath(tpl.functionsfile), result.functions);
  // Read globalsfile.
  if (tpl.globalsfile)
    tryRequireNew(
      build.resolvePath(tpl.globalsfile), result.globals);
  // Merge extensions, filters and functions into build.template.globals.
  var g = tpl.globals = lodash.merge(tpl.globals || {}, result.globals.obj);
  g.extensions = lodash.merge(g.extensions || {}, result.extensions.obj);
  g.filters = lodash.merge(g.filters || {}, result.filters.obj);
  g.functions = lodash.merge(g.functions || {}, result.functions.obj);
}

function loadVerbosity(build, data) {
  // verbose
  // - Can only be turned ON from build, not off.
  if (data.verbose === true || data.verbose > 0)
    build.verbose = data.verbose;
}

function loadWebHost(build, data) {
  // host
  if (istype('String', data.host))
    build.host = data.host;
  // port
  if (istype('Number', data.port))
    build.port = data.port;
  // favicon
  if (istype('String', data.favicon))
    build.favicon = data.favicon;
}

// #endregion

// #region Locales

var currentLocale;

StaticBuild.prototype.translate =
function (str, etc) {
  /*jshint unused:false*/
  var args = Array.prototype.slice.call(arguments);
  updateLocaleIfChanged(this);
  return i18n.__.apply(i18n, args);
};

StaticBuild.prototype.translateNumeric =
function (singular, plural, value) {
  /*jshint unused:false*/
  var args = Array.prototype.slice.call(arguments);
  updateLocaleIfChanged(this);
  return i18n.__n.apply(i18n, args);
};

function updateLocaleIfChanged(build) {
  if (build.locale === currentLocale)
    return;
  i18n.setLocale(build.locale);
  currentLocale = build.locale;
}

// #endregion

// #region Options

function fileFromPathOption(opt) {
  if (opt.filepath !== undefined)
    return true;
  if (opt.path === undefined)
    return false;
  try {
    var stat = fs.statSync(opt.path);
    if (stat.isFile()) {
      opt.filepath = path.resolve(opt.path);
      return true;
    }
  } catch (err) {
  }
  return false;
}

function normalizePathOptions(opt) {
  if (fileFromPathOption(opt)) {
    opt.basedir = path.resolve(path.dirname(opt.filepath));
    opt.filename = path.basename(opt.filepath);
  }
  else if (opt.path !== undefined) {
    opt.filename = opt.filename || 'staticbuild.json';
    opt.basedir = path.resolve(opt.basedir || process.cwd(), opt.path);
    opt.filepath = path.join(opt.basedir, opt.filename);
  }
}

// #endregion

// #region Paths

StaticBuild.prototype.getWatchPaths =
function () {
  var paths = [
    this.filepath
  ];
  var tpl = this.template;
  if (tpl.globalsfile)
    paths.push(this.resolvePath(tpl.globalsfile));
  if (tpl.extensionsfile)
    paths.push(this.resolvePath(tpl.extensionsfile));
  if (tpl.filtersfile)
    paths.push(this.resolvePath(tpl.filtersfile));
  if (tpl.functionsfile)
    paths.push(this.resolvePath(tpl.functionsfile));
  if (this.datafile)
    paths.push(this.resolvePath(this.datafile));
  return paths;
};

StaticBuild.prototype.resolvePath =
function (to) {
  return path.resolve(this.basedir, to);
};

StaticBuild.prototype.resolveSrcPath =
function (to) {
  return path.resolve(this.sourcedir, to);
};

function tryRequireNew(filepath, result) {
  if (filepath === undefined || filepath === null)
    return false;
  try {
    result.obj = requireNew(filepath);
    return true;
  } catch (err) {
    if (err.code === 'MODULE_NOT_FOUND')
      result.message = 'File not found: ' + filepath;
    else
      result.message = err.toString();
  }
  return false;
}
StaticBuild.tryRequireNew = tryRequireNew;

// #endregion

// #region Write

StaticBuild.prototype.writeFileSync =
function (tofile) {
  var result;
  var INDENT = 2;

  var config = lodash.cloneDeep(this);

  // Delete object data, make absolute paths relative.
  if (config.verbose !== true && config.verbose < 1)
    delete config.verbose;

  delete config.devmode;

  config.sourcedir = path.relative(config.basedir, config.sourcedir);
  delete config.basedir;
  delete config.path;

  config.data = config.datafile;
  delete config.datafile;

  config.localesdir = path.relative(config.basedir, config.localesdir);
  delete config.locale;

  delete config.filepath;
  delete config.filename;

  delete config.restart;
  delete config.restartDelay;

  delete config.template.globals;

  delete config.warnings;

  result = JSON.stringify(config, null, INDENT);

  fs.writeFileSync(tofile, result);
};

// #endregion
<|endoftext|>


<commit_before>#!/usr/bin/env electron

var path = require('path')
var fs = require('fs')
var minimist = require('minimist')
var electron = require('electron')
var app = electron.app
var Menu = electron.Menu
var BrowserWindow = electron.BrowserWindow

var mkdirp = require('mkdirp')
var level = require('level')
var sublevel = require('subleveldown')
var osmdb = require('osm-p2p')
var series = require('run-series')
var semver = require('semver')
var rimraf = require('rimraf')
var MediaStore = require('safe-fs-blob-store')
var styles = require('mapeo-styles')

var menuTemplate = require('./src/menu')
var createServer = require('./src/server.js')
var createTileServer = require('./src/tile-server.js')

var appSettings = require('./app-settings.json')
var installStatsIndex = require('./src/lib/osm-stats')
var userConfig = require('./src/lib/user-config')
var TileImporter = require('./src/lib/tile-importer')
var importer = require('./src/lib/importer')
var locale = require('./src/lib/locale')
var i18n = require('./src/lib/i18n')
var exportData = require('./src/lib/export-data')

if (require('electron-squirrel-startup')) {
  process.exit(0)
}

// HACK: enable GPU graphics acceleration on some older laptops
app.commandLine.appendSwitch('ignore-gpu-blacklist', 'true')

var APP_NAME = app.getName()
var IS_TEST = process.env.NODE_ENV === 'test'

var log = require('./src/lib/log').Node()

var win = null

// Listen for app-ready event
var appIsReady = false
app.once('ready', function () {
  appIsReady = true
})

// Set up global node exception handler
handleUncaughtExceptions()
log('[STARTUP] Listening for uncaught exceptions')

// Path to `userData`, operating system specific, see
// https://github.com/atom/electron/blob/master/docs/api/app.md#appgetpathname
var userDataPath = app.getPath('userData')

var argv = minimist(process.argv.slice(2), {
  default: {
    port: 5000,
    datadir: path.join(userDataPath, 'data'),
    tileport: 5005
  },
  boolean: [ 'headless', 'debug' ],
  alias: {
    p: 'port',
    t: 'tileport',
    d: 'debug'
  }
})

function startupMsg (txt) {
  return function (done) {
    console.log('[STARTUP] ' + txt)
    done()
  }
}

startupMsg('Unpacking Styles')
mkdirp(path.join(userDataPath, 'styles'), function (err) {
  if (err) log(err)
  mkdirp(path.join(userDataPath, 'presets'), function (err) {
    if (err) log(err)
    styles.unpackIfNew(userDataPath, function (err) {
      if (err) log('[ERROR] while unpacking styles:', err)
    })
  })
})

// The app startup sequence
series([
  // versionCheckIndexes,
  startupMsg('Checked indexes version is up-to-date'),

  initOsmDb,
  startupMsg('Initialized osm-p2p'),

  createServers,
  startupMsg('Started osm and tile servers'),

  createMainWindow,
  startupMsg('Created app window')
], function (err) {
  if (err) log('STARTUP FAILED', err)
  else log('STARTUP success!')
})

function initOsmDb (done) {
  var osm = osmdb(argv.datadir)
  log('loading datadir', argv.datadir)

  var idb = sublevel(osm.index, 'stats')
  osm.core.use('stats', installStatsIndex(idb))

  var media = MediaStore(path.join(argv.datadir, 'media'))
  app.osm = osm
  app.media = media
  app.importer = importer(osm)
  app.tiles = TileImporter(userDataPath)

  log('preparing osm indexes..')

  done()
}

// Regenerate osm indexes if needed
function versionCheckIndexes (done) {
  var dir = argv.datadir
  var idxDb = level(path.join(dir, 'index'))
  var versionDb = sublevel(idxDb, 'versions')

  versionDb.get('kdb-index', function (err, version) {
    if (err && err.notFound) version = '1.0.0'
    else if (err) return versionDb.close(function (_) { done(err) }) // cleanup!

    idxDb.close(function (_) {
      if (semver.major(appSettings.indexes.kdb.version) > semver.major(version)) {
        log('kdb index must be regenerated (have=' + version + ', needed=' + appSettings.indexes.kdb.version + ')')

        // TODO(noffle): in the future, let's be smarter about selectively wiping sub-indexes as needed
        series([wipeAllIndexes, writeUpToDateVersions], done)
      } else {
        log('indexes are up to date!')
        done()
      }
    })
  })

  function wipeAllIndexes (fin) {
    // swallow errors; the indexes might not exist in the first place
    console.log('wiping indexes')
    series([
      function (done) {
        rimraf(path.join(dir, 'index'), function (_) { done() })
      },
      function (done) {
        fs.unlink(path.join(dir, 'kdb'), function (_) { done() })
      }
    ], fin)
  }

  function writeUpToDateVersions (fin) {
    console.log('writing new index versions')
    var idxDb = level(path.join(dir, 'index'))
    var versionDb = sublevel(idxDb, 'versions')
    series([
      function (done) { versionDb.put('kdb-index', appSettings.indexes.kdb.version, done) },
      idxDb.close.bind(idxDb)
    ], fin)
  }
}

function createServers (done) {
  app.server = createServer(app.osm, app.media, { staticRoot: userDataPath })

  var pending = 2

  app.server.listen(argv.port, '127.0.0.1', function () {
    global.osmServerHost = '127.0.0.1:' + app.server.address().port
    log(global.osmServerHost)
    if (--pending === 0) done()
  })

  var tileServer = createTileServer()
  tileServer.listen(argv.tileport, function () {
    log('tile server listening on :', tileServer.address().port)
    if (--pending === 0) done()
  })
}

function createMainWindow (done) {
  app.translations = locale.load()
  if (!argv.headless) {
    if (!appIsReady) {
      app.once('ready', ready)
    } else {
      ready()
    }

    app.on('before-quit', function () {
      app.server.mapeo.api.close(function () {
        app.server.close()
      })
    })

    // Quit when all windows are closed.
    app.on('window-all-closed', function () {
      app.quit()
    })
  } else {
    done()
  }

  function ready () {
    if (argv.headless) return

    var INDEX = 'file://' + path.resolve(__dirname, './index.html')
    if (!win) {
      win = new BrowserWindow({
        title: APP_NAME,
        show: false,
        icon: path.resolve(__dirname, 'static', 'mapeo_256x256.png')
      })
      win.once('ready-to-show', () => win.show())
      if (IS_TEST) win.setSize(1000, 800, false)
      else win.maximize()
    }

    if (argv.debug) win.webContents.openDevTools()
    win.loadURL(INDEX)

    var ipc = electron.ipcMain

    ipc.on('get-user-data', function (event, type) {
      var data = userConfig.getSettings(type)
      if (!data) console.warn('unhandled event', type)
      event.returnValue = data
    })

    app.importer.on('import-error', function (err, filename) {
      win.webContents.send('import-error', err, path.basename(filename))
    })

    app.importer.on('import-complete', function (filename) {
      win.webContents.send('import-complete', path.basename(filename))
    })

    app.importer.on('import-progress', function (filename, index, total) {
      win.webContents.send('import-progress', path.basename(filename), index, total)
    })

    ipc.on('set-locale', function (ev, lang) {
      app.translations = locale.load(lang)
    })

    ipc.on('import-example-presets', function (ev) {
      var filename = path.join(__dirname, 'static', 'settings-jungle-v1.0.0.mapeosettings')
      userConfig.importSettings(win, filename, function (err) {
        if (err) return log(err)
        log('Example presets imported from ' + filename)
      })
    })

    ipc.on('import-settings', function (ev, filename) {
      console.log('importing settings')
      userConfig.importSettings(win, filename, function (err) {
        if (err) return log(err)
        log('Example presets imported from ' + filename)
      })
    })

    ipc.on('save-file', function () {
      var metadata = userConfig.getSettings('metadata')
      var ext = metadata ? metadata.dataset_id : 'mapeodata'
      electron.dialog.showSaveDialog({
        title: i18n('save-db-dialog'),
        defaultPath: 'database.' + ext,
        filters: [
          { name: 'Mapeo Data (*.' + ext + ')', extensions: ['mapeodata', 'mapeo-jungle', ext] }
        ]
      }, onopen)

      function onopen (filename) {
        if (typeof filename === 'undefined') return
        win.webContents.send('select-file', filename)
      }
    })

    ipc.on('open-file', function () {
      var metadata = userConfig.getSettings('metadata')
      var ext = metadata ? metadata.dataset_id : 'mapeodata'
      electron.dialog.showOpenDialog({
        title: i18n('open-db-dialog'),
        properties: [ 'openFile' ],
        filters: [
          { name: 'Mapeo Data (*.' + ext + ')', extensions: ['mapeodata', 'mapeo-jungle', ext, 'sync', 'zip'] }
        ]
      }, onopen)

      function onopen (filenames) {
        if (typeof filenames === 'undefined') return
        if (filenames.length === 1) {
          var file = filenames[0]
          win.webContents.send('select-file', file)
        }
      }
    })

    ipc.on('export-data', function (_, name, ext) {
      exportData.openDialog(app, name, ext)
    })

    ipc.on('zoom-to-data-get-centroid', function (_, type) {
      getDatasetCentroid(type, function (_, loc) {
        console.log(_, loc)
        if (!loc) return
        win.webContents.send('zoom-to-data-response', loc)
      })
    })

    ipc.on('zoom-to-latlon-request', function (_, lat, lon) {
      win.webContents.send('zoom-to-latlon-response', lat, lon)
    })

    ipc.on('refresh-window', function () {
      win.webContents.send('refresh-window')
    })

    var menu = Menu.buildFromTemplate(menuTemplate(app))
    Menu.setApplicationMenu(menu)

    win.webContents.once('did-finish-load', function () {
      win.webContents.send('indexes-loading')
      app.osm.ready(function () {
        log('indexes READY')
       win.webContents.send('indexes-ready')
      })
    })

    // Emitted when the window is closed.
    win.on('closed', function () {
      // Dereference the window object, usually you would store windows
      // in an array if your app supports multi windows, this is the time
      // when you should delete the corresponding element.
      win = null
      app.quit()
    })

    done()
  }
}

function handleUncaughtExceptions () {
  process.on('uncaughtException', function (error) {
    log('uncaughtException in Node:', error)

    // Show a vaguely informative dialog.
    if (app && win) {
      var opts = {
        type: 'error',
        buttons: [ 'OK' ],
        title: 'Error Fatal',
        message: error.message
      }
      electron.dialog.showMessageBox(win, opts, function () {
        process.exit(1)
      })
    }
  })
}

function getDatasetCentroid (type, done) {
  log('STATUS(getDatasetCentroid):', type)
  app.osm.core.api.stats.getMapCenter(type, function (err, center) {
    if (err) return log('ERROR(getDatasetCentroid):', err)
    console.log('center', center)
    if (!center) return done(null, null)
    done(null, [center.lon, center.lat])
  })
}
<commit_msg>remove unnecessary code for checking version indexes<commit_after>#!/usr/bin/env electron

var path = require('path')
var fs = require('fs')
var minimist = require('minimist')
var electron = require('electron')
var app = electron.app
var Menu = electron.Menu
var BrowserWindow = electron.BrowserWindow

var mkdirp = require('mkdirp')
var level = require('level')
var sublevel = require('subleveldown')
var osmdb = require('osm-p2p')
var series = require('run-series')
var semver = require('semver')
var rimraf = require('rimraf')
var MediaStore = require('safe-fs-blob-store')
var styles = require('mapeo-styles')

var menuTemplate = require('./src/menu')
var createServer = require('./src/server.js')
var createTileServer = require('./src/tile-server.js')

var appSettings = require('./app-settings.json')
var installStatsIndex = require('./src/lib/osm-stats')
var userConfig = require('./src/lib/user-config')
var TileImporter = require('./src/lib/tile-importer')
var importer = require('./src/lib/importer')
var locale = require('./src/lib/locale')
var i18n = require('./src/lib/i18n')
var exportData = require('./src/lib/export-data')

if (require('electron-squirrel-startup')) {
  process.exit(0)
}

// HACK: enable GPU graphics acceleration on some older laptops
app.commandLine.appendSwitch('ignore-gpu-blacklist', 'true')

var APP_NAME = app.getName()
var IS_TEST = process.env.NODE_ENV === 'test'

var log = require('./src/lib/log').Node()

var win = null

// Listen for app-ready event
var appIsReady = false
app.once('ready', function () {
  appIsReady = true
})

// Set up global node exception handler
handleUncaughtExceptions()
log('[STARTUP] Listening for uncaught exceptions')

// Path to `userData`, operating system specific, see
// https://github.com/atom/electron/blob/master/docs/api/app.md#appgetpathname
var userDataPath = app.getPath('userData')

var argv = minimist(process.argv.slice(2), {
  default: {
    port: 5000,
    datadir: path.join(userDataPath, 'data'),
    tileport: 5005
  },
  boolean: [ 'headless', 'debug' ],
  alias: {
    p: 'port',
    t: 'tileport',
    d: 'debug'
  }
})

function startupMsg (txt) {
  return function (done) {
    console.log('[STARTUP] ' + txt)
    done()
  }
}

startupMsg('Unpacking Styles')
mkdirp(path.join(userDataPath, 'styles'), function (err) {
  if (err) log(err)
  mkdirp(path.join(userDataPath, 'presets'), function (err) {
    if (err) log(err)
    styles.unpackIfNew(userDataPath, function (err) {
      if (err) log('[ERROR] while unpacking styles:', err)
    })
  })
})

// The app startup sequence
series([
  startupMsg('Checked indexes version is up-to-date'),

  initOsmDb,
  startupMsg('Initialized osm-p2p'),

  createServers,
  startupMsg('Started osm and tile servers'),

  createMainWindow,
  startupMsg('Created app window')
], function (err) {
  if (err) log('STARTUP FAILED', err)
  else log('STARTUP success!')
})

function initOsmDb (done) {
  var osm = osmdb(argv.datadir)
  log('loading datadir', argv.datadir)

  var idb = sublevel(osm.index, 'stats')
  osm.core.use('stats', installStatsIndex(idb))

  var media = MediaStore(path.join(argv.datadir, 'media'))
  app.osm = osm
  app.media = media
  app.importer = importer(osm)
  app.tiles = TileImporter(userDataPath)

  log('preparing osm indexes..')

  done()
}

function createServers (done) {
  app.server = createServer(app.osm, app.media, { staticRoot: userDataPath })

  var pending = 2

  app.server.listen(argv.port, '127.0.0.1', function () {
    global.osmServerHost = '127.0.0.1:' + app.server.address().port
    log(global.osmServerHost)
    if (--pending === 0) done()
  })

  var tileServer = createTileServer()
  tileServer.listen(argv.tileport, function () {
    log('tile server listening on :', tileServer.address().port)
    if (--pending === 0) done()
  })
}

function createMainWindow (done) {
  app.translations = locale.load()
  if (!argv.headless) {
    if (!appIsReady) {
      app.once('ready', ready)
    } else {
      ready()
    }

    app.on('before-quit', function () {
      app.server.mapeo.api.close(function () {
        app.server.close()
      })
    })

    // Quit when all windows are closed.
    app.on('window-all-closed', function () {
      app.quit()
    })
  } else {
    done()
  }

  function ready () {
    if (argv.headless) return

    var INDEX = 'file://' + path.resolve(__dirname, './index.html')
    if (!win) {
      win = new BrowserWindow({
        title: APP_NAME,
        show: false,
        icon: path.resolve(__dirname, 'static', 'mapeo_256x256.png')
      })
      win.once('ready-to-show', () => win.show())
      if (IS_TEST) win.setSize(1000, 800, false)
      else win.maximize()
    }

    if (argv.debug) win.webContents.openDevTools()
    win.loadURL(INDEX)

    var ipc = electron.ipcMain

    ipc.on('get-user-data', function (event, type) {
      var data = userConfig.getSettings(type)
      if (!data) console.warn('unhandled event', type)
      event.returnValue = data
    })

    app.importer.on('import-error', function (err, filename) {
      win.webContents.send('import-error', err, path.basename(filename))
    })

    app.importer.on('import-complete', function (filename) {
      win.webContents.send('import-complete', path.basename(filename))
    })

    app.importer.on('import-progress', function (filename, index, total) {
      win.webContents.send('import-progress', path.basename(filename), index, total)
    })

    ipc.on('set-locale', function (ev, lang) {
      app.translations = locale.load(lang)
    })

    ipc.on('import-example-presets', function (ev) {
      var filename = path.join(__dirname, 'static', 'settings-jungle-v1.0.0.mapeosettings')
      userConfig.importSettings(win, filename, function (err) {
        if (err) return log(err)
        log('Example presets imported from ' + filename)
      })
    })

    ipc.on('import-settings', function (ev, filename) {
      console.log('importing settings')
      userConfig.importSettings(win, filename, function (err) {
        if (err) return log(err)
        log('Example presets imported from ' + filename)
      })
    })

    ipc.on('save-file', function () {
      var metadata = userConfig.getSettings('metadata')
      var ext = metadata ? metadata.dataset_id : 'mapeodata'
      electron.dialog.showSaveDialog({
        title: i18n('save-db-dialog'),
        defaultPath: 'database.' + ext,
        filters: [
          { name: 'Mapeo Data (*.' + ext + ')', extensions: ['mapeodata', 'mapeo-jungle', ext] }
        ]
      }, onopen)

      function onopen (filename) {
        if (typeof filename === 'undefined') return
        win.webContents.send('select-file', filename)
      }
    })

    ipc.on('open-file', function () {
      var metadata = userConfig.getSettings('metadata')
      var ext = metadata ? metadata.dataset_id : 'mapeodata'
      electron.dialog.showOpenDialog({
        title: i18n('open-db-dialog'),
        properties: [ 'openFile' ],
        filters: [
          { name: 'Mapeo Data (*.' + ext + ')', extensions: ['mapeodata', 'mapeo-jungle', ext, 'sync', 'zip'] }
        ]
      }, onopen)

      function onopen (filenames) {
        if (typeof filenames === 'undefined') return
        if (filenames.length === 1) {
          var file = filenames[0]
          win.webContents.send('select-file', file)
        }
      }
    })

    ipc.on('export-data', function (_, name, ext) {
      exportData.openDialog(app, name, ext)
    })

    ipc.on('zoom-to-data-get-centroid', function (_, type) {
      getDatasetCentroid(type, function (_, loc) {
        console.log(_, loc)
        if (!loc) return
        win.webContents.send('zoom-to-data-response', loc)
      })
    })

    ipc.on('zoom-to-latlon-request', function (_, lat, lon) {
      win.webContents.send('zoom-to-latlon-response', lat, lon)
    })

    ipc.on('refresh-window', function () {
      win.webContents.send('refresh-window')
    })

    var menu = Menu.buildFromTemplate(menuTemplate(app))
    Menu.setApplicationMenu(menu)

    win.webContents.once('did-finish-load', function () {
      win.webContents.send('indexes-loading')
      app.osm.ready(function () {
        log('indexes READY')
       win.webContents.send('indexes-ready')
      })
    })

    // Emitted when the window is closed.
    win.on('closed', function () {
      // Dereference the window object, usually you would store windows
      // in an array if your app supports multi windows, this is the time
      // when you should delete the corresponding element.
      win = null
      app.quit()
    })

    done()
  }
}

function handleUncaughtExceptions () {
  process.on('uncaughtException', function (error) {
    log('uncaughtException in Node:', error)

    // Show a vaguely informative dialog.
    if (app && win) {
      var opts = {
        type: 'error',
        buttons: [ 'OK' ],
        title: 'Error Fatal',
        message: error.message
      }
      electron.dialog.showMessageBox(win, opts, function () {
        process.exit(1)
      })
    }
  })
}

function getDatasetCentroid (type, done) {
  log('STATUS(getDatasetCentroid):', type)
  app.osm.core.api.stats.getMapCenter(type, function (err, center) {
    if (err) return log('ERROR(getDatasetCentroid):', err)
    console.log('center', center)
    if (!center) return done(null, null)
    done(null, [center.lon, center.lat])
  })
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    webpack = require('gulp-webpack'),
    gulpIf = require('gulp-if'),
    uglify = require('gulp-uglify'),
    _ = require('underscore'),
    elixir = require('laravel-elixir'),
    utilities = require('laravel-elixir/ingredients/commands/Utilities'),
    notification = require('laravel-elixir/ingredients/commands/Notification');

elixir.extend('webpack', function (src, options) {

    var config = this,
        defaultOptions = {
            debug:     ! config.production,
            watch:     ! config.production,
            srcDir:    config.assetsDir + 'js',
            outputDir: config.jsOutput,
        };

    options = _.extend(defaultOptions, options);
    src = "./" + utilities.buildGulpSrc(src, options.srcDir);

    options = _.extend(defaultOptions, options);

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

        var onError = function(e) {
            new notification().error(e, 'Webpack Compilation Failed!');
            this.emit('end');
        };

        return gulp.src(src)
            .pipe(webpack(options)).on('error', onError)
            .pipe(gulpIf(! options.debug, uglify()))
            .pipe(gulp.dest(options.outputDir))
            .pipe(new notification().message('Webpack Compiled!'));
    });

    this.registerWatcher('webpack', options.srcDir + '/**/*.js');

    return this.queueTask('webpack');
});
<commit_msg>redundant extend<commit_after>var gulp = require('gulp'),
    webpack = require('gulp-webpack'),
    gulpIf = require('gulp-if'),
    uglify = require('gulp-uglify'),
    _ = require('underscore'),
    elixir = require('laravel-elixir'),
    utilities = require('laravel-elixir/ingredients/commands/Utilities'),
    notification = require('laravel-elixir/ingredients/commands/Notification');

elixir.extend('webpack', function (src, options) {

    var config = this,
        defaultOptions = {
            debug:     ! config.production,
            watch:     ! config.production,
            srcDir:    config.assetsDir + 'js',
            outputDir: config.jsOutput,
        };

    options = _.extend(defaultOptions, options);
    src = "./" + utilities.buildGulpSrc(src, options.srcDir);

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

        var onError = function(e) {
            new notification().error(e, 'Webpack Compilation Failed!');
            this.emit('end');
        };

        return gulp.src(src)
            .pipe(webpack(options)).on('error', onError)
            .pipe(gulpIf(! options.debug, uglify()))
            .pipe(gulp.dest(options.outputDir))
            .pipe(new notification().message('Webpack Compiled!'));
    });

    this.registerWatcher('webpack', options.srcDir + '/**/*.js');

    return this.queueTask('webpack');
});
<|endoftext|>