<commit_before>import * as rrb from "rrb-vector";

import { error } from "./error";

import { seq, first, isSeq, foldLeft as seqFoldLeft, zeroOrOne, exactlyOne } from "./seq";

import * as t from "./transducers";

var List = rrb.empty.constructor;

List.prototype.__is_List = true;

List.prototype._type = 5;

List.prototype["@@transducer/init"] = function(){
	return rrb.empty;
};

List.prototype["@@transducer/step"] = function(l,x) {
	return l.push(x);
};

List.prototype["@@transducer/result"] = function(l) {
	return l;
};

rrb.TreeIterator.prototype["@@transducer/init"] = function(){
	return rrb.empty;
};

rrb.TreeIterator.prototype["@@transducer/step"] = function(l,x) {
	return l.push(x);
};

rrb.TreeIterator.prototype["@@transducer/result"] = function(l) {
	return l;
};

export function isArray($maybe) {
	let maybe = first($maybe);
	return !!(maybe && maybe.__is_List);
}

export default function array(...a) {
	var l = a.length;
	if(l===0){
		return rrb.empty;
	}
	if(l==1 && isSeq(a[0])){
		return rrb.fromArray(a[0].toArray());
	}
	return rrb.fromArray(a);
}

export function join($a) {
	if ($a === undefined) return error("XPTY0004");
	// assume a sequence of vectors
	return seqFoldLeft($a,rrb.empty,function(pre,cur){
		var v = first(cur);
		if(!isArray(v)) return error("XPTY0004","One of the items for array:join is not an array.");
		return pre.concat(v);
	});
}

function _checked($a, fn, ...args) {
	if ($a === undefined) return error("XPTY0004");
	var a = $a;
	if (isSeq($a)) {
		if ($a.size > 1) return error("XPTY0004");
		a = first($a);
	}
	if (!isArray(a)) return error("XPTY0004");
	args.unshift(a);
	return fn.apply(a, args);
}

export function head($a) {
	return _checked($a, rrb.get,0);
}

export function tail($a) {
	return _checked($a, rrb.slice,1);
}

export function size($a) {
	return _checked($a, List.prototype.count);
}

export function subarray($a,$s,$l) {
	var s =  first($s) || 1, l = first($l);
	var sx = s.valueOf() - 1;
	if(l) l = Math.max(sx + Number(l),0);
	return _checked($a, rrb.slice, sx, l);
}

export function insertBefore($a, $i, $v) {
	var i = first($i) || 1;
	var ix = i.valueOf() - 1;
	// unmarshal Singleton
	var v = isSeq($v) && $v.size != 1 ? $v : first($v);
	return _checked($a, function(a){
		// slice from 0 to i
		// slice form i to end
		// concat s1 + v + s2
		return a.slice(0,ix).push(v).concat(a.slice(ix));
	});
}

export function remove($a,$i) {
	var i = first($i) || 1;
	var ix = i.valueOf() - 1;
	return _checked($a, function(a){
		return a.slice(0,ix).concat(a.slice(i));
	});
}

export function append($a,$v) {
	var v = isSeq($v) && $v.size != 1 ? $v : first($v);
	return _checked($a,rrb.push,v);
}

export function reverse($a) {
	return _checked($a,function(a){
		return rrb.fromArray(a.toJS(true).reverse());
	});
}

export function flatten($a) {
	return t.into($a, t.compose(t.cat,t.filter(_ => _ !== undefined)), seq());
}

export function get($a,$i) {
	var i = first($i) || 1;
	var ix = i.valueOf() - 1;
	return _checked($a,function(a){
		if(a.size) return a.get(ix);
		return seq();
	});
}

export function forEach($a,$f){
	return t.forEach(first($a),first($f));
}

export function filter($a,$f){
	return t.filter(first($a),first($f));
}

export function foldLeft($a,$z,$f){
	return zeroOrOne($a).concatMap(a => exactlyOne($z).concatMap(z => exactlyOne($f).concatMap(f => t.foldLeft(a,z,f))));
}
<commit_msg>initial fixes array<commit_after>import * as rrb from "rrb-vector";

import { error } from "./error";

import { seq, from, of, first, isSeq, foldLeft as seqFoldLeft, zeroOrOne, exactlyOne } from "./seq";

import { ensureDoc } from "./doc";

import { list } from "./access";

import { isArray, isUndef } from "./util";

var List = rrb.empty.constructor;

List.prototype.__is_List = true;

List.prototype._type = 5;

List.prototype["@@transducer/init"] = function(){
	return rrb.empty;
};

List.prototype["@@transducer/step"] = function(l,x) {
	return l.push(x);
};

List.prototype["@@transducer/result"] = function(l) {
	return l;
};

rrb.TreeIterator.prototype["@@transducer/init"] = function(){
	return rrb.empty;
};

rrb.TreeIterator.prototype["@@transducer/step"] = function(l,x) {
	return l.push(x);
};

rrb.TreeIterator.prototype["@@transducer/result"] = function(l) {
	return l;
};

function _isList(maybe) {
	return maybe && maybe.__is_List;
}

export function isList($maybe) {
	let maybe = first($maybe);
}

export default function array(...a) {
	var l = a.length;
	if(l===0){
		return seq(rrb.empty);
	}
	if(l==1){
		const s = a[0];
		if (isSeq(s)) return s;
		if (_isList(s)) return of(s);
		if (isArray(s)) return of(rrb.fromArray(s));
		// TODO VNode conversion
		if (list()(s)) return of(s.toArray());
		return rrb.empty.push(s);
	}
	return join(seq(a.map(of)).concatAll().map(a => array(a)));
}

export function join($a) {
	if ($a === undefined) return error("XPTY0004");
	// assume a sequence of vectors
	return $a.reduce(function(pre,cur){
		// TODO force persistent cx
		if(list(cur)) cur = cur.toArray();
		if(!_isList(cur)) return error("XPTY0004","One of the items for array:join is not an array.");
		return pre.concat(cur);
	},rrb.empty);
}

function _checked($a, fn, ...args) {
	if ($a === undefined) return error("XPTY0004");
	return exactlyOne($a).map(a => !_isList(a) ? error("XPTY0004") : fn.bind(a,a).apply(a, args));
}

// TODO iterator to Observable using transducer protocol
// at the completion of the operation, create a new list
// array:transform($input, ... functions) => zeroOrOne()
// for now:
export function head($a) {
	return _checked($a, rrb.get,0);
}

export function tail($a) {
	return _checked($a, rrb.slice,1);
}

export function size($a) {
	return _checked($a, List.prototype.count);
}

export function subarray($a,$s,$l) {
	return exactlyOne($a).concatMap(a => seq($s).concatMap(s => {
		s = s.valueOf() - 1;
		$l = seq($l);
		return $l.isEmpty().map(test => test ? rrb.slice(a,s) : $l.map(l => rrb.slice(a,s,Math.max(s + Number(l),0))));
	}));
}

export function insertBefore($a, $i, $v) {
	return seq($i).concatMap(i => {
		return _checked($a, function(a){
			const ix = i - 1;
			// slice from 0 to i
			// slice form i to end
			// concat s1 + v + s2
			return a.slice(0,ix).push($v).concat(a.slice(ix));
		});
	});
}

export function remove($a,$i) {
	var i = first($i) || 1;
	var ix = i.valueOf() - 1;
	return _checked($a, function(a){
		return a.slice(0,ix).concat(a.slice(i));
	});
}

export function append($a,$v) {
	return _checked($a,rrb.push,$v);
}

export function reverse($a) {
	return _checked($a,function(a){
		return rrb.fromArray(a.toJS(true).reverse());
	});
}

export function flatten($a) {
	return $a.concatAll();
}

export function get($a,$i) {
	if(isUndef($i)) return error("XPST0017");
	return exactlyOne($i).concatMap(i => _checked($a,function(a){
		if(a.size) return a.get(i - 1);
		//return seq();
	}));
}

export function forEach($a,$f){
	return t.forEach(first($a),first($f));
}

export function filter($a,$f){
	return t.filter(first($a),first($f));
}

export function foldLeft($a,$z,$f){
	// TODO use iterator to seq, foldLeft seq into new array
	//return zeroOrOne($a).concatMap(a => seq())
	return zeroOrOne($a).concatMap(a => exactlyOne($z).concatMap(z => exactlyOne($f).concatMap(f => t.foldLeft(a,z,f))));
}
<|endoftext|>


<commit_before>const Maths = require('./maths');
const Prefab = require('./prefab');
const Renderer = require('./renderer');
const Shaders = require('./shaders');
const Primitives = require('./primitives');

module.exports = (function(){
	let exports = {};

	let getAtlasIndex = (atlas, name) => {
		let map = atlas.map;
		for (let i = 0, l = map.length; i < l; i++) {
			if (map[i] == name) {
				return i;
			}
		}
		return 0;
	};

	let getPrefabName = (atlas, atlasIndex, color, alpha, centered) => {
		let name = atlas.id + "_" + atlasIndex;
		if (alpha !== undefined && alpha != atlas.materialConfig.properties.alpha) {
			name += "_" + (alpha ? "a1" : "a0");
		}

		if (color !== undefined && (color[0] != 1 || color[1] != 1 || color[2] != 1 || color[3] != 1)) {
			name += "_" + color[0] + "_" + color[1] + "_" + color[2] + "_" + color[3];
		}

		if (centered) {
			name += "_c";
		}

		return name;
	}

	let setMaterialOffset = (config, atlasIndex, width, height) => {
		let offsetU = (atlasIndex % width) / width;
		let offsetV = 1 - (Math.floor(atlasIndex / width) + 1) / height;
		config.properties.offset = [ offsetU, offsetV ];
	};

	exports.setMaterialOffset = (config, atlas, tile) => {
		let atlasIndex = getAtlasIndex(atlas, tile);
		setMaterialOffset(config, atlasIndex, atlas.width, atlas.height);
	};

	exports.createTilePrefab = (config) => {
		let { atlas, tile, color, alpha, centered } = config;
		let { width, height } = atlas;
		let atlasIndex = getAtlasIndex(atlas, tile);
		let prefabName = getPrefabName(atlas, atlasIndex, color, alpha, centered);

		if (Prefab.prefabs[prefabName] === undefined) {
			let meshConfig = centered ? atlas.centerdMeshConfig : atlas.meshConfig;

			let materialConfig = Object.create(atlas.materialConfig);
			if (alpha !== undefined) {
				materialConfig.properties.alpha = alpha;
			}
			if (color !== undefined) {
				materialConfig.properties.color = color;
			} else {
				 // This shouldn't be necessary, however it is
				materialConfig.properties.color = Maths.vec4.fromValues(1,1,1,1);
			}
			setMaterialOffset(materialConfig, atlasIndex, width, height);

			Prefab.create({
				name: prefabName,
				meshConfig: meshConfig,
				materialConfig: materialConfig
			});
		}
		return prefabName;
	};

	exports.create = (config, image) => {
		if (!config.id || !config.map || !config.width || !config.height || !config.tileWidth || !config.tileHeight) {
			console.error("Invalid atlas definition provided, must contain properties: id, map, width, height, tileWidth and tileHeight");
		}
		let atlas = Object.create(config);
		atlas.alpha = atlas.alpha === undefined ? true : !!atlas.alpha;
		atlas.texture = Renderer.createTexture(image, "low");
		atlas.materialConfig = {
			shader: Shaders.Sprite,
			texture: atlas.texture,
			properties: {
				alpha: atlas.alpha,
				offset: [ 0, 0 ],
				scale: [ 1 / atlas.width, 1 / atlas.height ]
			}
		};
		atlas.meshConfig = Primitives.createQuadMeshConfig(atlas.tileWidth, atlas.tileHeight);
		atlas.centerdMeshConfig = Primitives.createCenteredQuadMeshConfig(atlas.tileWidth, atlas.tileHeight);
		return atlas;
	};

	exports.load = (config, callback) => {
		let image = new Image();
		image.onload = () => {
			callback(exports.create(config, image));
		};
		image.src = config.path;
	};

	return exports;
})();<commit_msg>Updated Atlas.setMaterialOffset to take material rather than material config.<commit_after>const Maths = require('./maths');
const Prefab = require('./prefab');
const Renderer = require('./renderer');
const Shaders = require('./shaders');
const Primitives = require('./primitives');

module.exports = (function(){
	let exports = {};

	let getAtlasIndex = (atlas, name) => {
		let map = atlas.map;
		for (let i = 0, l = map.length; i < l; i++) {
			if (map[i] == name) {
				return i;
			}
		}
		return 0;
	};

	let getPrefabName = (atlas, atlasIndex, color, alpha, centered) => {
		let name = atlas.id + "_" + atlasIndex;
		if (alpha !== undefined && alpha != atlas.materialConfig.properties.alpha) {
			name += "_" + (alpha ? "a1" : "a0");
		}

		if (color !== undefined && (color[0] != 1 || color[1] != 1 || color[2] != 1 || color[3] != 1)) {
			name += "_" + color[0] + "_" + color[1] + "_" + color[2] + "_" + color[3];
		}

		if (centered) {
			name += "_c";
		}

		return name;
	}

	let setOffset = (out, atlasIndex, width, height) => {
		out[0] = (atlasIndex % width) / width;
		out[1] = 1 - (Math.floor(atlasIndex / width) + 1) / height;
	};

	let setMaterialConfigOffset = (config, atlasIndex, width, height) => {
		config.properties.offset = [0,0]; // Create new offset array per prefab
		setOffset(config.properties.offset, atlasIndex, width, height);
	};

	exports.setMaterialOffset = (material, atlas, tile) => {
		let atlasIndex = getAtlasIndex(atlas, tile);
		if (!material.offset) { material.offset = [0,0]; }
		setOffset(material.offset, atlasIndex, atlas.width, atlas.height);
	};

	exports.createTilePrefab = (config) => {
		let { atlas, tile, color, alpha, centered } = config;
		let { width, height } = atlas;
		let atlasIndex = getAtlasIndex(atlas, tile);
		let prefabName = getPrefabName(atlas, atlasIndex, color, alpha, centered);

		if (Prefab.prefabs[prefabName] === undefined) {
			let meshConfig = centered ? atlas.centerdMeshConfig : atlas.meshConfig;

			let materialConfig = Object.create(atlas.materialConfig);
			if (alpha !== undefined) {
				materialConfig.properties.alpha = alpha;
			}
			if (color !== undefined) {
				materialConfig.properties.color = color;
			} else {
				 // This shouldn't be necessary, however it is
				materialConfig.properties.color = Maths.vec4.fromValues(1,1,1,1);
			}
			setMaterialConfigOffset(materialConfig, atlasIndex, width, height);

			Prefab.create({
				name: prefabName,
				meshConfig: meshConfig,
				materialConfig: materialConfig
			});
		}
		return prefabName;
	};

	exports.create = (config, image) => {
		if (!config.id || !config.map || !config.width || !config.height || !config.tileWidth || !config.tileHeight) {
			console.error("Invalid atlas definition provided, must contain properties: id, map, width, height, tileWidth and tileHeight");
		}
		let atlas = Object.create(config);
		atlas.alpha = atlas.alpha === undefined ? true : !!atlas.alpha;
		atlas.texture = Renderer.createTexture(image, "low");
		atlas.materialConfig = {
			shader: Shaders.Sprite,
			texture: atlas.texture,
			properties: {
				alpha: atlas.alpha,
				offset: [ 0, 0 ],
				scale: [ 1 / atlas.width, 1 / atlas.height ]
			}
		};
		atlas.meshConfig = Primitives.createQuadMeshConfig(atlas.tileWidth, atlas.tileHeight);
		atlas.centerdMeshConfig = Primitives.createCenteredQuadMeshConfig(atlas.tileWidth, atlas.tileHeight);
		return atlas;
	};

	exports.load = (config, callback) => {
		let image = new Image();
		image.onload = () => {
			callback(exports.create(config, image));
		};
		image.src = config.path;
	};

	return exports;
})();<|endoftext|>


<commit_before>/* global _ */

/*
 * Complex scripted dashboard
 * This script generates a dashboard object that Grafana can load. It also takes a number of user
 * supplied URL parameters (int ARGS variable)
 */

// Accessable variables in this scope
var window, document, ARGS, $, jQuery, moment, kbn;

return function (callback) {
  'use strict';

  // Setup some variables
  var dashboard;
  var hostSeries = [];

  // InfluxDB setup
  var influxUser = 'root';
  var influxPass = 'root';
  var influxDB = 'graphite';

  // GET variables
  var displayHost = '';
  var displayMetric = '';
  var displayTime;

  if(!_.isUndefined(ARGS.host)) {
    displayHost = ARGS.host;
  }
  if(!_.isUndefined(ARGS.metric)) {
    displayMetric = ARGS.metric;
  }
  if(!_.isUndefined(ARGS.time)) {
    displayTime = ARGS.time;
  }

  var prefix = 'collectd.' + displayHost + '.';
  var postfix = '';
  var influxdbQueryUrl = window.location.protocol + '//'+ window.location.host +
                   ':8086/db/' + influxDB + '/series?u=' + influxUser + '&p=' + influxPass +
                   '&q=list series /\.' + displayHost + '\./';

  var getdashConfig = '/app/getdash/getdash.conf.js';

  // Intialize a skeleton with nothing but a rows array and service object
  dashboard = {
      rows : [],
      services : {}
  };

  // Set default time
  // time can be overriden in the url using from/to parameteres, but this is
  // handled automatically in grafana core during dashboard initialization

  // Dashboard time and interval setup function
  var getDashTimeInterval = function (time) {
    var defaultTimeInterval =  {
      time: {
        from: "now-6h",
        to: "now"
      },
      interval: '1m',
    };

    if (!time)
      return defaultTimeInterval;

    var timeM = 0;
    var regexpTime = /(\d+)(m|h|d)/;
    var rTime = regexpTime.exec(time);

    if (!rTime)
      return defaultTimeInterval;

    if (rTime[2] === 'm') {
      timeM = parseInt(rTime[1]);
    } else if (rTime[2] === 'h') {
      timeM = parseInt(rTime[1]) * 60;
    } else if (rTime[2] === 'd') {
      timeM = parseInt(rTime[1]) * 60 * 24;
    }

    return {
      time: {
        from: "now-" + time,
        to: "now"
      },
      interval: (timeM >= 360) ? Math.floor(timeM / 360).toString() + 'm' : '30s',
    };
  };

  var dashTimeInterval = getDashTimeInterval(displayTime);
  dashboard.time = dashTimeInterval.time;
  var interval = dashTimeInterval.interval;

  // Set a title
  dashboard.title = 'Scripted Dashboard for ' + displayHost;

  // Dashboard setup helper functions
  var targetGen = function (series, alias, interval, column, apply) {
    return {
      'series': series,
      'alias': alias,
      'column': (column === undefined) ? 'value' : column,
      'interval': (interval === undefined) ? '1m' : interval,
      'function': (apply === undefined) ? 'mean' : apply,
    };
  };

  var targetsGen = function (series, seriesAlias, span, interval, graphConf, aliasConf) {
    var targets = [];
    var aliasColors = {};
    var aliasColor = '';
    var alias = '';
    var column = '';
    var apply = '';
    for (var match in graphConf) {
      var graph = graphConf[match];
      for (var i = 0; i < series.length; i++) {
        var s = series[i];
        seriesAlias = (seriesAlias) ? seriesAlias : s.split('.')[2];
        if (s.lastIndexOf(match) === s.length - match.length) {
          if ((aliasConf) && ('position' in aliasConf)) {
            alias = seriesAlias + '.' + s.split('.')[aliasConf.position];
          } else if (graph.alias) {
            alias = seriesAlias + '.' + graph.alias;
          } else {
            alias = seriesAlias + '.' + match;
          }
          column = graph.column;
          apply = graph.apply;
          targets.push(targetGen(s, alias, interval, column, apply));
          if (graph.color) {
            aliasColor = graph.color;
          } else {
            aliasColor = '#' + ((1 << 24) * Math.random() | 0).toString(16);
          }
          aliasColors[alias] = aliasColor;
        }
      }
    }
    return {
      'targets': targets,
      'aliasColors': aliasColors,
    };
  };

  var panelFactory = function (gConf) {
    return function (series, seriesAlias, span, interval) {
      span = (span === undefined) ? 12 : span;
      interval = (interval === undefined) ? '1m' : interval;
      var result = {};
      var graph = gConf.graph;
      var alias = gConf.alias;
      var targets = targetsGen(series, seriesAlias, span, interval, graph, alias);
      var panel = {
        'title': 'Default Title',
        'type': 'graphite',
        'span': span,
        'y_formats': [ 'none' ],
        'grid': { 'max': null, 'min': 0, 'leftMin': 0 },
        'lines': true,
        'fill': 1,
        'linewidth': 1,
        'nullPointMode': 'null',
        'targets': targets.targets,
        'aliasColors': targets.aliasColors,
      };

      if (('title' in gConf.panel) && (gConf.panel.title.match('@metric'))) {
        return $.extend(result, panel, gConf.panel,
            { 'title': gConf.panel.title.replace('@metric', series[0].split('.')[2]) });
      }

      return $.extend(result, panel, gConf.panel);
   };
  };

  var setupRow = function (title, panels) {
    return {
      'title': title,
      'height': '250px',
      'panels': panels,
      'grid': { 'max': null, 'min': 0 },
    };
  };

  var getExtendedMetrics = function (series, prefix) {
    var metricsExt = [];
    var postfix = '';
    for (var i = 0; i < series.length; i++) {
      if (series[i].indexOf(prefix) === 0) {
        postfix = series[i].slice(prefix.length);
        postfix = postfix.slice(0, postfix.indexOf('.'));
        if (metricsExt.indexOf(postfix) === -1) {
          metricsExt.push(postfix);
        }
      }
    }
    return metricsExt;
  };

  var setupDash = function (plugin) {
    var p = {
      func: [],
      config: plugin.config,
    };
    for (var name in plugin) {
      p.func.push(panelFactory(plugin[name]));
    }
    return p;
  };

  var genDashs = function (metrics, plugins) {
    var dashs = {};
    if (metrics) {
      var groups = plugins.groups;
      for (var i = 0, mlen = metrics.length; i < mlen; i++) {
        var metric = metrics[i];
        if (metric in plugins) {
          dashs[metric] = setupDash(plugins[metric]);
        } else if (metric in groups) {
          var group = groups[metric];
          for (var j = 0, glen = group.length; j < glen; j++) {
            var member = group[j];
            if (!(member in dashs) && (member in plugins)) {
              dashs[member] = setupDash(plugins[member]);
            }
          }
        }
      }
      return dashs;
    } else {
      for (var plugin in plugins) {
        dashs[plugin] = setupDash(plugins[plugin]);
      }
      return dashs;
    }
  };

  var matchSeries = function (prefix, metric, plugin, series, dash) {
    var matchedSeries = [];
    for (var i = 0, len = series.length; i < len; i++) {
      if ((series[i].indexOf(prefix + metric) === 0) &&
        (!('regexp' in dash[plugin].config) ||
        dash[plugin].config.regexp.test(series[i].split('.')[2]))) {
          matchedSeries.push(series[i]);
      }
    }
    return matchedSeries;
  };

  // AJAX configuration
  $.ajaxSetup({
    async: true,
    cache: false,
  });

  // Get series and panel configuration to perepare dashboard
  $.when(
    $.getJSON(influxdbQueryUrl)
      .done(function (jsonData) {
        var points = jsonData[0].points;
        for (var i = 0, len = points.length; i < len; i++) {
          hostSeries.push(points[i][1]);
        }
      })
      .fail(function () {
        throw new Error('Error loading InfluxDB data JSON from: ' + influxdbQueryUrl);
      }),

    $.getScript(getdashConfig)
      .fail(function () {
        throw new Error('Error loading getdash config from: ' + getdashConfig);
      }),

    $.Deferred(function (deferred) {
      $(deferred.resolve);
    })
  ).done(function () {
    if (hostSeries.length === 0) {
      return dashboard;
    }

    var displayMetrics = (displayMetric) ? displayMetric.split(',') : null;
    var showDashs = genDashs(displayMetrics, plugins);

    for (var plugin in showDashs) {
      var metric = plugin;
      var seriesAlias = ('alias' in showDashs[plugin].config) ? showDashs[plugin].config.alias : null;
      var matchedSeries = [];

      if (showDashs[plugin].config.multi) {
        var metricsExt = getExtendedMetrics(matchSeries(prefix, metric, plugin, hostSeries, showDashs), prefix);
        for (var i = 0, mlen = metricsExt.length; i < mlen; i++) {
          matchedSeries.push(matchSeries(prefix, metricsExt[i], plugin, hostSeries, showDashs));
        }
      } else {
        matchedSeries.push(matchSeries(prefix, metric, plugin, hostSeries, showDashs));
      }

      for (var j = 0, slen = matchedSeries.length; j < slen; j++) {
        for (var k = 0, flen = showDashs[plugin].func.length; k < flen; k++) {
          var metricFunc = showDashs[plugin].func[k];
          dashboard.rows.push(setupRow(metric.toUpperCase, [metricFunc(matchedSeries[j], seriesAlias, 12, interval)]));
        }
      }
    }

    // Return dashboard
    callback(dashboard);
  });
};
<commit_msg>Improved interval calculation based on time GET argument.<commit_after>/* global _ */

/*
 * Complex scripted dashboard
 * This script generates a dashboard object that Grafana can load. It also takes a number of user
 * supplied URL parameters (int ARGS variable)
 */

// Accessable variables in this scope
var window, document, ARGS, $, jQuery, moment, kbn;

return function (callback) {
  'use strict';

  // Setup some variables
  var dashboard;
  var hostSeries = [];

  // InfluxDB setup
  var influxUser = 'root';
  var influxPass = 'root';
  var influxDB = 'graphite';

  // GET variables
  var displayHost = '';
  var displayMetric = '';
  var displayTime;

  if(!_.isUndefined(ARGS.host)) {
    displayHost = ARGS.host;
  }
  if(!_.isUndefined(ARGS.metric)) {
    displayMetric = ARGS.metric;
  }
  if(!_.isUndefined(ARGS.time)) {
    displayTime = ARGS.time;
  }

  var prefix = 'collectd.' + displayHost + '.';
  var postfix = '';
  var influxdbQueryUrl = window.location.protocol + '//'+ window.location.host +
                   ':8086/db/' + influxDB + '/series?u=' + influxUser + '&p=' + influxPass +
                   '&q=list series /\.' + displayHost + '\./';

  var getdashConfig = '/app/getdash/getdash.conf.js';

  // Intialize a skeleton with nothing but a rows array and service object
  dashboard = {
      rows : [],
      services : {}
  };

  // Set default time
  // time can be overriden in the url using from/to parameteres, but this is
  // handled automatically in grafana core during dashboard initialization

  // Dashboard time and interval setup function
  var getDashTimeInterval = function (time) {
    var defaultTimeInterval = {
      'time': {
        'from': "now-6h",
        'to': "now"
      },
      'interval': '1m',
    };

    if (!time)
      return defaultTimeInterval;

    var timeM = 0;
    var interval = '';
    var regexpTime = /(\d+)(m|h|d)/;
    var rTime = regexpTime.exec(time);

    if (!rTime)
      return defaultTimeInterval;

    if (rTime[2] === 'm')
      timeM = parseInt(rTime[1]);
    else if (rTime[2] === 'h')
      timeM = parseInt(rTime[1]) * 60;
    else if (rTime[2] === 'd')
      timeM = parseInt(rTime[1]) * 60 * 24;

    if (timeM > 360)
      interval = (Math.ceil((Math.floor(timeM / 360) + 1) / 5) * 5).toString() + 'm';
    else if (timeM === 360)
      interval = '1m';
    else
      interval = '30s';

    return {
      'time': {
        'from': "now-" + time,
        'to': "now"
      },
      'interval': interval,
    };
  };

  var dashTimeInterval = getDashTimeInterval(displayTime);
  dashboard.time = dashTimeInterval.time;
  var interval = dashTimeInterval.interval;

  // Set a title
  dashboard.title = 'Scripted Dashboard for ' + displayHost;

  // Dashboard setup helper functions
  var targetGen = function (series, alias, interval, column, apply) {
    return {
      'series': series,
      'alias': alias,
      'column': (column === undefined) ? 'value' : column,
      'interval': (interval === undefined) ? '1m' : interval,
      'function': (apply === undefined) ? 'mean' : apply,
    };
  };

  var targetsGen = function (series, seriesAlias, span, interval, graphConf, aliasConf) {
    var targets = [];
    var aliasColors = {};
    var aliasColor = '';
    var alias = '';
    var column = '';
    var apply = '';
    for (var match in graphConf) {
      var graph = graphConf[match];
      for (var i = 0; i < series.length; i++) {
        var s = series[i];
        seriesAlias = (seriesAlias) ? seriesAlias : s.split('.')[2];
        if (s.lastIndexOf(match) === s.length - match.length) {
          if ((aliasConf) && ('position' in aliasConf)) {
            alias = seriesAlias + '.' + s.split('.')[aliasConf.position];
          } else if (graph.alias) {
            alias = seriesAlias + '.' + graph.alias;
          } else {
            alias = seriesAlias + '.' + match;
          }
          column = graph.column;
          apply = graph.apply;
          targets.push(targetGen(s, alias, interval, column, apply));
          if (graph.color) {
            aliasColor = graph.color;
          } else {
            aliasColor = '#' + ((1 << 24) * Math.random() | 0).toString(16);
          }
          aliasColors[alias] = aliasColor;
        }
      }
    }
    return {
      'targets': targets,
      'aliasColors': aliasColors,
    };
  };

  var panelFactory = function (gConf) {
    return function (series, seriesAlias, span, interval) {
      span = (span === undefined) ? 12 : span;
      interval = (interval === undefined) ? '1m' : interval;
      var result = {};
      var graph = gConf.graph;
      var alias = gConf.alias;
      var targets = targetsGen(series, seriesAlias, span, interval, graph, alias);
      var panel = {
        'title': 'Default Title',
        'type': 'graphite',
        'span': span,
        'y_formats': [ 'none' ],
        'grid': { 'max': null, 'min': 0, 'leftMin': 0 },
        'lines': true,
        'fill': 1,
        'linewidth': 1,
        'nullPointMode': 'null',
        'targets': targets.targets,
        'aliasColors': targets.aliasColors,
      };

      if (('title' in gConf.panel) && (gConf.panel.title.match('@metric'))) {
        return $.extend(result, panel, gConf.panel,
            { 'title': gConf.panel.title.replace('@metric', series[0].split('.')[2]) });
      }

      return $.extend(result, panel, gConf.panel);
   };
  };

  var setupRow = function (title, panels) {
    return {
      'title': title,
      'height': '250px',
      'panels': panels,
      'grid': { 'max': null, 'min': 0 },
    };
  };

  var getExtendedMetrics = function (series, prefix) {
    var metricsExt = [];
    var postfix = '';
    for (var i = 0; i < series.length; i++) {
      if (series[i].indexOf(prefix) === 0) {
        postfix = series[i].slice(prefix.length);
        postfix = postfix.slice(0, postfix.indexOf('.'));
        if (metricsExt.indexOf(postfix) === -1) {
          metricsExt.push(postfix);
        }
      }
    }
    return metricsExt;
  };

  var setupDash = function (plugin) {
    var p = {
      func: [],
      config: plugin.config,
    };
    for (var name in plugin) {
      p.func.push(panelFactory(plugin[name]));
    }
    return p;
  };

  var genDashs = function (metrics, plugins) {
    var dashs = {};
    if (metrics) {
      var groups = plugins.groups;
      for (var i = 0, mlen = metrics.length; i < mlen; i++) {
        var metric = metrics[i];
        if (metric in plugins) {
          dashs[metric] = setupDash(plugins[metric]);
        } else if (metric in groups) {
          var group = groups[metric];
          for (var j = 0, glen = group.length; j < glen; j++) {
            var member = group[j];
            if (!(member in dashs) && (member in plugins)) {
              dashs[member] = setupDash(plugins[member]);
            }
          }
        }
      }
      return dashs;
    } else {
      for (var plugin in plugins) {
        dashs[plugin] = setupDash(plugins[plugin]);
      }
      return dashs;
    }
  };

  var matchSeries = function (prefix, metric, plugin, series, dash) {
    var matchedSeries = [];
    for (var i = 0, len = series.length; i < len; i++) {
      if ((series[i].indexOf(prefix + metric) === 0) &&
        (!('regexp' in dash[plugin].config) ||
        dash[plugin].config.regexp.test(series[i].split('.')[2]))) {
          matchedSeries.push(series[i]);
      }
    }
    return matchedSeries;
  };

  // AJAX configuration
  $.ajaxSetup({
    async: true,
    cache: false,
  });

  // Get series and panel configuration to perepare dashboard
  $.when(
    $.getJSON(influxdbQueryUrl)
      .done(function (jsonData) {
        var points = jsonData[0].points;
        for (var i = 0, len = points.length; i < len; i++) {
          hostSeries.push(points[i][1]);
        }
      })
      .fail(function () {
        throw new Error('Error loading InfluxDB data JSON from: ' + influxdbQueryUrl);
      }),

    $.getScript(getdashConfig)
      .fail(function () {
        throw new Error('Error loading getdash config from: ' + getdashConfig);
      }),

    $.Deferred(function (deferred) {
      $(deferred.resolve);
    })
  ).done(function () {
    if (hostSeries.length === 0) {
      return dashboard;
    }

    var displayMetrics = (displayMetric) ? displayMetric.split(',') : null;
    var showDashs = genDashs(displayMetrics, plugins);

    for (var plugin in showDashs) {
      var metric = plugin;
      var seriesAlias = ('alias' in showDashs[plugin].config) ? showDashs[plugin].config.alias : null;
      var matchedSeries = [];

      if (showDashs[plugin].config.multi) {
        var metricsExt = getExtendedMetrics(matchSeries(prefix, metric, plugin, hostSeries, showDashs), prefix);
        for (var i = 0, mlen = metricsExt.length; i < mlen; i++) {
          matchedSeries.push(matchSeries(prefix, metricsExt[i], plugin, hostSeries, showDashs));
        }
      } else {
        matchedSeries.push(matchSeries(prefix, metric, plugin, hostSeries, showDashs));
      }

      for (var j = 0, slen = matchedSeries.length; j < slen; j++) {
        for (var k = 0, flen = showDashs[plugin].func.length; k < flen; k++) {
          var metricFunc = showDashs[plugin].func[k];
          dashboard.rows.push(setupRow(metric.toUpperCase, [metricFunc(matchedSeries[j], seriesAlias, 12, interval)]));
        }
      }
    }

    // Return dashboard
    callback(dashboard);
  });
};
<|endoftext|>


<commit_before>//Copyright 2014, Small Picture, Inc.
	//1/19/14 by DW
		//This is a shell for developing the functionality of the Fargo back-end.
		//When done, it will take requests saying that a named outline has updated.
		//It will know how to find the OPML, and from there, to find a "package" of updates.
		//Which it will then parse, and upload to a bucket on S3.
		//Still have a ways to go, but it's fun, and a lot is working! :-)

var AWS = require ("aws-sdk");
var s3 = new AWS.S3 ();
var http = require ('http');

var padWithZeros = function (num, ctplaces) {
	var s = num.toString ();
	while (s.length < ctplaces) {
		s = "0" + s;
		}
	return (s);
	}
var isAlpha = function (ch) {
	return (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')));
	}

var writeStaticFile = function (path, data, type, acl) {
	var bucketname = "";
	if (type == undefined) {
		type = "text/plain";
		}
	if (acl == undefined) {
		acl = "public-read";
		}

	//split path into bucketname and path -- like this: /tmp.scripting.com/testing/one.txt
		if (path.length > 0) {
			if (path [0] == "/") { //delete the slash
				path = path.substr (1);
				}
			var ix = path.indexOf ("/");
			bucketname = path.substr (0, ix);
			path = path.substr (ix + 1);
			}

	var params = {
		ACL: acl,
		ContentType: type,
		Body: data,
		Bucket: bucketname,
		Key: path
		};
	s3.putObject (params, function (err, data) {
		console.log ("Wrote S3 file: http://" + bucketname + "/" + path);
		});
	}

console.log ("starting server");
var counter = 0;
var server = http.createServer(function(request, response) {
	response.writeHead(200, {'Content-Type': 'text/plain'});
	var color = 'blue';
	if (counter % 2 === 1) {
		color = 'no, green';
		}
	response.end(color);
	writeStaticFile ("/tmp.scripting.com/testing/" + padWithZeros (counter, 4) + ".txt", new Date ().toString ());
	counter++;
	});
server.listen (1337);
<commit_msg>Update<commit_after>//Copyright 2014, Small Picture, Inc.
	//1/19/14 by DW
		//This is a shell for developing the functionality of the Fargo back-end.
		//When done, it will take requests saying that a named outline has updated.
		//It will know how to find the OPML, and from there, to find a "package" of updates.
		//Which it will then parse, and upload to a bucket on S3.
		//Still have a ways to go, but it's fun, and a lot is working! :-)

var AWS = require ("aws-sdk");
var s3 = new AWS.S3 ();
var http = require ("http");

//parseUri 1.2.2
	// (c) Steven Levithan <stevenlevithan.com>
	// MIT License
	http://blog.stevenlevithan.com/archives/parseuri

	function parseUri (str) {
		var	o   = parseUri.options,
			m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
			uri = {},
			i   = 14;

		while (i--) uri[o.key[i]] = m[i] || "";

		uri[o.q.name] = {};
		uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
			if ($1) uri[o.q.name][$1] = $2;
		});

		return uri;
	};

	parseUri.options = {
		strictMode: false,
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
		q:   {
			name:   "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
		}
	};
var httpReadUrl = function (url, callback) {
	var httpoptions, httptext = "", httpmethod = "GET";
	//set httpoptions with info from url
		var x = parseUri (url);
		if (x.port.length == 0) {
			x.port = "80";
			}
		httpoptions = {
			host: x.host,
			port: x.port,
			path: x.path,
			method: httpmethod
			};
	var req = http.request (httpoptions, function (res) {
		res.setEncoding ("utf8");
		res.on ("data", function (chunk) {
			httptext += chunk;
			});
		res.on ("end", function () {
			callback (httptext);
			});
		});
	req.on ("error", function (e) {
		console.log ("httpReadUrl error: " + e.message);
		});
	req.end ();
	}
var padWithZeros = function (num, ctplaces) {
	var s = num.toString ();
	while (s.length < ctplaces) {
		s = "0" + s;
		}
	return (s);
	}
var isAlpha = function (ch) {
	return (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')));
	}

var writeStaticFile = function (path, data, type, acl) {
	var bucketname = "";
	if (type == undefined) {
		type = "text/plain";
		}
	if (acl == undefined) {
		acl = "public-read";
		}

	//split path into bucketname and path -- like this: /tmp.scripting.com/testing/one.txt
		if (path.length > 0) {
			if (path [0] == "/") { //delete the slash
				path = path.substr (1);
				}
			var ix = path.indexOf ("/");
			bucketname = path.substr (0, ix);
			path = path.substr (ix + 1);
			}

	var params = {
		ACL: acl,
		ContentType: type,
		Body: data,
		Bucket: bucketname,
		Key: path
		};
	s3.putObject (params, function (err, data) {
		console.log ("Wrote S3 file: http://" + bucketname + "/" + path);
		});
	}

console.log ("starting server");
var counter = 0;
var server = http.createServer(function(request, response) {
	response.writeHead(200, {'Content-Type': 'text/plain'});
	var color = 'blue';
	if (counter % 2 === 1) {
		color = 'no, green';
		}
	response.end(color);
	writeStaticFile ("/tmp.scripting.com/testing/" + padWithZeros (counter, 4) + ".txt", new Date ().toString ());
	counter++;
	});
server.listen (1337);
<|endoftext|>


<commit_before>/**
*	Bubble-Sort's implementation
*	For using in browser, it exposes window.bubbleSort function
*	For node, do require('bubble-sort')
*
*	@author Lakha Singh
*/

(function(){
	var bubbleSort = function( arr ){
		var i, j, tmp;

		for ( i = 0; i < arr.length - 1; i++ ){
			for ( j = 0; j < arr.length - 1 - i; j++ ){
				if ( arr[j] > arr[j+1] ){
					tmp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = tmp;
				}
			}
		}

		return arr;
	}

	// Supporting browser and node env
	if ( typeof window === 'object' ){
		window.sort = window.sort || {};
		window.sort.bubbleSort = bubbleSort;
	}
	else if ( typeof module === 'object' ){
		module.exports = bubbleSort;
	}
}());
<commit_msg>redined comments<commit_after>/**
*	Bubble sort implementation
*
*	For browser, it exposes window.sort.bubbleSort function
*
*	For node, it exposes require('sorting').bubbleSort function
*	do npm install sorting
*
*	@author Lakha Singh
*/

(function(){
	var bubbleSort = function( arr ){
		var i, j, tmp;

		for ( i = 0; i < arr.length - 1; i++ ){
			for ( j = 0; j < arr.length - 1 - i; j++ ){
				if ( arr[j] > arr[j+1] ){
					tmp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = tmp;
				}
			}
		}

		return arr;
	}

	// Supporting browser and node env
	if ( typeof window === 'object' ){
		window.sort = window.sort || {};
		window.sort.bubbleSort = bubbleSort;
	}
	else if ( typeof module === 'object' ){
		module.exports = bubbleSort;
	}
}());
<|endoftext|>


<commit_before>function find(array, cb) {
  for (let i = array.length - 1; i >= 0; i--) {
    if (cb(array[i])) {
      return array[i];
    }
  }
}

const mediaQueries = {
  between(val1, val2) {
    return window.matchMedia(`screen and (min-width: ${val1}px) and ` +
                             `(max-width: ${val2 - 1}px)`);
  },
  atLeast(val) {
    return window.matchMedia(`screen and (min-width: ${val}px)`);
  },
  atMost(val) {
    return window.matchMedia(`screen and (max-width: ${val - 1}px)`);
  }
};

const query = function(bp, nextBp) {
  return {
    is: typeof nextBp === 'number'
          ? mediaQueries.between(bp, nextBp)
          : mediaQueries.atLeast(bp),
    atLeast: mediaQueries.atLeast(bp),
    atMost: mediaQueries.atMost(nextBp || Number.MAX_VALUE)
  };
};

const Breakjs = function(bpEntries) {
  if (!bpEntries) {
    throw new Error('No breakpoints were defined!');
  }

  const bps = [];
  for (const key in bpEntries) {
    const entry = {name: key, value: bpEntries[key]};

    if (find(bps, bp => bp.value === entry.value)) {
      throw new Error('Breakpoint values must be unique.');
    }

    bps.push(entry);
  }

  const breakpoints = bps
    .sort((a, b) => { return a.value > b.value; })
    .map((bp, index) => {
      if (typeof bp.name !== 'string') {
        throw new Error('Invalid breakpoint name -- should be a string.');
      }

      if (typeof bp.value !== 'number' || bp.value < 0 || bp.value >= 9999) {
        throw new Error(`Invalid breakpoint value for ${bp.name}: ${bp.value}`);
      }

      const breakpoint = {name: bp.name};

      // only query
      if (bps.length === 1) {
        breakpoint.query = query(0, null);
      }

      // last query
      else if (index === bps.length - 1) {
        breakpoint.query = query(bp.value, null);
      }

      // query inbetween
      else {
        breakpoint.query = query(bp.value, bps[index + 1].value);
      }

      return breakpoint;
    });

  function getBreakpoint(breakpointName) {
    const findObj = find(breakpoints, bp => bp.name === breakpointName);

    if (!findObj) {
      throw new Error('invalid breakpoint name');
    }

    return findObj;
  }

  const changeListeners = [];

  return {
    breakpoints: bps,

    /**
     * Check if the current window size is the given size
     * @param  {String} size
     * @return {Boolean}
     */
    is(name) {
      return getBreakpoint(name).query.is.matches;
    },

    /**
     * Check if the current window size at least the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atLeast(name) {
      return getBreakpoint(name).query.atLeast.matches;
    },

    /**
     * Check if the current window size at most the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atMost(name) {
      return getBreakpoint(name).query.atMost.matches;
    },

    current() {
      const findObj = find(breakpoints, bp => bp.query.is.matches);

      if (findObj) {
        return findObj.name;
      }
    },

    addChangeListener(listener) {
      breakpoints.forEach(bp => {
        const changeListener = () => {
          var current = this.current();
          if (current === bp.name) {
            listener(current);
          }
        };

        changeListeners.push({
          original: listener,
          created: changeListener
        });

        bp.query.is.addListener(changeListener);
      });
    },

    removeChangeListener(listener) {
      breakpoints.forEach(bp => {
        const findObj = find(changeListeners, cl => cl.original === listener);

        if (findObj) {
          bp.query.is.removeListener(findObj.created);
          changeListeners.splice(changeListeners.indexOf(findObj), 1);
        }
      });
    }
  };
};

if (typeof window !== 'undefined') {
  window.Breakjs = Breakjs;
}

export default Breakjs;
<commit_msg>unnecessary condition removed<commit_after>function find(array, cb) {
  for (let i = array.length - 1; i >= 0; i--) {
    if (cb(array[i])) {
      return array[i];
    }
  }
}

const mediaQueries = {
  between(val1, val2) {
    return window.matchMedia(`screen and (min-width: ${val1}px) and ` +
                             `(max-width: ${val2 - 1}px)`);
  },
  atLeast(val) {
    return window.matchMedia(`screen and (min-width: ${val}px)`);
  },
  atMost(val) {
    return window.matchMedia(`screen and (max-width: ${val - 1}px)`);
  }
};

const query = function(bp, nextBp) {
  return {
    is: typeof nextBp === 'number'
          ? mediaQueries.between(bp, nextBp)
          : mediaQueries.atLeast(bp),
    atLeast: mediaQueries.atLeast(bp),
    atMost: mediaQueries.atMost(nextBp || Number.MAX_VALUE)
  };
};

const Breakjs = function(bpEntries) {
  if (!bpEntries) {
    throw new Error('No breakpoints were defined!');
  }

  const bps = [];
  for (const key in bpEntries) {
    const entry = {name: key, value: bpEntries[key]};

    if (find(bps, bp => bp.value === entry.value)) {
      throw new Error('Breakpoint values must be unique.');
    }

    bps.push(entry);
  }

  const breakpoints = bps
    .sort((a, b) => { return a.value > b.value; })
    .map((bp, index) => {
      if (typeof bp.name !== 'string') {
        throw new Error('Invalid breakpoint name -- should be a string.');
      }

      if (typeof bp.value !== 'number' || bp.value < 0) {
        throw new Error(`Invalid breakpoint value for ${bp.name}: ${bp.value}`);
      }

      const breakpoint = {name: bp.name};

      // only query
      if (bps.length === 1) {
        breakpoint.query = query(0, null);
      }

      // last query
      else if (index === bps.length - 1) {
        breakpoint.query = query(bp.value, null);
      }

      // query inbetween
      else {
        breakpoint.query = query(bp.value, bps[index + 1].value);
      }

      return breakpoint;
    });

  function getBreakpoint(breakpointName) {
    const findObj = find(breakpoints, bp => bp.name === breakpointName);

    if (!findObj) {
      throw new Error('invalid breakpoint name');
    }

    return findObj;
  }

  const changeListeners = [];

  return {
    breakpoints: bps,

    /**
     * Check if the current window size is the given size
     * @param  {String} size
     * @return {Boolean}
     */
    is(name) {
      return getBreakpoint(name).query.is.matches;
    },

    /**
     * Check if the current window size at least the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atLeast(name) {
      return getBreakpoint(name).query.atLeast.matches;
    },

    /**
     * Check if the current window size at most the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atMost(name) {
      return getBreakpoint(name).query.atMost.matches;
    },

    current() {
      const findObj = find(breakpoints, bp => bp.query.is.matches);

      if (findObj) {
        return findObj.name;
      }
    },

    addChangeListener(listener) {
      breakpoints.forEach(bp => {
        const changeListener = () => {
          var current = this.current();
          if (current === bp.name) {
            listener(current);
          }
        };

        changeListeners.push({
          original: listener,
          created: changeListener
        });

        bp.query.is.addListener(changeListener);
      });
    },

    removeChangeListener(listener) {
      breakpoints.forEach(bp => {
        const findObj = find(changeListeners, cl => cl.original === listener);

        if (findObj) {
          bp.query.is.removeListener(findObj.created);
          changeListeners.splice(changeListeners.indexOf(findObj), 1);
        }
      });
    }
  };
};

if (typeof window !== 'undefined') {
  window.Breakjs = Breakjs;
}

export default Breakjs;
<|endoftext|>


<commit_before>import 'array.prototype.find';

let mediaQueries = {
  between(val1, val2) {
    return window.matchMedia(`(min-width: ${val1}px) and
                              (max-width: ${val2 - 1}px)`);
  },
  atLeast(val) {
    return window.matchMedia(`(min-width: ${val}px)`);
  },
  atMost(val) {
    return window.matchMedia(`(max-width: ${val - 1}px)`);
  }
};

let Query = function(bp, nextBp) {
  return {
    is: bp && nextBp
          ? mediaQueries.between(bp, nextBp)
          : mediaQueries.atLeast(bp),
    atLeast: mediaQueries.atLeast(bp),
    atMost: mediaQueries.atMost(nextBp || 9999)
  };
};

let Breakjs = function(bpEntries) {
  let bps = [];
  for (let key in bpEntries) {
    bps.push({name: key, value: bpEntries[key]});
  }

  let breakpoints = bps.map((bp, index) => {
    let breakpoint = {name: bp.name};

    // only query
    if (bps.length === 1) {
      breakpoint.query = Query(0, null);
    }

    // last query
    else if (index === bps.length - 1) {
      breakpoint.query = Query(bp.value, null);
    }

    // query inbetween
    else {
      breakpoint.query = Query(bp.value, bps[index + 1].value);
    }

    return breakpoint;
  });

  function getBreakpoint(breakpointName) {
    let find = breakpoints.find(
      bp => bp.name.toLowerCase() === breakpointName.toLowerCase()
    );

    if (!find) {
      throw new Error('invalid breakpoint name');
    }

    return find;
  }

  return {
    breakpoints: bps,

    /**
     * Check if the current window size is the given size
     * @param  {String} size
     * @return {Boolean}
     */
    is(name) {
      return getBreakpoint(name).query.is.matches;
    },

    /**
     * Check if the current window size at least the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atLeast(name) {
      return getBreakpoint(name).query.atLeast.matches;
    },

    /**
     * Check if the current window size at most the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atMost(name) {
      return getBreakpoint(name).query.atMost.matches;
    },

    current() {
      return breakpoints.find(bp => bp.query.is.matches);
    },

    addEventListener(listener) {
      breakpoints.forEach((bp) => {
        bp.query.is.addListener(() => { listener(bp.name); });
        bp.query.atLeast.addListener(() => { listener(bp.name); });
        bp.query.atMost.addListener(() => { listener(bp.name); });
      });
    }
  };
};

if (typeof window !== 'undefined') {
  window.Breakjs = Breakjs;
}

export default Breakjs;
<commit_msg>expose original breakpoints object<commit_after>import 'array.prototype.find';

let mediaQueries = {
  between(val1, val2) {
    return window.matchMedia(`(min-width: ${val1}px) and
                              (max-width: ${val2 - 1}px)`);
  },
  atLeast(val) {
    return window.matchMedia(`(min-width: ${val}px)`);
  },
  atMost(val) {
    return window.matchMedia(`(max-width: ${val - 1}px)`);
  }
};

let Query = function(bp, nextBp) {
  return {
    is: bp && nextBp
          ? mediaQueries.between(bp, nextBp)
          : mediaQueries.atLeast(bp),
    atLeast: mediaQueries.atLeast(bp),
    atMost: mediaQueries.atMost(nextBp || 9999)
  };
};

let Breakjs = function(bpEntries) {
  let bps = [];
  for (let key in bpEntries) {
    bps.push({name: key, value: bpEntries[key]});
  }

  let breakpoints = bps.map((bp, index) => {
    let breakpoint = {name: bp.name};

    // only query
    if (bps.length === 1) {
      breakpoint.query = Query(0, null);
    }

    // last query
    else if (index === bps.length - 1) {
      breakpoint.query = Query(bp.value, null);
    }

    // query inbetween
    else {
      breakpoint.query = Query(bp.value, bps[index + 1].value);
    }

    return breakpoint;
  });

  function getBreakpoint(breakpointName) {
    let find = breakpoints.find(
      bp => bp.name.toLowerCase() === breakpointName.toLowerCase()
    );

    if (!find) {
      throw new Error('invalid breakpoint name');
    }

    return find;
  }

  return {
    breakpoints: bpEntries,

    /**
     * Check if the current window size is the given size
     * @param  {String} size
     * @return {Boolean}
     */
    is(name) {
      return getBreakpoint(name).query.is.matches;
    },

    /**
     * Check if the current window size at least the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atLeast(name) {
      return getBreakpoint(name).query.atLeast.matches;
    },

    /**
     * Check if the current window size at most the given size
     * @param  {String} size
     * @return {Boolean}
     */
    atMost(name) {
      return getBreakpoint(name).query.atMost.matches;
    },

    current() {
      return breakpoints.find(bp => bp.query.is.matches);
    },

    addEventListener(listener) {
      breakpoints.forEach((bp) => {
        bp.query.is.addListener(() => { listener(bp.name); });
        bp.query.atLeast.addListener(() => { listener(bp.name); });
        bp.query.atMost.addListener(() => { listener(bp.name); });
      });
    }
  };
};

if (typeof window !== 'undefined') {
  window.Breakjs = Breakjs;
}

export default Breakjs;
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const rimraf = require('rimraf').sync
const rollup = require('rollup')
const uglify = require('uglify-js')
const zlib = require('zlib')

/**
 * Rollup configuration template.
 * @type {Object}
 */
const config = require('./rollup.config.js')

/**
 * Establish current working directory.
 * @type {string}
 */
const root = process.cwd()

/**
 * Collection of paths.
 * @type {{build: string, commands: string, dist: string}}
 */
const paths = {
  build: `${root}/build`,
  src: `${root}/src`,
  dist: `${root}/dist`,
}

// Drop dist directory
if (fs.existsSync(paths.dist)) {
  rimraf(paths.dist)
}
// Re-create dist directory
fs.mkdirSync(paths.dist)
// Re-create commands directory
fs.mkdirSync(`${paths.dist}/commands`)

/**
 * Array of files in the commands directory.
 * @type {Array}
 */
const commands = fs.readdirSync(`${paths.src}/commands`)

// Publish commands
commands.forEach(command => {
  return createBuild('commands', command).catch(report)
})

function createBuild (type, filename) {
  const conf = Object.assign({}, config, {
    entry: `${paths.src}/${type}/${filename}`,
    dest: `${paths.dist}/${type}/${filename}`,
  })

  return rollup.rollup(conf).then(bundle => {
    const code = bundle.generate(conf).code
    // const minified = uglify.minify(code).code

    return write(conf.dest, code)
  })
}

/**
 * Write message to console. Handler for promises.
 * @param {*} msg
 */
function report (msg) {
  console.log(msg)
}

/**
 * Write minified code to file.
 * @param {string} dest
 * @param {string} code
 * @returns {Promise}
 */
function write (dest, code) {
  return new Promise((resolve, reject) => {
    function report (extra) {
      console.log(blue(path.relative(process.cwd(), dest)) + ' ' + getSize(code) + (extra || ''))
      resolve()
    }

    fs.writeFile(dest, code, err => {
      if (err) return reject(err)

      // zlib.gzip(code, (err, zipped) => {
      //   if (err) return reject(err)
      //   report(' (gzipped: ' + getSize(zipped) + ')')
      // })
    })
  })
}

/**
 * Get the size of generated code in kilobytes.
 * Shamelessly stolen from https://github.com/vuejs/vue/blob/v2.3.3/build/build.js
 * @param {string} code
 * @returns {string}
 */
function getSize (code) {
  return (code.length / 1024).toFixed(2) + 'kb'
}

/**
 * Output in bold & blue.
 * Shamelessly stolen from https://github.com/vuejs/vue/blob/v2.3.3/build/build.js
 * @param {string} str
 * @returns {string}
 */
function blue (str) {
  return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}
<commit_msg>Include assertions in the build process<commit_after>const fs = require('fs')
const path = require('path')
const rimraf = require('rimraf').sync
const rollup = require('rollup')
const uglify = require('uglify-js')
const zlib = require('zlib')

/**
 * Rollup configuration template.
 * @type {Object}
 */
const config = require('./rollup.config.js')

/**
 * Establish current working directory.
 * @type {string}
 */
const root = process.cwd()

/**
 * Collection of paths.
 * @type {{build: string, commands: string, dist: string}}
 */
const paths = {
  build: `${root}/build`,
  src: `${root}/src`,
  dist: `${root}/dist`,
}

// Drop dist directory
if (fs.existsSync(paths.dist)) {
  rimraf(paths.dist)
}
// Re-create dist directory
fs.mkdirSync(paths.dist)
// Re-create commands directory
fs.mkdirSync(`${paths.dist}/commands`)
// Re-create assertions directory
fs.mkdirSync(`${paths.dist}/assertions`)

/**
 * Array of files in the commands directory.
 * @type {Array}
 */
const commands = fs.readdirSync(`${paths.src}/commands`)

// Publish commands
commands.forEach(command => {
  return createBuild('commands', command).catch(report)
})

/**
 * Array of files in the assertions directory.
 * @type {Array}
 */
const assertions = fs.readdirSync(`${paths.src}/assertions`)

// Publish assertions
assertions.forEach(assertion => {
  return createBuild('assertions', assertion).catch(report)
})

/**
 * Build a custom module.
 * @param {string} type
 * @param {string} filename
 * @returns {Promise.<TResult>}
 */
function createBuild (type, filename) {
  const conf = Object.assign({}, config, {
    entry: `${paths.src}/${type}/${filename}`,
    dest: `${paths.dist}/${type}/${filename}`,
  })

  return rollup.rollup(conf).then(bundle => {
    const code = bundle.generate(conf).code
    // const minified = uglify.minify(code).code

    return write(conf.dest, code)
  })
}

/**
 * Write message to console. Handler for promises.
 * @param {*} msg
 */
function report (msg) {
  console.log(msg)
}

/**
 * Write minified code to file.
 * @param {string} dest
 * @param {string} code
 * @returns {Promise}
 */
function write (dest, code) {
  return new Promise((resolve, reject) => {
    function report (extra) {
      console.log(blue(path.relative(process.cwd(), dest)) + ' ' + getSize(code) + (extra || ''))
      resolve()
    }

    fs.writeFile(dest, code, err => {
      if (err) return reject(err)

      // zlib.gzip(code, (err, zipped) => {
      //   if (err) return reject(err)
      //   report(' (gzipped: ' + getSize(zipped) + ')')
      // })
    })
  })
}

/**
 * Get the size of generated code in kilobytes.
 * Shamelessly stolen from https://github.com/vuejs/vue/blob/v2.3.3/build/build.js
 * @param {string} code
 * @returns {string}
 */
function getSize (code) {
  return (code.length / 1024).toFixed(2) + 'kb'
}

/**
 * Output in bold & blue.
 * Shamelessly stolen from https://github.com/vuejs/vue/blob/v2.3.3/build/build.js
 * @param {string} str
 * @returns {string}
 */
function blue (str) {
  return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}
<|endoftext|>


<commit_before>var quantum = require('quantum-js')
var html = require('quantum-html')
var api = require('quantum-api')
var version = require('quantum-version')
var template = require('quantum-template')
var changelog = require('quantum-changelog')

var hexagon = require('hexagon-js')

var Promise = require('bluebird')
var path = require('path')
var fs = Promise.promisifyAll(require('fs-extra'))
var util = require('./util')
var versions = require('../content/versions.json')

var glob = Promise.promisify(require('glob'))
var Progress = require('progress')
var chalk = require('chalk')
var watch = require('quantum-watch')
var flatten = require('flatten')
var liveServer = require('live-server')

try {
  var privateConfig = require('../config.json')
} catch (e) {
  var privateConfig = {}
}

function buildMetaData (dev) {
  if (dev === true) {
    var targetVersions = [versions.targetVersions.reverse()[0]]
  } else {
    var targetVersions = versions.targetVersions
  }

  return util.moduleList().then(function (moduleNames) {
    var res = {}
    return Promise.all(moduleNames.map(function (moduleName) {
      return fs.readJsonAsync(path.join(util.toModuleDir(moduleName), 'module.json'))
        .then(function (meta) {
          res[moduleName] = meta
        })
    }))
      .then(function () {
        return res
      })
  })
    .then(function (modules) {
      return Promise.props({
        versions: versions.versions,
        targetVersions: targetVersions,
        latest: versions.latest,
        modules: modules
      })
    })
    .then(function (meta) {
      return fs.writeJsonAsync(path.join('target', 'meta.json'), meta)
    })
}

function createBuilds () {
  // create the dx-prefixed and hx-prefixed builds for the latest version of hexagon
  var buildList = [
    { dest: 'target/resources/hexagon/' + versions.latest, embedAssets: true },
    { dest: 'target/resources/hexagon/docs', prefix: 'dx', embedAssets: true, addFavicons: true }
  ]
  return progressSequence('Building Hexagon', chalk.cyan('='), buildList, function (opts) {
    return hexagon.light.build(opts)
  })
}

function buildHexagon (force) { // XXX: do this in the postinstall npm script
  if (force) return createBuilds()
  return fs.accessAsync('target/resources/hexagon/' + versions.latest + '/hexagon.css', fs.F_OK)
    .then(function () {
      console.log(chalk.cyan('Skipping Hexagon Build (Already Exists)'))
    })
    // Hexagon build doesn't already exist
    .catch(createBuilds)
}

// copies the static resources to the target directory
function copyResources () {
  return Promise.all([
    fs.copyAsync('node_modules/font-awesome/css/', 'target/resources/font-awesome/css/'),
    fs.copyAsync('node_modules/font-awesome/fonts/', 'target/resources/font-awesome/fonts/'),
    fs.copyAsync('content/resources/', 'target/resources/'),
    fs.copyAsync('server/', 'target/')
  ])
}

function getTemplateVariables (dev) {
  if (dev === true) {
    var targetVersions = [versions.targetVersions.reverse()[0]]
  } else {
    var targetVersions = versions.targetVersions
  }

  return Promise.props({
    version: versions.latest,
    versionList: versions.versions,
    targetVersionList: targetVersions,
    modules: util.moduleList()
  })
}

function progressSequence (desc, completeStyle, list, func) {
  var bar = new Progress(desc + ' :current/:total [:bar] :percent :etas', { total: list.length, width: 50, complete: completeStyle})
  bar.tick(0)
  return Promise.all(list)
    .map(function (f) {
      return func(f)
        .then(function (res) {
          bar.tick()
          return res
        })
    }, {concurrency: 5})
}

function getOptions (dev) {
  function filenameModifier (filename, version) {
    var baseName = path.basename(filename)
    var moduleName = path.basename(path.dirname(filename))
    return path.join('docs', version, moduleName, baseName)
  }

  var apiOptions = util.moduleList().then(function (modules) {
    var types = {
      'Array': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array',
      'Boolean': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean',
      'Date': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date',
      'Element': 'https://developer.mozilla.org/en/docs/Web/API/Element',
      'Function': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function',
      'HTMLElement': 'https://developer.mozilla.org/en/docs/Web/API/HTMLElement',
      'Node': 'https://developer.mozilla.org/en/docs/Web/API/Node',
      'Number': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number',
      'Object': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object',
      'String': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String',
      'SVGElement': 'https://developer.mozilla.org/en/docs/Web/API/SVGElement'
    }

    modules.forEach(function (moduleId) {
      var moduleType = moduleId.split('-').map(function (part) {
        return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
      }).join('')
      types[moduleType] = '../' + moduleId
    })

    return {
      typeLinks: types
    }
  })

  var taggable = [
    'function',
    'prototype',
    'method',
    'property',
    'object',
    'constructor',
    'returns',
    'event',
    'data',
    'class',
    'extraclass',
    'childclass'
  ]

  var indexable = [
    'param',
    'group'
  ]

  var buildTags = {
    added: {
      order: 8
    },
    updated: {
      order: 7
    },
    deprecated: {
      order: 5
    },
    removed: {
      order: 4
    },
    enhancement: {
      keyText: 'Enhancement',
      iconClass: 'fa fa-fw fa-magic',
      order: 6,
      retain: false,
      removeEntity: false
    },
    bugfix: {
      keyText: 'Bug Fix',
      iconClass: 'fa fa-fw fa-bug',
      order: 3,
      retain: false,
      removeEntity: false
    },
    docs: {
      keyText: 'Documentation',
      iconClass: 'fa fa-fw fa-book',
      order: 2,
      retain: false,
      removeEntity: false
    },
    info: {
      keyText: 'Information',
      iconClass: 'fa fa-fw fa-info',
      order: 1,
      retain: false,
      removeEntity: false
    }
  }

  if (dev === true) {
    var targetVersions = [versions.targetVersions.reverse()[0]]
  } else {
    var targetVersions = versions.targetVersions
  }

  var changelogOptions = {
    tags: buildTags,
    taggable: taggable,
    indexable: indexable,
    versions: versions.versions,
    targetVersions: targetVersions,
    milestoneUrl: privateConfig.milestoneUrl || 'https://github.com/ocadotechnology/hexagonjs/milestones/',
    issueUrl: privateConfig.issueUrl || 'https://github.com/ocadotechnology/hexagonjs/issues/'
  }

  var versionOptions = {
    tags: buildTags,
    taggable: taggable,
    indexable: indexable,
    unmergable: ['examples', 'description', 'extra'],
    filenameModifier: filenameModifier,
    versions: versions.versions,
    targetVersions: targetVersions
  }

  var htmlTransforms = Promise.props({
    html: html.transforms,
    api: apiOptions.then(api),
    changelog: changelog(changelogOptions).transforms,
    docs: require('../transforms/transforms')
  })

  return Promise.props({
    changelogOptions: changelogOptions,
    versionOptions: versionOptions,
    htmlTransforms: htmlTransforms
  })
}

function buildPages (objs, dev) {
  var start = Date.now()
  return Promise.all([getTemplateVariables(dev), getOptions(dev)]).spread(function (templateVariables, options) {
    return progressSequence('Building pages', chalk.green('='), objs, function (obj) {
      return Promise.resolve(obj)
        .then(template({variables: templateVariables}))
        .then(changelog(options.changelogOptions))
        .then(version(options.versionOptions))
        .then(function (res) { return Array.isArray(res) ? res : [res] })
        .then(flatten)
        .map(function (file) {
          if (file.filename.indexOf('modules') > -1) {
            file.filename = file.filename.replace('modules', 'docs')
          }
          return file
        })
        .map(html(options.htmlTransforms))
        .map(html.stringify())
        .map(function (file) {
          if (file.filename.indexOf('docs') === 0) {
            var v = file.filename.split('/')[1]
            file.content = file.content.split('__version__').join(v)
          }
          return file
        })
        .map(quantum.write('target'))
    })
  }).then(function (res) {
    var diff = (Date.now() - start)
    var mins = (diff - diff % 60000) / 60000
    var sec = (diff - (diff - diff % 60000)) / 1000
    console.log(chalk.blue('Done!', mins + 'm', sec + 's'))
    return res
  })
}

function watchPages () {
  // return watch('content/pages/modules/card/**/index.um', { base: 'content/pages'}, function (objs) {return buildPages(objs, true)}).then(function (fun) {
  // return watch('content/pages/changelog/**/index.um', { base: 'content/pages'}, function(objs) {return buildPages(objs, true)}).then(function (fun) {
  return watch('content/pages/**/index.um', { base: 'content/pages'}, function (objs) {return buildPages(objs, true)}).then(function (fun) {
    return fun()
  })
}

function buildOnce () {
  return quantum.read('content/pages/**/index.um', { base: 'content/pages'}).then(buildPages)
}

function startServer () {
  liveServer.start({
    port: 9000,
    root: 'target',
    wait: 50,
    open: false
  })
}

if (process.argv[2] === 'build-hexagon') {
  buildHexagon(true)
} else if (process.argv[2] === 'build-release') {
  buildHexagon(true)
    .then(copyResources)
    .then(buildMetaData)
    .then(buildOnce)
} else {
  buildHexagon(false)
    .then(copyResources)
    .then(function () {
      return buildMetaData(true)
    })
    .then(watchPages)
    .then(startServer)
}
<commit_msg>reverse the order of the changelog and remove some commented out dev code<commit_after>var quantum = require('quantum-js')
var html = require('quantum-html')
var api = require('quantum-api')
var version = require('quantum-version')
var template = require('quantum-template')
var changelog = require('quantum-changelog')

var hexagon = require('hexagon-js')

var Promise = require('bluebird')
var path = require('path')
var fs = Promise.promisifyAll(require('fs-extra'))
var util = require('./util')
var versions = require('../content/versions.json')

var glob = Promise.promisify(require('glob'))
var Progress = require('progress')
var chalk = require('chalk')
var watch = require('quantum-watch')
var flatten = require('flatten')
var liveServer = require('live-server')

try {
  var privateConfig = require('../config.json')
} catch (e) {
  var privateConfig = {}
}

function buildMetaData (dev) {
  if (dev === true) {
    var targetVersions = [versions.targetVersions.reverse()[0]]
  } else {
    var targetVersions = versions.targetVersions
  }

  return util.moduleList().then(function (moduleNames) {
    var res = {}
    return Promise.all(moduleNames.map(function (moduleName) {
      return fs.readJsonAsync(path.join(util.toModuleDir(moduleName), 'module.json'))
        .then(function (meta) {
          res[moduleName] = meta
        })
    }))
      .then(function () {
        return res
      })
  })
    .then(function (modules) {
      return Promise.props({
        versions: versions.versions,
        targetVersions: targetVersions,
        latest: versions.latest,
        modules: modules
      })
    })
    .then(function (meta) {
      return fs.writeJsonAsync(path.join('target', 'meta.json'), meta)
    })
}

function createBuilds () {
  // create the dx-prefixed and hx-prefixed builds for the latest version of hexagon
  var buildList = [
    { dest: 'target/resources/hexagon/' + versions.latest, embedAssets: true },
    { dest: 'target/resources/hexagon/docs', prefix: 'dx', embedAssets: true, addFavicons: true }
  ]
  return progressSequence('Building Hexagon', chalk.cyan('='), buildList, function (opts) {
    return hexagon.light.build(opts)
  })
}

function buildHexagon (force) { // XXX: do this in the postinstall npm script
  if (force) return createBuilds()
  return fs.accessAsync('target/resources/hexagon/' + versions.latest + '/hexagon.css', fs.F_OK)
    .then(function () {
      console.log(chalk.cyan('Skipping Hexagon Build (Already Exists)'))
    })
    // Hexagon build doesn't already exist
    .catch(createBuilds)
}

// copies the static resources to the target directory
function copyResources () {
  return Promise.all([
    fs.copyAsync('node_modules/font-awesome/css/', 'target/resources/font-awesome/css/'),
    fs.copyAsync('node_modules/font-awesome/fonts/', 'target/resources/font-awesome/fonts/'),
    fs.copyAsync('content/resources/', 'target/resources/'),
    fs.copyAsync('server/', 'target/')
  ])
}

function getTemplateVariables (dev) {
  if (dev === true) {
    var targetVersions = [versions.targetVersions.reverse()[0]]
  } else {
    var targetVersions = versions.targetVersions
  }

  return Promise.props({
    version: versions.latest,
    versionList: versions.versions,
    targetVersionList: targetVersions,
    modules: util.moduleList()
  })
}

function progressSequence (desc, completeStyle, list, func) {
  var bar = new Progress(desc + ' :current/:total [:bar] :percent :etas', { total: list.length, width: 50, complete: completeStyle})
  bar.tick(0)
  return Promise.all(list)
    .map(function (f) {
      return func(f)
        .then(function (res) {
          bar.tick()
          return res
        })
    }, {concurrency: 5})
}

function getOptions (dev) {
  function filenameModifier (filename, version) {
    var baseName = path.basename(filename)
    var moduleName = path.basename(path.dirname(filename))
    return path.join('docs', version, moduleName, baseName)
  }

  var apiOptions = util.moduleList().then(function (modules) {
    var types = {
      'Array': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array',
      'Boolean': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean',
      'Date': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date',
      'Element': 'https://developer.mozilla.org/en/docs/Web/API/Element',
      'Function': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function',
      'HTMLElement': 'https://developer.mozilla.org/en/docs/Web/API/HTMLElement',
      'Node': 'https://developer.mozilla.org/en/docs/Web/API/Node',
      'Number': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number',
      'Object': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object',
      'String': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String',
      'SVGElement': 'https://developer.mozilla.org/en/docs/Web/API/SVGElement'
    }

    modules.forEach(function (moduleId) {
      var moduleType = moduleId.split('-').map(function (part) {
        return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
      }).join('')
      types[moduleType] = '../' + moduleId
    })

    return {
      typeLinks: types
    }
  })

  var taggable = [
    'function',
    'prototype',
    'method',
    'property',
    'object',
    'constructor',
    'returns',
    'event',
    'data',
    'class',
    'extraclass',
    'childclass'
  ]

  var indexable = [
    'param',
    'group'
  ]

  var buildTags = {
    added: {
      order: 8
    },
    updated: {
      order: 7
    },
    deprecated: {
      order: 5
    },
    removed: {
      order: 4
    },
    enhancement: {
      keyText: 'Enhancement',
      iconClass: 'fa fa-fw fa-magic',
      order: 6,
      retain: false,
      removeEntity: false
    },
    bugfix: {
      keyText: 'Bug Fix',
      iconClass: 'fa fa-fw fa-bug',
      order: 3,
      retain: false,
      removeEntity: false
    },
    docs: {
      keyText: 'Documentation',
      iconClass: 'fa fa-fw fa-book',
      order: 2,
      retain: false,
      removeEntity: false
    },
    info: {
      keyText: 'Information',
      iconClass: 'fa fa-fw fa-info',
      order: 1,
      retain: false,
      removeEntity: false
    }
  }

  if (dev === true) {
    var targetVersions = [versions.targetVersions.reverse()[0]]
  } else {
    var targetVersions = versions.targetVersions
  }

  var changelogOptions = {
    tags: buildTags,
    taggable: taggable,
    indexable: indexable,
    versions: versions.versions,
    targetVersions: targetVersions,
    reverseVisibleList: true,
    milestoneUrl: privateConfig.milestoneUrl || 'https://github.com/ocadotechnology/hexagonjs/milestones/',
    issueUrl: privateConfig.issueUrl || 'https://github.com/ocadotechnology/hexagonjs/issues/'
  }

  var versionOptions = {
    tags: buildTags,
    taggable: taggable,
    indexable: indexable,
    unmergable: ['examples', 'description', 'extra'],
    filenameModifier: filenameModifier,
    versions: versions.versions,
    targetVersions: targetVersions
  }

  var htmlTransforms = Promise.props({
    html: html.transforms,
    api: apiOptions.then(api),
    changelog: changelog(changelogOptions).transforms,
    docs: require('../transforms/transforms')
  })

  return Promise.props({
    changelogOptions: changelogOptions,
    versionOptions: versionOptions,
    htmlTransforms: htmlTransforms
  })
}

function buildPages (objs, dev) {
  var start = Date.now()
  return Promise.all([getTemplateVariables(dev), getOptions(dev)]).spread(function (templateVariables, options) {
    return progressSequence('Building pages', chalk.green('='), objs, function (obj) {
      return Promise.resolve(obj)
        .then(template({variables: templateVariables}))
        .then(changelog(options.changelogOptions))
        .then(version(options.versionOptions))
        .then(function (res) { return Array.isArray(res) ? res : [res] })
        .then(flatten)
        .map(function (file) {
          if (file.filename.indexOf('modules') > -1) {
            file.filename = file.filename.replace('modules', 'docs')
          }
          return file
        })
        .map(html(options.htmlTransforms))
        .map(html.stringify())
        .map(function (file) {
          if (file.filename.indexOf('docs') === 0) {
            var v = file.filename.split('/')[1]
            file.content = file.content.split('__version__').join(v)
          }
          return file
        })
        .map(quantum.write('target'))
    })
  }).then(function (res) {
    var diff = (Date.now() - start)
    var mins = (diff - diff % 60000) / 60000
    var sec = (diff - (diff - diff % 60000)) / 1000
    console.log(chalk.blue('Done!', mins + 'm', sec + 's'))
    return res
  })
}

function watchPages () {
  return watch('content/pages/**/index.um', { base: 'content/pages'}, function (objs) {return buildPages(objs, true)}).then(function (fun) {
    return fun()
  })
}

function buildOnce () {
  return quantum.read('content/pages/**/index.um', { base: 'content/pages'}).then(buildPages)
}

function startServer () {
  liveServer.start({
    port: 9000,
    root: 'target',
    wait: 50,
    open: false
  })
}

if (process.argv[2] === 'build-hexagon') {
  buildHexagon(true)
} else if (process.argv[2] === 'build-release') {
  buildHexagon(true)
    .then(copyResources)
    .then(buildMetaData)
    .then(buildOnce)
} else {
  buildHexagon(false)
    .then(copyResources)
    .then(function () {
      return buildMetaData(true)
    })
    .then(watchPages)
    .then(startServer)
}
<|endoftext|>


<commit_before>var fs     = require("fs"),
path   = require("path"),
logger = require("../../server/logger.js")
;

exports.mapFiles = function(last_stat) {
  var alloy_list = fs.getList(config.alloy_path,last_stat.mtime);

  // Theme
  var theme = fs.existsSync(path.join(config.alloy_path, 'themes')) ? require(path.join(config.resources_path, 'alloy', 'CFG.js')).theme : null;

  // We need the dirs
  var file_list = fs.getList(config.resources_path);
  var file_list_files = file_list.files; // Keep for root changes
  file_list.files = [];

  var addAllControllers = false;
  var undouble = false;

  for (var i in alloy_list.files) {
    var file = alloy_list.files[i];
    var file_path = file.split(path.sep);
    var ln = file_path.length;
    var la = ln - 1;

    // Alloy root files affect all resources
    if (ln === 1) {
      logger.debug('Alloy root file triggered full push: ' + file);
      file_list.files = fi;e_list_files;
      return file_list;
    }

    if (file_path[0] === 'assets' || file_path[0] === 'lib') {
      file_path.shift();

    } else if (file_path[0] === 'models') {
      file_path[la] = file_path[la][0].toUpperCase() + file_path[la].substr(1);
      file_path.unshift('alloy');

    } else if (file_path[0] === 'migrations') {
      file_path[0] = 'models';
      file_path[la] = file_path[la].substr(15, 1).toUpperCase() + file_path[la].substr(16);
      file_path.unshift('alloy');

      undouble = true;

    } else if (file_path[0] === 'controllers') {
      file_path.unshift('alloy');

    } else if (file_path[0] === 'views') {
      file_path[0] = 'controllers';
      file_path[la] = file_path[la].replace('.xml', '.js');
      file_path.unshift('alloy');

      undouble = true;

    } else if (file_path[0] === 'styles') {

      // app.tss effects all controllers and widget controllers
      if (ln === 2 && file_path[la] === 'app.tss') {
        addAllControllers = true;
        continue;
      }

      file_path[0] = 'controllers';
      file_path[la] = file_path[la].replace('.tss', '.js');
      file_path.unshift('alloy');

      undouble = true;

    } else if (file_path[0] === 'themes') {

      // Not current theme
      if (file_path[1] !== theme) {
        logger.debug('Skipped change in unselected Alloy theme: ' + file);
        continue;
      }

      file_path = file_path.slice(2);

      if (file_path[0] === 'assets') {
        file_path.shift();

      } else if (file_path[0] === 'styles') {

        if (file_path.length === 2 && file_path[la] === 'app.tss') {
          addAllControllers = true;
          continue;
        }

        file_path[0] = 'controllers';
        file_path[file_path.length-1] = file_path[file_path.length-1].replace('.tss', '.js');
        file_path.unshift('alloy');

        undouble = true;
      }

    } else if (file_path[0] === 'widgets') {

      if (file_path[2] === 'lib' || file_path[2] === 'assets') {
        var widget = file_path[1];
        var file_name = file_path[la];
        file_path = file_path.slice(3, -1);
        file_path.push(widget, file_name);

      } else if (file_path[2] === 'models') {
        file_path[la] = file_path[la][0].toUpperCase() + file_path[la].substr(1);
        file_path.unshift('alloy');

      } else if (file_path[0] === 'migrations') {
        file_path[2] = 'models';
        file_path[la] = file_path[la].substr(15, 1).toUpperCase() + file_path[la].substr(16);
        file_path.unshift('alloy');

        undouble = true;

      } else if (file_path[2] === 'controllers') {
        file_path.unshift('alloy');

      } else if (file_path[2] === 'views') {
        file_path[2] = 'controllers';
        file_path[la] = file_path[la].replace('.xml', '.js');
        file_path.unshift('alloy');

        undouble = true;

      } else if (file_path[2] === 'styles') {
        file_path[2] = 'controllers';
        file_path[la] = file_path[la].replace('.tss', '.js');
        file_path.unshift('alloy');

        undouble = true;

      } else {
        logger.debug('Ignored: ' + file);
        continue;
      }

    } else {
      logger.debug('Ignored: ' + file);
      continue;
    }

    var file_path_join = file_path.join(path.sep);
    file_list.files.push(file_path_join);
  }

  if (addAllControllers) {
    logger.debug('Alloy global style change triggered full controllers & widgets push.');

    var controller_files = fs.getList(path.join(config.resources_path, 'alloy', 'controllers')).files;
    var widget_files = fs.getList(path.join(config.resources_path, 'alloy', 'widgets')).files;

    controller_files.forEach(function (val, key, list) {
      list[key] = path.join('alloy', 'controllers', val);
    });

    widget_files.forEach(function (val, key, list) {
      list[key] = path.join('alloy', 'widgets', val);
    });

    file_list.files = file_list.files.concat(controller_files).concat(widget_files);

    undouble = true;
  }

  if (undouble) {
    logger.debug('Removing possible doubles.');

    var undoubled = [];

    file_list.files.forEach(function (val, key, list) {
      if (list.indexOf(undoubled, val) === -1) {
        undoubled.push(val);
      }
    });

    file_list.files = undoubled;
  }

  return file_list;
};

<commit_msg>Fixed typo in alloy.js<commit_after>var fs     = require("fs"),
path   = require("path"),
logger = require("../../server/logger.js")
;

exports.mapFiles = function(last_stat) {
  var alloy_list = fs.getList(config.alloy_path,last_stat.mtime);

  // Theme
  var theme = fs.existsSync(path.join(config.alloy_path, 'themes')) ? require(path.join(config.resources_path, 'alloy', 'CFG.js')).theme : null;

  // We need the dirs
  var file_list = fs.getList(config.resources_path);
  var file_list_files = file_list.files; // Keep for root changes
  file_list.files = [];

  var addAllControllers = false;
  var undouble = false;

  for (var i in alloy_list.files) {
    var file = alloy_list.files[i];
    var file_path = file.split(path.sep);
    var ln = file_path.length;
    var la = ln - 1;

    // Alloy root files affect all resources
    if (ln === 1) {
      logger.debug('Alloy root file triggered full push: ' + file);
      file_list.files = file_list_files;
      return file_list;
    }

    if (file_path[0] === 'assets' || file_path[0] === 'lib') {
      file_path.shift();

    } else if (file_path[0] === 'models') {
      file_path[la] = file_path[la][0].toUpperCase() + file_path[la].substr(1);
      file_path.unshift('alloy');

    } else if (file_path[0] === 'migrations') {
      file_path[0] = 'models';
      file_path[la] = file_path[la].substr(15, 1).toUpperCase() + file_path[la].substr(16);
      file_path.unshift('alloy');

      undouble = true;

    } else if (file_path[0] === 'controllers') {
      file_path.unshift('alloy');

    } else if (file_path[0] === 'views') {
      file_path[0] = 'controllers';
      file_path[la] = file_path[la].replace('.xml', '.js');
      file_path.unshift('alloy');

      undouble = true;

    } else if (file_path[0] === 'styles') {

      // app.tss effects all controllers and widget controllers
      if (ln === 2 && file_path[la] === 'app.tss') {
        addAllControllers = true;
        continue;
      }

      file_path[0] = 'controllers';
      file_path[la] = file_path[la].replace('.tss', '.js');
      file_path.unshift('alloy');

      undouble = true;

    } else if (file_path[0] === 'themes') {

      // Not current theme
      if (file_path[1] !== theme) {
        logger.debug('Skipped change in unselected Alloy theme: ' + file);
        continue;
      }

      file_path = file_path.slice(2);

      if (file_path[0] === 'assets') {
        file_path.shift();

      } else if (file_path[0] === 'styles') {

        if (file_path.length === 2 && file_path[la] === 'app.tss') {
          addAllControllers = true;
          continue;
        }

        file_path[0] = 'controllers';
        file_path[file_path.length-1] = file_path[file_path.length-1].replace('.tss', '.js');
        file_path.unshift('alloy');

        undouble = true;
      }

    } else if (file_path[0] === 'widgets') {

      if (file_path[2] === 'lib' || file_path[2] === 'assets') {
        var widget = file_path[1];
        var file_name = file_path[la];
        file_path = file_path.slice(3, -1);
        file_path.push(widget, file_name);

      } else if (file_path[2] === 'models') {
        file_path[la] = file_path[la][0].toUpperCase() + file_path[la].substr(1);
        file_path.unshift('alloy');

      } else if (file_path[0] === 'migrations') {
        file_path[2] = 'models';
        file_path[la] = file_path[la].substr(15, 1).toUpperCase() + file_path[la].substr(16);
        file_path.unshift('alloy');

        undouble = true;

      } else if (file_path[2] === 'controllers') {
        file_path.unshift('alloy');

      } else if (file_path[2] === 'views') {
        file_path[2] = 'controllers';
        file_path[la] = file_path[la].replace('.xml', '.js');
        file_path.unshift('alloy');

        undouble = true;

      } else if (file_path[2] === 'styles') {
        file_path[2] = 'controllers';
        file_path[la] = file_path[la].replace('.tss', '.js');
        file_path.unshift('alloy');

        undouble = true;

      } else {
        logger.debug('Ignored: ' + file);
        continue;
      }

    } else {
      logger.debug('Ignored: ' + file);
      continue;
    }

    var file_path_join = file_path.join(path.sep);
    file_list.files.push(file_path_join);
  }

  if (addAllControllers) {
    logger.debug('Alloy global style change triggered full controllers & widgets push.');

    var controller_files = fs.getList(path.join(config.resources_path, 'alloy', 'controllers')).files;
    var widget_files = fs.getList(path.join(config.resources_path, 'alloy', 'widgets')).files;

    controller_files.forEach(function (val, key, list) {
      list[key] = path.join('alloy', 'controllers', val);
    });

    widget_files.forEach(function (val, key, list) {
      list[key] = path.join('alloy', 'widgets', val);
    });

    file_list.files = file_list.files.concat(controller_files).concat(widget_files);

    undouble = true;
  }

  if (undouble) {
    logger.debug('Removing possible doubles.');

    var undoubled = [];

    file_list.files.forEach(function (val, key, list) {
      if (list.indexOf(undoubled, val) === -1) {
        undoubled.push(val);
      }
    });

    file_list.files = undoubled;
  }

  return file_list;
};

<|endoftext|>


<commit_before>/**
 * @fileoverview Soundworks client side
 * @author Sebastien.Robaszkiewicz@ircam.fr, Norbert.Schnell@ircam.fr
 */
"use strict";

const MobileDetect = require('mobile-detect');
const ClientModule = require('./ClientModule');

// debug - http://socket.io/docs/logging-and-debugging/#available-debugging-scopes
// localStorage.debug = '*';

var client = {
  type: null,
  ready: null,
  index: -1,
  coordinates: null,
  init: init,
  start: start,

  // deprecated functions
  serial: serial,
  parallel: parallel,

  io: null,
  socket: null,
  send: send,
  receive: receive,
  removeListener: removeListener,
  platform: {
    os: null,
    isMobile: null,
    audioFileExt: '',
    isForbidden: false
  }
};

// get informations about client
const ua = window.navigator.userAgent
const md = new MobileDetect(ua);
client.platform.isMobile = (md.mobile() !== null); // true if phone or tablet
client.platform.os = (() => {
  let os = md.os();

  if (os === 'AndroidOS') {
    return 'android';
  } else if (os === 'iOS') {
    return 'ios';
  } else {
    return 'other';
  }
})();

// audio file extention
const a = document.createElement('audio');
// http://diveintohtml5.info/everything.html
if (!!(a.canPlayType && a.canPlayType('audio/mpeg;'))) {
  client.platform.audioFileExt = '.mp3';
} else if (!!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"'))) {
  client.platform.audioFileExt = '.ogg';
} else {
  client.platform.audioFileExt = '.wav';
}

function init(clientType = 'player', options = {}) {
  client.type = clientType;
  client.io = null;

  if (options.io !== false) {
    var io = require('socket.io-client');

    client.io = io;
    client.socket = client.io('/' + clientType, {
      transports: ['websocket']
    });

    client.ready = new Promise((resolve) => {
      client.receive('client:start', (index) => {
        client.index = index;
        resolve();
      });
    });
  }
}

function start(startFun) {
  let module = startFun; // be compatible with previous version

  if(typeof startFun === 'function')
    module = startFun(ClientModule.sequential, ClientModule.parallel);

  let promise = module.createPromise();

  if (client.io) {
    client.ready
      .then(() => module.launch());

    client.receive('disconnect', () => {
      // console.log('disconnect', client.index);
    });

    client.receive('reconnect', () => {
      // console.log('reconnect', client.index);
    });
  } else {
    // no client i/o, no server
    module.launch();
  }

  return promise;
}

function serial(...modules) {
  console.log('The function "client.serial" is deprecated. Please use the new API instead.');
  return ClientModule.sequential(modules);
}

function parallel(...modules) {
  console.log('The function "client.parallel" is deprecated. Please use the new API instead.');
  return ClientModule.parallel(modules);
}

function send(msg, ...args) {
  if (client.socket)
    client.socket.emit(msg, ...args);
}

function receive(msg, callback) {
  if (client.socket) {
    client.socket.removeListener(msg, callback);
    client.socket.on(msg, callback);
  }
}

function removeListener(msg, callback) {
  if (client.socket)
    client.socket.removeListener(msg, callback);
}

module.exports = client;<commit_msg>fixed client serial/parallel compatibility<commit_after>/**
 * @fileoverview Soundworks client side
 * @author Sebastien.Robaszkiewicz@ircam.fr, Norbert.Schnell@ircam.fr
 */
"use strict";

const MobileDetect = require('mobile-detect');
const ClientModule = require('./ClientModule');

// debug - http://socket.io/docs/logging-and-debugging/#available-debugging-scopes
// localStorage.debug = '*';

var client = {
  type: null,
  ready: null,
  index: -1,
  coordinates: null,
  init: init,
  start: start,

  // deprecated functions
  serial: serial,
  parallel: parallel,

  io: null,
  socket: null,
  send: send,
  receive: receive,
  removeListener: removeListener,
  platform: {
    os: null,
    isMobile: null,
    audioFileExt: '',
    isForbidden: false
  }
};

// get informations about client
const ua = window.navigator.userAgent
const md = new MobileDetect(ua);
client.platform.isMobile = (md.mobile() !== null); // true if phone or tablet
client.platform.os = (() => {
  let os = md.os();

  if (os === 'AndroidOS') {
    return 'android';
  } else if (os === 'iOS') {
    return 'ios';
  } else {
    return 'other';
  }
})();

// audio file extention
const a = document.createElement('audio');
// http://diveintohtml5.info/everything.html
if (!!(a.canPlayType && a.canPlayType('audio/mpeg;'))) {
  client.platform.audioFileExt = '.mp3';
} else if (!!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"'))) {
  client.platform.audioFileExt = '.ogg';
} else {
  client.platform.audioFileExt = '.wav';
}

function init(clientType = 'player', options = {}) {
  client.type = clientType;
  client.io = null;

  if (options.io !== false) {
    var io = require('socket.io-client');

    client.io = io;
    client.socket = client.io('/' + clientType, {
      transports: ['websocket']
    });

    client.ready = new Promise((resolve) => {
      client.receive('client:start', (index) => {
        client.index = index;
        resolve();
      });
    });
  }
}

function start(startFun) {
  let module = startFun; // be compatible with previous version

  if(typeof startFun === 'function')
    module = startFun(ClientModule.sequential, ClientModule.parallel);

  let promise = module.createPromise();

  if (client.io) {
    client.ready
      .then(() => module.launch());

    client.receive('disconnect', () => {
      // console.log('disconnect', client.index);
    });

    client.receive('reconnect', () => {
      // console.log('reconnect', client.index);
    });
  } else {
    // no client i/o, no server
    module.launch();
  }

  return promise;
}

function serial(...modules) {
  console.log('The function "client.serial" is deprecated. Please use the new API instead.');
  return ClientModule.sequential(...modules);
}

function parallel(...modules) {
  console.log('The function "client.parallel" is deprecated. Please use the new API instead.');
  return ClientModule.parallel(...modules);
}

function send(msg, ...args) {
  if (client.socket)
    client.socket.emit(msg, ...args);
}

function receive(msg, callback) {
  if (client.socket) {
    client.socket.removeListener(msg, callback);
    client.socket.on(msg, callback);
  }
}

function removeListener(msg, callback) {
  if (client.socket)
    client.socket.removeListener(msg, callback);
}

module.exports = client;<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');

// hide warning //
var emitter = require('events');
emitter.defaultMaxListeners = 5;

var appRoot = 'src/';
var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));

var paths = {
  root: appRoot,
  source: appRoot + '**/*.js',
  style: 'styles/**/*.css',
  output: 'dist/',
  doc:'./doc',
  test: 'test/**/*.js',
  exampleSource: 'doc/example/',
  exampleOutput: 'doc/example-dist/',
  packageName: pkg.name,
  ignore: [],
  useTypeScriptForDTS: false,
  importsToAdd: [],
  importsToIgnoreForDts: [], // imports that are only used internally. no need to d.ts export them
  jsResources: [appRoot+ 'datatable.js', appRoot+ 'columns-filter.js'], // js to transpile, but not be concated and keeping their relative path
  resources: appRoot + '{**/*.css,**/*.html}',
  sort: true,
  concat: true
};

// files to be traspiled (and concated if selected)
paths.mainSource = [paths.source].concat(paths.jsResources.map(function(resource) {return '!' + resource;}));
// files to be linted
paths.lintSource = paths.source;

module.exports = paths;
<commit_msg>fix(build): add convert-manager to build<commit_after>var path = require('path');
var fs = require('fs');

// hide warning //
var emitter = require('events');
emitter.defaultMaxListeners = 5;

var appRoot = 'src/';
var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));

var paths = {
  root: appRoot,
  source: appRoot + '**/*.js',
  style: 'styles/**/*.css',
  output: 'dist/',
  doc:'./doc',
  test: 'test/**/*.js',
  exampleSource: 'doc/example/',
  exampleOutput: 'doc/example-dist/',
  packageName: pkg.name,
  ignore: [],
  useTypeScriptForDTS: false,
  importsToAdd: [],
  importsToIgnoreForDts: [], // imports that are only used internally. no need to d.ts export them
  jsResources: [
    appRoot + 'datatable.js',
    appRoot + 'columns-filter.js',
    appRoot + 'convert-manager.js'
  ], // js to transpile, but not be concated and keeping their relative path
  resources: appRoot + '{**/*.css,**/*.html}',
  sort: true,
  concat: true
};

// files to be traspiled (and concated if selected)
paths.mainSource = [paths.source].concat(paths.jsResources.map(function(resource) {return '!' + resource;}));
// files to be linted
paths.lintSource = paths.source;

module.exports = paths;
<|endoftext|>