<commit_before>// Dave: checkout https://css-tricks.com/gulp-for-beginners/
// Sass configuration:
// https://code.visualstudio.com/docs/languages/css
// .js stuff:
// https://www.npmjs.com/package/gulp-minify
// https://www.npmjs.com/package/gulp-concat

// https://www.npmjs.com/package/gulp-htmlmin
// https://github.com/kangax/html-minifier

// https://www.npmjs.com/package/gulp-rename
// https://www.npmjs.com/package/gulp-replace

// https://www.npmjs.com/package/gulp-babel  (GOING TO START USING ES6 !!! BIT LATE LOL)

// https://github.com/OverZealous/run-sequence   (I want to concat, then compress)
//                                               e.g. ['task1', 'task2'], 'task3', ['t4', 't5']
//                                                      parallel       then series then parallel

/* NOTE: Windows paths ... I'm using mapped UNC path as L:\
         ... however glob pattern matching doesn't work
         ... properly with this ... e.g. if cwd is L:\
         ... then wildcard matching won't work for files
         ... in cwd.  Even if L:/ is specified.

         ... Have to use a subdirectory.
*/

 // look for gulp in package node-modules
var gulp = require("gulp");
const gutil = require("gulp-util");
var sass = require("gulp-sass");
var minify = require("gulp-minify");
var cleanCSS = require("gulp-clean-css");
var concat = require("gulp-concat");
var runSequence = require("run-sequence");
var htmlmin = require("gulp-htmlmin");
var rename = require("gulp-rename");
var replace = require("gulp-replace");
const babel = require("gulp-babel");
const sourcemaps = require("gulp-sourcemaps");
const fs = require("fs");   // https://nodejs.org/api/fs.html#fs_file_system

// my own attempt at cache busting (don't want to use Gulp(rev) ... not more requires
// and complexity !!! ... Keep It Simple  ) BUT REMEMBER: only call this when
// my sources change ... not intermediates.
// Just using date time (to hex to keep it shorter) ... not a hash per se
// saving to file so if I save the index again, it can use the correct time value
// (using global var with runsequence so I don't have to mess-about with promises
// or vinyl or streams or whatnot ... really am keeping things simple and using
// resources I've already required)
var cachebustHex = null;
gulp.task("setDateTimeHash", function(){
    cachebustHex = ( (new Date()).getTime()  ).toString(16);
    return gulp.src("cacheBustingHashSrc.txt")
        .pipe (replace("NothingHere", cachebustHex))
        .pipe (rename(function (path) {
            path.basename = path.basename.replace("Src", "Dst");
        }))
        .pipe(gulp.dest("./"))
});

gulp.task("cachebust-html", function(){
    fs.readFile("cacheBustingHashDst.txt", "utf-8", function(err, _data) {
            cachebustHex = _data;
            gutil.log("This cachebuster datetime stamp is: " + cachebustHex);
            gulp.start("minify-html");
            gulp.start("cachebust-web-config");
    })
    return true;
});

gulp.task("cachebust-web-config", function(){
    return gulp.src("web.config")
        .pipe (replace(/styles-[0-9a-fA-F]+.css/g, "styles-" + cachebustHex + ".css"))
        .pipe(gulp.dest(function(f) {
            gutil.log("NEARLY DONE");
            return f.base;
        }))
});

gulp.task("TEST", function(){
    gutil.log("In gulp.task TEST: " + cachebustHex);
});

// minifyJS and minifyCSS (as options) break my page at the moment
// need to learn how to pass options to minifyJS here
gulp.task("minify-html", function() {
    return gulp.src("html-debug/*-debug.html")
        .pipe (htmlmin({collapseWhitespace: true, conservativeCollapse: true, caseSensitive: true, minifyJS: true, minifyCSS: false, removeComments: true, removeEmptyElements: false }))
        .pipe (replace("<script></script>", ""))
        .pipe (replace("homepage-min.js", "homepage-" + cachebustHex + ".js"))
        .pipe (replace("defer-min.js", "defer-" + cachebustHex + ".js"))
        .pipe (replace("styles.css", "styles-" + cachebustHex + ".css"))
        .pipe (rename(function (path) {
            path.basename = path.basename.replace("-debug", "");
        }))
        .pipe(gulp.dest("./"))
});

//                                           ************
// MAKE DEBUG VERSION OF index.html ... i.e. index-d.html
//                                           ************
// as well as debugging js (i.e. don't have to prettify all the time when stepping)
// ... wanted to reduce bandwidth use on my account on cloudinary.com
gulp.task("debug-js", function() {
    return gulp.src("html-debug/*-debug.html")
        .pipe (replace("js/homepage-min.js", "js-debug-home/homepage.js"))
        .pipe (replace("js/OrbitControls-min.js", "js-debug-home/OrbitControls.js"))
        .pipe (replace("https://cdn.jsdelivr.net/threejs/0.85.2/three.min.js", "js-debug-home/three.js"))
        .pipe (replace("https://res.cloudinary.com/xarta/image/upload/","images/"))
        .pipe (replace(/v\d{10}\/xarta\//g, ""))
        .pipe (rename(function (path) {
            path.basename = path.basename.replace("-debug", "-d");
        }))
        .pipe(gulp.dest("./"))
});

// change cloudinary (CDN) paths in homepage.js (not homepage-min.js)
// for debugging (so only effects homepage.js which is generated every time)
// - reduce bandwidth use on Cloudinary account when debugging
gulp.task("homepage-js-cloudinary", function() {
    return gulp.src("js-debug-home/homepage.js")
        .pipe (replace("setPath('https://res.cloudinary.com/xarta/image/upload/'", "setPath('https://xarta.co.uk/images/'"))
        .pipe (replace("https://res.cloudinary.com/xarta/image/upload/","images/"))
        .pipe (replace(/v\d{10}\/xarta\//g, ""))
        .pipe(gulp.dest(function(f) {
            return f.base;
        }))
});

gulp.task("sass", function() {
    return gulp.src("css/css-debug/*.scss")
        .pipe(sass())
        .pipe(gulp.dest(function(f) {
            return f.base;
        }))
});

gulp.task("minify-css", function() {
  return gulp.src("css/css-debug/styles.css")
    .pipe(cleanCSS({compatibility: "*"}))
    .pipe(gulp.dest("css"));
});

gulp.task("cachebust-homepage-min", function() {
  return gulp.src("js/homepage-min.js")
    .pipe (rename(function (path) {
        path.basename = path.basename.replace("min", cachebustHex);
    }))
    .pipe(gulp.dest("js"))
});

gulp.task("cachebust-defer-min", function() {
  return gulp.src("js/defer-min.js")
    .pipe (rename(function (path) {
        path.basename = path.basename.replace("min", cachebustHex);
    }))
    .pipe(gulp.dest("js"))
});

gulp.task("cachebust-styles-css", function() {
  return gulp.src("css/styles.css")
    .pipe (rename(function (path) {
        path.basename = path.basename.replace("styles", "styles-" + cachebustHex);
    }))
    .pipe(gulp.dest("css"));
});

gulp.task("minify-home-js", function() {
  return gulp.src("js-debug-home/*.js")
    .pipe(minify({
        ext:{
            src:"-debug.js",
            min:"-min.js"
        },
        exclude: ["tasks"],
        ignoreFiles: [".combo.js", "-min.js", "three.js", "three.module.js"],
        noSource: ["*.js"]
    }))
    .pipe(gulp.dest("js"))
});

// see: https://github.com/gulp-sourcemaps/gulp-sourcemaps
// when I need to, use base e.g.
// gulp.src(['src/test.js', 'src/testdir/test2.js'], { base: 'src' })

/* *
 * pollyfill.js ... from: http://babeljs.io/docs/usage/polyfill/
 *              ... installed using NPM, and copied from module dist folder
 *              ... needed to fix non ES2015 compatibility in Edge (for of)
 *              ... gave error: Object doesn't support property or method 'ToString'
 */
gulp.task("concat-home-js", function() {
  return gulp.src([ "./js-debug-home/polyfill.js",
                    "./js-debug-home/CSS3DRenderer.js",
                    "./js-debug-home/beep.js",
                    "./js-debug-home/water.js",
                    "./js-debug-home/scene.js"], {base: "./"})
    .pipe(sourcemaps.init())
    .pipe(babel({
        presets: ["es2015"]
    }))
    .pipe(concat("homepage.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("./js-debug-home/"));
});

gulp.task("concat-defer-js", function() {
  return gulp.src([ "./js-debug-home/cookie-consent.js",
                    "./js-debug-home/defer-xarta.js"], {base: "./"})
    .pipe(sourcemaps.init())
    .pipe(babel({
        presets: ["es2015"]
    }))
    .pipe(concat("defer.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("./js-debug-home/"));
});

// want the homepage to be fast so concatenate & compress all js files
// to one (but also separates for three stuff, for other pages)
gulp.task("concat-minify-home-js-css", function() {
    runSequence(
        "setDateTimeHash", "concat-home-js", "concat-defer-js", "minify-home-js", "homepage-js-cloudinary", "cachebust-homepage-min",
        "cachebust-defer-min", "minify-css", "cachebust-styles-css", "cachebust-html"
    );
});

gulp.task("xarta", function() {
    gulp.watch("css/css-debug/*.scss", ["sass"]);
    gulp.watch("css/css-debug/*.css", ["concat-minify-home-js-css"]);
    gulp.watch("html-debug/*.html", ["cachebust-html", "debug-js"]);
    gulp.watch(["js-debug-home/*.js", "!js-debug-home/homepage.js", "!js-debug-home/defer.js"], ["concat-minify-home-js-css"]);
});

<commit_msg>trying to get gulpfile to display correctly in syntax highlighter<commit_after>// Dave: checkout https://css-tricks.com/gulp-for-beginners/
// Sass configuration:
// https://code.visualstudio.com/docs/languages/css
// .js stuff:
// https://www.npmjs.com/package/gulp-minify
// https://www.npmjs.com/package/gulp-concat

// https://www.npmjs.com/package/gulp-htmlmin
// https://github.com/kangax/html-minifier

// https://www.npmjs.com/package/gulp-rename
// https://www.npmjs.com/package/gulp-replace

// https://www.npmjs.com/package/gulp-babel  (GOING TO START USING ES6 !!! BIT LATE LOL)

// https://github.com/OverZealous/run-sequence   (I want to concat, then compress)
//                                               e.g. ['task1', 'task2'], 'task3', ['t4', 't5']
//                                                      parallel       then series then parallel

/* NOTE: Windows paths ... I'm using mapped UNC path as L:\
         ... however glob pattern matching doesn't work
         ... properly with this ... e.g. if cwd is L:\
         ... then wildcard matching won't work for files
         ... in cwd.  Even if L:/ is specified.

         ... Have to use a subdirectory.
*/

 // look for gulp in package node-modules
var gulp = require("gulp");
const gutil = require("gulp-util");
var sass = require("gulp-sass");
var minify = require("gulp-minify");
var cleanCSS = require("gulp-clean-css");
var concat = require("gulp-concat");
var runSequence = require("run-sequence");
var htmlmin = require("gulp-htmlmin");
var rename = require("gulp-rename");
var replace = require("gulp-replace");
const babel = require("gulp-babel");
const sourcemaps = require("gulp-sourcemaps");
const fs = require("fs");   // https://nodejs.org/api/fs.html#fs_file_system

// my own attempt at cache busting (don't want to use Gulp(rev) ... not more requires
// and complexity !!! ... Keep It Simple  ) BUT REMEMBER: only call this when
// my sources change ... not intermediates.
// Just using date time (to hex to keep it shorter) ... not a hash per se
// saving to file so if I save the index again, it can use the correct time value
// (using global var with runsequence so I don't have to mess-about with promises
// or vinyl or streams or whatnot ... really am keeping things simple and using
// resources I've already required)
var cachebustHex = null;
gulp.task("setDateTimeHash", function(){
    cachebustHex = ( (new Date()).getTime()  ).toString(16);
    return gulp.src("cacheBustingHashSrc.txt")
        .pipe (replace("NothingHere", cachebustHex))
        .pipe (rename(function (path) {
            path.basename = path.basename.replace("Src", "Dst");
        }))
        .pipe(gulp.dest("./"))
});

gulp.task("cachebust-html", function(){
    fs.readFile("cacheBustingHashDst.txt", "utf-8", function(err, _data) {
            cachebustHex = _data;
            gutil.log("This cachebuster datetime stamp is: " + cachebustHex);
            gulp.start("minify-html");
            gulp.start("cachebust-web-config");
    })
    return true;
});

gulp.task("cachebust-web-config", function(){
    return gulp.src("web.config")
        .pipe (replace(/styles-[0-9a-fA-F]+.css/g, "styles-" + cachebustHex + ".css"))
        .pipe(gulp.dest(function(f) {
            gutil.log("NEARLY DONE");
            return f.base;
        }))
});

gulp.task("TEST", function(){
    gutil.log("In gulp.task TEST: " + cachebustHex);
});

// minifyJS and minifyCSS (as options) break my page at the moment
// need to learn how to pass options to minifyJS here
gulp.task("minify-html", function() {
    return gulp.src("html-debug/*-debug.html")
        .pipe (htmlmin({collapseWhitespace: true, conservativeCollapse: true, caseSensitive: true, minifyJS: true, minifyCSS: false, removeComments: true, removeEmptyElements: false }))
        .pipe (replace("<script></script>", ""))
        .pipe (replace("homepage-min.js", "homepage-" + cachebustHex + ".js"))
        .pipe (replace("defer-min.js", "defer-" + cachebustHex + ".js"))
        .pipe (replace("styles.css", "styles-" + cachebustHex + ".css"))
        .pipe (rename(function (path) {
            path.basename = path.basename.replace("-debug", "");
        }))
        .pipe(gulp.dest("./"))
});

//                                           ************
// MAKE DEBUG VERSION OF index.html ... i.e. index-d.html
//                                           ************
// as well as debugging js (i.e. don't have to prettify all the time when stepping)
// ... wanted to reduce bandwidth use on my account on cloudinary.com
gulp.task("debug-js", function() {
    return gulp.src("html-debug/*-debug.html")
        .pipe (replace("js/homepage-min.js", "js-debug-home/homepage.js"))
        .pipe (replace("js/OrbitControls-min.js", "js-debug-home/OrbitControls.js"))
        .pipe (replace("https://cdn.jsdelivr.net/threejs/0.85.2/three.min.js", "js-debug-home/three.js"))
        .pipe (replace("https://res.cloudinary.com/xarta/image/upload/","images/"))
        .pipe (replace(/v\d{10}\/xarta\//g, ""))
        .pipe (rename(function (path) {
            path.basename = path.basename.replace("-debug", "-d");
        }))
        .pipe(gulp.dest("./"))
});

// change cloudinary (CDN) paths in homepage.js (not homepage-min.js)
// for debugging (so only effects homepage.js which is generated every time)
// - reduce bandwidth use on Cloudinary account when debugging
gulp.task("homepage-js-cloudinary", function() {
    return gulp.src("js-debug-home/homepage.js")
        .pipe (replace("setPath('https://res.cloudinary.com/xarta/image/upload/'", "setPath('https://xarta.co.uk/images/'"))
        .pipe (replace("https://res.cloudinary.com/xarta/image/upload/","images/"))
        .pipe (replace(/v\d{10}\/xarta\//g, ""))
        .pipe(gulp.dest(function(f) {
            return f.base;
        }))
});

gulp.task("sass", function() {
    return gulp.src("css/css-debug/*.scss")
        .pipe(sass())
        .pipe(gulp.dest(function(f) {
            return f.base;
        }))
});

gulp.task("minify-css", function() {
  return gulp.src("css/css-debug/styles.css")
    .pipe(cleanCSS({compatibility: "*"}))
    .pipe(gulp.dest("css"));
});

gulp.task("cachebust-homepage-min", function() {
  return gulp.src("js/homepage-min.js")
    .pipe (rename(function (path) {
        path.basename = path.basename.replace("min", cachebustHex);
    }))
    .pipe(gulp.dest("js"))
});

gulp.task("cachebust-defer-min", function() {
  return gulp.src("js/defer-min.js")
    .pipe (rename(function (path) {
        path.basename = path.basename.replace("min", cachebustHex);
    }))
    .pipe(gulp.dest("js"))
});

gulp.task("cachebust-styles-css", function() {
  return gulp.src("css/styles.css")
    .pipe (rename(function (path) {
        path.basename = path.basename.replace("styles", "styles-" + cachebustHex);
    }))
    .pipe(gulp.dest("css"));
});

gulp.task("minify-home-js", function() {
  return gulp.src("js-debug-home/*.js")
    .pipe(minify({
        ext:{
            src:"-debug.js",
            min:"-min.js"
        },
        exclude: ["tasks"],
        ignoreFiles: [".combo.js", "-min.js", "three.js", "three.module.js"],
        noSource: ["*.js"]
    }))
    .pipe(gulp.dest("js"))
});

// see: https://github.com/gulp-sourcemaps/gulp-sourcemaps
// when I need to, use base e.g.
// gulp.src(["src/test.js", "src/testdir/test2.js"], { base: "src" })

/* pollyfill.js ... from: http://babeljs.io/docs/usage/polyfill/
 *              ... installed using NPM, and copied from module dist folder
 *              ... needed to fix non ES2015 compatibility in Edge (for of)
 *              ... gave error: Object doesn't support property or method 'ToString'
 */
gulp.task("concat-home-js", function() {
  return gulp.src([ "./js-debug-home/polyfill.js",
                    "./js-debug-home/CSS3DRenderer.js",
                    "./js-debug-home/beep.js",
                    "./js-debug-home/water.js",
                    "./js-debug-home/scene.js"], {base: "./"})
    .pipe(sourcemaps.init())
    .pipe(babel({
        presets: ["es2015"]
    }))
    .pipe(concat("homepage.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("./js-debug-home/"));
});

gulp.task("concat-defer-js", function() {
  return gulp.src([ "./js-debug-home/cookie-consent.js",
                    "./js-debug-home/defer-xarta.js"], {base: "./"})
    .pipe(sourcemaps.init())
    .pipe(babel({
        presets: ["es2015"]
    }))
    .pipe(concat("defer.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("./js-debug-home/"));
});

// want the homepage to be fast so concatenate & compress all js files
// to one (but also separates for three stuff, for other pages)
gulp.task("concat-minify-home-js-css", function() {
    runSequence(
        "setDateTimeHash", "concat-home-js", "concat-defer-js", "minify-home-js", "homepage-js-cloudinary", "cachebust-homepage-min",
        "cachebust-defer-min", "minify-css", "cachebust-styles-css", "cachebust-html"
    );
});

gulp.task("xarta", function() {
    gulp.watch("css/css-debug/*.scss", ["sass"]);
    gulp.watch("css/css-debug/*.css", ["concat-minify-home-js-css"]);
    gulp.watch("html-debug/*.html", ["cachebust-html", "debug-js"]);
    gulp.watch(["js-debug-home/*.js", "!js-debug-home/homepage.js", "!js-debug-home/defer.js"], ["concat-minify-home-js-css"]);
});

<|endoftext|>


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

var options = {
  verbose: true
};

if (process.env.FILTER) {
  options.include = new RegExp(process.env.FILTER + '.*\\.js$');
}

// set timezone to UTC
process.env.TZ = 'UTC';

require('urun')(__dirname, options);
<commit_msg>add more loggin to error handlers<commit_after>#!/usr/bin/env node

var options = {
  verbose: true
};

if (process.env.FILTER) {
  options.include = new RegExp(process.env.FILTER + '.*\\.js$');
}

// set timezone to UTC
process.env.TZ = 'UTC';

require('urun')(__dirname, options);

process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});

process.on('unhandledRejection', (reason) => {
  console.log('unhandledRejection', reason);
});

process.on('uncaughtException', (err) => {
  console.log('uncaughtException', err);
});
<|endoftext|>


<commit_before>'use strict';

var bulk = require('bulk-require');

bulk(__dirname, ['spec/**/*.js']);

if (process.env.ONLY_UNIT !== 'true' && process.env.INTEGRATION_TEST_API_KEY && process.env.INTEGRATION_TEST_APPID) {
  // usage: INTEGRATION_TEST_APPID=$APPID INTEGRATION_TEST_API_KEY=$APIKEY npm run dev
  bulk(__dirname, ['integration-spec/**/*.js']);
}
<commit_msg>chore(test): delete indices at the end of the tests (#570)<commit_after>'use strict';

var bulk = require('bulk-require');
var test = require('tape');
var algolia = require('algoliasearch');

bulk(__dirname, ['spec/**/*.js']);

if (process.env.ONLY_UNIT !== 'true' && process.env.INTEGRATION_TEST_API_KEY && process.env.INTEGRATION_TEST_APPID) {
  // usage: INTEGRATION_TEST_APPID=$APPID INTEGRATION_TEST_API_KEY=$APIKEY npm run dev
  bulk(__dirname, ['integration-spec/**/*.js']);

  test.onFinish(cleanupIntegration);
}

function cleanupIntegration() {
  console.log('Deleting all indices');
  var client = algolia(process.env.INTEGRATION_TEST_APPID, process.env.INTEGRATION_TEST_API_KEY);
  var maybeIndices = client.listIndexes();
  maybeIndices.then(content => {
    content.items
      .map(i => i.name)
      .filter(n => n.indexOf('_travis-algoliasearch-helper') !== -1)
      .forEach(n => client.deleteIndex(n));
  });
}
<|endoftext|>


<commit_before>var
	util         = require('util'),
	gulp         = require('gulp'),
	mocha        = require('gulp-mocha'),
	jshint       = require('gulp-jshint'),
	jscs         = require('gulp-jscs'),
	map          = require('gulp-jshint/node_modules/map-stream'),
	jshintErrors = []
;

gulp.task('validate', function() {
	return gulp.src([__filename, './index.js', './lib/**/*.js', './test/**/test_*.js'])
		.pipe(jshint())
		.pipe(map(function (file, cb) {
			if (file.jshint && !file.jshint.success) {
				jshintErrors.push.apply(jshintErrors, file.jshint.results);
			}

			cb(null, file);
		}))
		.pipe(jscs(__dirname + '/.jscs.json'));
});

gulp.task('test', ['validate'], function() {
	return gulp.src('./test/**/test_*.js')
		.pipe(mocha({
			resporter: 'spec',
			bail: true
		}));
});

gulp.task('default', ['test'], function() {
	if (jshintErrors.length) {
		console.error(jshintErrors.map(function(error) {
			return util.format('%s\nLine: %d\nMessage: %s\n\n', error.file, error.error.line, error.error.reason);
		}).join(''));
		process.exit(1);
	}
});
<commit_msg>Update code styling<commit_after>var
	util         = require('util'),
	gulp         = require('gulp'),
	mocha        = require('gulp-mocha'),
	jshint       = require('gulp-jshint'),
	jscs         = require('gulp-jscs'),
	map          = require('gulp-jshint/node_modules/map-stream'),
	jshintErrors = []
;

gulp.task('validate', function() {
	return gulp.src([__filename, './index.js', './lib/**/*.js', './test/**/test_*.js'])
		.pipe(jshint())
		.pipe(map(function (file, cb) {
			if (file.jshint && !file.jshint.success) {
				jshintErrors.push.apply(jshintErrors, file.jshint.results);
			}

			cb(null, file);
		}))
		.pipe(jscs(__dirname + '/.jscs.json'));
});

gulp.task('test', ['validate'], function() {
	return gulp.src('./test/**/test_*.js')
		.pipe(mocha({
			resporter: 'spec',
			bail: true
		}));
});

gulp.task('default', ['test'], function() {
	if (jshintErrors.length) {
		console.error(jshintErrors.map(function(error) {
			return util.format(
				'%s\nLine: %d\nMessage: %s\n\n',
				error.file,
				error.error.line,
				error.error.reason
			);
		}).join(''));
		process.exit(1);
	}
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012 eBay Inc.
 * Author: Senthil Padmanabhan
 *
 * Released under the MIT License
 * http://www.opensource.org/licenses/MIT
 *
 * A standalone rules array to hold the basic spof rules
 * @property rules
 * @type Object[]
 */
var rules = [];

/**
 * A global function to check if a given URL belongs to the a third party domain.
 * A block pattern is maintained which lists all the possible third party scripts
 * that can be included in a page
 * @param {String} url The url to be verified
 * @return {Boolean} The flag indicating if the given url belongs to a third party domain
 * @method is3P
 */
function is3P(url) {
	// Known 3rd-party assets
	// Ref: https://github.com/pmeenan/spof-o-matic/blob/master/src/background.js
	var BLOCK_PATTERN = [
         'platform\.twitter\.com',
         'connect\.facebook\.net',
         'platform\.linkedin\.com',
         'assets\.pinterest\.com',
         'widgets\.digg\.com',
         '.*\.addthis\.com',
         'ajax\.googleapis\.com',
         'code\.jquery\.com',
         'cdn\.jquerytools\.org',
         'apis\.google\.com',
         '.*\.google-analytics\.com',
         '.*\.chartbeat\.com',
         'static\.chartbeat\.com',
         '.*\.2o7\.net',
         '.*\.revsci\.net',
         '.*\.omtrdc\.net',
         'b\.scorecardresearch\.com',
         'cdn\.sailthru\.com',
         '.*browserid\.org',
         'ad\.doubleclick\.net',
         'js\.adsonar\.com',
         'ycharts\.com',
         '.*\.googlecode\.com',
         '.*\.gstatic\.com',
         '.*\.quantserve\.com',
         '.*\.brightcove\.com',
         '.*\.disqus\.com',
         '.*\.lognornal\.com'
    ],
	i,
	l,
	regEx;

	for(i = 0, l = BLOCK_PATTERN.length; i < l; i++) {
		regEx = new RegExp(BLOCK_PATTERN[i], 'im');
		if(regEx.test(url)) {
			return true;
		}
	}
	return false;
}

/**
 * Rule: Load 3rd party JS Asynchronously
 */
rules.push({
	// Rule metadata
	id: "3rdparty-scripts",
	name: "Load 3rd Party JS Asynchronously",
	desc: "Always load 3rd party external scripts asyncronously in a non-blocking pattern",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			pageLength = html.length,
			scripts = $('script'),
			/**
			 * Determines the SPOF score for the script url in the page
			 * @param {String} src The script source for which the score should be determined
			 * @return {int} The score
			 * @method getScore
			 */
			getScore = function(src) {
				var value = 100 - (((html.indexOf(src) + src.length) / pageLength ) * 100);
				return Math.round(value);
			},
			i,
			l,
			script,
			src;

		for(i = 0, l = scripts.length; i < l; i++) {
			script = scripts[i];
			src = script.src;
			if(src && is3P(src)) {
				if(!script.defer || !script.async) {
					reporter.error("ERROR: Possible SPOF attack due to 3rd party script - " + src, src, getScore(src), rule);
				}
			}
		}
	}
});

/**
 * Rule: Load Application JS Non-blocking
 */
rules.push({
	// Rule metadata
	id: "application-js",
	name: "Load Application JS Non-blocking",
	desc: "Load application JS in a non-blocking pattern or towards the end of page",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			pageLength = html.length,
			scripts = $('script'),
			/**
			 * Determines the SPOF score for the script url in the page
			 * @param {String} src The script source for which the score should be determined
			 * @return {int} The score
			 * @method getScore
			 */
			getScore = function(src) {
				var value = 100 - (((html.indexOf(src) + src.length) / pageLength ) * 100);
				return Math.round(value);
			},
			i,
			l,
			script,
			src,
			score;

		for(i = 0, l = scripts.length; i < l; i++) {
			script = scripts[i];
			src = script.src;
			if(src && !is3P(src)) {
				score = getScore(src);
				if(score > 50 && (!script.defer || !script.async)) {
					reporter.warn("WARNING: Possible SPOF attack due to script " + src, src, score, rule);
				}
			}
		}
	}
});

/**
 * Rule: Stylesheet With @font-face
 */
rules.push({
	// Rule metadata
	id: "fontface-stylesheet",
	name: "Stylesheet With @font-face",
	desc: "Try to inline @font-face style. Also make the font files compressed and cacheable",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			pattern = /@font-face[\s\n]*{([^{}]*)}/gim, // RegEx pattern for retrieving all the font-face styles
			urlPattern = /url\s*\(\s*['"]?([^'"]*)['"]?\s*\)/gim, // RegEx pattern for retrieving the urls  font-face styles
			fontFaceMatches,
			fontUrl;

		if(!cssContent || cssContent === "") {
			// Return immediately if CSS content is empty
			return;
		}

		fontFaceMatches = cssContent.match(pattern);
		if(!fontFaceMatches) {
			// Return if no font-face style
			return;
		}

		fontFaceMatches.forEach(function(match) {
			while(fontUrl = urlPattern.exec(match)) {
				fontUrl[1] && reporter.warn("WARNING: Possible SPOF attack due to @font-face style in external stylesheet", fontUrl[1], "NA", rule);
			}
		});
	}
});

/**
 * Rule: Inline @font-face
 */
rules.push({
	// Rule metadata
	id: "fontface-inline",
	name: "Inline @font-face",
	desc: "Make sure the fonts files are compressed, cached and small in size",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			pattern = /@font-face[\s\n]*{([^{}]*)}/gim, // RegEx pattern for retrieving all the font-face styles
			urlPattern = /url\s*\(\s*['"]?([^'"]*)['"]?\s*\)/gim, // RegEx pattern for retrieving the urls  font-face styles
			fontFaceMatches,
			fontUrl;

		fontFaceMatches = html.match(pattern);
		if(!fontFaceMatches) {
			// Return if no font-face style
			return;
		}

		fontFaceMatches.forEach(function(match) {
			while(fontUrl = urlPattern.exec(match)) {
				fontUrl[1] && reporter.warn("WARNING: Possible SPOF attack due to inline @font-face style", fontUrl[1], "NA", rule);
			}
		});
	}
});

/**
 * Rule: Inline @font-face precede Script tag IE issue
 */
rules.push({
	// Rule metadata
	id: "fontface-inline-precede-script-IE",
	name: "Inline @font-face precede Script tag IE issue",
	desc: "Make sure inlined @font-face is not preceded by a SCRIPT tag, causes SPOF in IE",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			scriptStylePattern=/<script[^>]*>[\s\S]*?<\/script>\s*<style[^>]*>[\s\S]*?<\/style>/gim,
			scriptStyleMatches,
			multipleMsg;

		scriptStyleMatches = html.match(scriptStylePattern);
		if(!scriptStyleMatches) {
			// Return if no font-face style
			return;
		}

		multipleMsg = scriptStyleMatches.length > 1? 'multiple occurances of ': '';
		reporter.warn("WARNING: Possible SPOF attack in IE due to " + multipleMsg + "inline @font-face preceded by a SCRIPT tag", "NA", "NA", rule);
	}
});

// Exporting the rules for node environment
if(typeof exports != 'undefined') {
	exports.rules = rules;
}
<commit_msg>Fixing a typo in the LogNormal domain<commit_after>/**
 * Copyright (c) 2012 eBay Inc.
 * Author: Senthil Padmanabhan
 *
 * Released under the MIT License
 * http://www.opensource.org/licenses/MIT
 *
 * A standalone rules array to hold the basic spof rules
 * @property rules
 * @type Object[]
 */
var rules = [];

/**
 * A global function to check if a given URL belongs to the a third party domain.
 * A block pattern is maintained which lists all the possible third party scripts
 * that can be included in a page
 * @param {String} url The url to be verified
 * @return {Boolean} The flag indicating if the given url belongs to a third party domain
 * @method is3P
 */
function is3P(url) {
	// Known 3rd-party assets
	// Ref: https://github.com/pmeenan/spof-o-matic/blob/master/src/background.js
	var BLOCK_PATTERN = [
         'platform\.twitter\.com',
         'connect\.facebook\.net',
         'platform\.linkedin\.com',
         'assets\.pinterest\.com',
         'widgets\.digg\.com',
         '.*\.addthis\.com',
         'ajax\.googleapis\.com',
         'code\.jquery\.com',
         'cdn\.jquerytools\.org',
         'apis\.google\.com',
         '.*\.google-analytics\.com',
         '.*\.chartbeat\.com',
         'static\.chartbeat\.com',
         '.*\.2o7\.net',
         '.*\.revsci\.net',
         '.*\.omtrdc\.net',
         'b\.scorecardresearch\.com',
         'cdn\.sailthru\.com',
         '.*browserid\.org',
         'ad\.doubleclick\.net',
         'js\.adsonar\.com',
         'ycharts\.com',
         '.*\.googlecode\.com',
         '.*\.gstatic\.com',
         '.*\.quantserve\.com',
         '.*\.brightcove\.com',
         '.*\.disqus\.com',
         '.*\.lognormal\.com'
    ],
	i,
	l,
	regEx;

	for(i = 0, l = BLOCK_PATTERN.length; i < l; i++) {
		regEx = new RegExp(BLOCK_PATTERN[i], 'im');
		if(regEx.test(url)) {
			return true;
		}
	}
	return false;
}

/**
 * Rule: Load 3rd party JS Asynchronously
 */
rules.push({
	// Rule metadata
	id: "3rdparty-scripts",
	name: "Load 3rd Party JS Asynchronously",
	desc: "Always load 3rd party external scripts asyncronously in a non-blocking pattern",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			pageLength = html.length,
			scripts = $('script'),
			/**
			 * Determines the SPOF score for the script url in the page
			 * @param {String} src The script source for which the score should be determined
			 * @return {int} The score
			 * @method getScore
			 */
			getScore = function(src) {
				var value = 100 - (((html.indexOf(src) + src.length) / pageLength ) * 100);
				return Math.round(value);
			},
			i,
			l,
			script,
			src;

		for(i = 0, l = scripts.length; i < l; i++) {
			script = scripts[i];
			src = script.src;
			if(src && is3P(src)) {
				if(!script.defer || !script.async) {
					reporter.error("ERROR: Possible SPOF attack due to 3rd party script - " + src, src, getScore(src), rule);
				}
			}
		}
	}
});

/**
 * Rule: Load Application JS Non-blocking
 */
rules.push({
	// Rule metadata
	id: "application-js",
	name: "Load Application JS Non-blocking",
	desc: "Load application JS in a non-blocking pattern or towards the end of page",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			pageLength = html.length,
			scripts = $('script'),
			/**
			 * Determines the SPOF score for the script url in the page
			 * @param {String} src The script source for which the score should be determined
			 * @return {int} The score
			 * @method getScore
			 */
			getScore = function(src) {
				var value = 100 - (((html.indexOf(src) + src.length) / pageLength ) * 100);
				return Math.round(value);
			},
			i,
			l,
			script,
			src,
			score;

		for(i = 0, l = scripts.length; i < l; i++) {
			script = scripts[i];
			src = script.src;
			if(src && !is3P(src)) {
				score = getScore(src);
				if(score > 50 && (!script.defer || !script.async)) {
					reporter.warn("WARNING: Possible SPOF attack due to script " + src, src, score, rule);
				}
			}
		}
	}
});

/**
 * Rule: Stylesheet With @font-face
 */
rules.push({
	// Rule metadata
	id: "fontface-stylesheet",
	name: "Stylesheet With @font-face",
	desc: "Try to inline @font-face style. Also make the font files compressed and cacheable",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			pattern = /@font-face[\s\n]*{([^{}]*)}/gim, // RegEx pattern for retrieving all the font-face styles
			urlPattern = /url\s*\(\s*['"]?([^'"]*)['"]?\s*\)/gim, // RegEx pattern for retrieving the urls  font-face styles
			fontFaceMatches,
			fontUrl;

		if(!cssContent || cssContent === "") {
			// Return immediately if CSS content is empty
			return;
		}

		fontFaceMatches = cssContent.match(pattern);
		if(!fontFaceMatches) {
			// Return if no font-face style
			return;
		}

		fontFaceMatches.forEach(function(match) {
			while(fontUrl = urlPattern.exec(match)) {
				fontUrl[1] && reporter.warn("WARNING: Possible SPOF attack due to @font-face style in external stylesheet", fontUrl[1], "NA", rule);
			}
		});
	}
});

/**
 * Rule: Inline @font-face
 */
rules.push({
	// Rule metadata
	id: "fontface-inline",
	name: "Inline @font-face",
	desc: "Make sure the fonts files are compressed, cached and small in size",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			pattern = /@font-face[\s\n]*{([^{}]*)}/gim, // RegEx pattern for retrieving all the font-face styles
			urlPattern = /url\s*\(\s*['"]?([^'"]*)['"]?\s*\)/gim, // RegEx pattern for retrieving the urls  font-face styles
			fontFaceMatches,
			fontUrl;

		fontFaceMatches = html.match(pattern);
		if(!fontFaceMatches) {
			// Return if no font-face style
			return;
		}

		fontFaceMatches.forEach(function(match) {
			while(fontUrl = urlPattern.exec(match)) {
				fontUrl[1] && reporter.warn("WARNING: Possible SPOF attack due to inline @font-face style", fontUrl[1], "NA", rule);
			}
		});
	}
});

/**
 * Rule: Inline @font-face precede Script tag IE issue
 */
rules.push({
	// Rule metadata
	id: "fontface-inline-precede-script-IE",
	name: "Inline @font-face precede Script tag IE issue",
	desc: "Make sure inlined @font-face is not preceded by a SCRIPT tag, causes SPOF in IE",

	// The check function to verify the rule
	check: function($, cssContent, reporter) {
		var rule = this,
			html = $('html').html(),
			scriptStylePattern=/<script[^>]*>[\s\S]*?<\/script>\s*<style[^>]*>[\s\S]*?<\/style>/gim,
			scriptStyleMatches,
			multipleMsg;

		scriptStyleMatches = html.match(scriptStylePattern);
		if(!scriptStyleMatches) {
			// Return if no font-face style
			return;
		}

		multipleMsg = scriptStyleMatches.length > 1? 'multiple occurances of ': '';
		reporter.warn("WARNING: Possible SPOF attack in IE due to " + multipleMsg + "inline @font-face preceded by a SCRIPT tag", "NA", "NA", rule);
	}
});

// Exporting the rules for node environment
if(typeof exports != 'undefined') {
	exports.rules = rules;
}
<|endoftext|>


<commit_before>var spawn = require('child_process').spawn;

var gulp = require('gulp');
var server = require( 'gulp-develop-server' );
var bower = require('gulp-bower');

gulp.task('watch-src', function () {
    return gulp.watch(['src/**/*.js', 'public/**/*.js', 'views/**/*.hbs'], ['restart-server']);
});

gulp.task('dev', ['watch-src', 'start-server']);

gulp.task('prod', function () {
    var server = spawn('node', ['./main.js']);

    server.stdout.on('data', function (data) {
        process.stdout.write(data.toString());
    });

    server.stderr.on('data', function (data) {
        process.stderr.write(data.toString());
    });

    server.on('close', function (code) {
        console.log('server process exited with code ' + code);
    });

    return server;
});

gulp.task('start-server', function (cb) {
    server.listen({
        path: './main.js'
    });

    cb(null);
});

gulp.task('restart-server', function (cb) {
    server.listen({
        path: './main.js'
    }, function (err) {
        if (err) {
            server.restart();
        }
        cb();
    });
});

gulp.task('bower', function (cb) {
    return runBower(cb);
});

function runBower () {
    return bower();
}
<commit_msg>Add bower as a dependency of production<commit_after>var spawn = require('child_process').spawn;

var gulp = require('gulp');
var server = require( 'gulp-develop-server' );
var bower = require('gulp-bower');

gulp.task('watch-src', function () {
    return gulp.watch(['src/**/*.js', 'public/**/*.js', 'views/**/*.hbs'], ['restart-server']);
});

gulp.task('dev', ['watch-src', 'start-server']);

gulp.task('prod', ['bower'], function () {
    var server = spawn('node', ['./main.js']);

    server.stdout.on('data', function (data) {
        process.stdout.write(data.toString());
    });

    server.stderr.on('data', function (data) {
        process.stderr.write(data.toString());
    });

    server.on('close', function (code) {
        console.log('server process exited with code ' + code);
    });

    return server;
});

gulp.task('start-server', function (cb) {
    server.listen({
        path: './main.js'
    });

    cb(null);
});

gulp.task('restart-server', function (cb) {
    server.listen({
        path: './main.js'
    }, function (err) {
        if (err) {
            server.restart();
        }
        cb();
    });
});

gulp.task('bower', function (cb) {
    return runBower(cb);
});

function runBower () {
    return bower();
}
<|endoftext|>


<commit_before>/*! Signal.js - v0.0.2 - 2013-11-23
 * https://github.com/JosephClay/Signal
 * Signal may be freely distributed under the MIT license. */

var Signal = (function() {

		/**
		 * Cached regex used to parse event string
		 * @type {RegExp}
		 */
	var _NAME_REGEX = /\w([^:\.])*/g,
		/**
		 * Quick reference to Array.prototype.splice
		 * for duplicating arrays
		 * @type {Function}
		 */
		_splicer = ([]).splice,
		/**
		 * Object merger
		 * @param {Objects}
		 * @return {Object}
		 */
		_extend = function() {
			var args = arguments,
				base = args[0],
				idx = 1, length = args.length,
				key, merger;
			for (; idx < length; idx += 1) {
				merger = args[idx];

				for (key in merger) {
					base[key] = merger[key];
				}
			}
		},
		/**
		 * Unique Id
		 * @type {Number}
		 */
		_subid = 0;

	var Signal = function() {
		/**
		 * Holds cached, parsed event keys by string
		 * @type {Object}
		 */
		this._cache = {};

		/**
		 * Holds active events by handle + event + namespace
		 * @type {Object}
		 */
		this._active = {};

		/**
		 * Holds inactive events by handle - lazy creation
		 * @type {Object}
		 */
		// this._inactive;

		/**
		 * Holds subscriptions - lazy creation
		 * @type {Object}
		 */
		// this._subscriptions;
	};

	/**
	 * Returns a new Signal instance
	 * @return {Signal}
	 */
	Signal.construct = function() {
		return new Signal();
	};

	/**
	 * Klass extend method
	 * @param  {Function} constructor
	 * @param  {Object} extension   prototype extension
	 * @return {Function} constructor
	 */
	Signal.extend = function(constructor, extension) {
		var hasConstructor = (typeof constructor === 'function');
		if (!hasConstructor) { extension = constructor; }

		var self = this,
			fn = function() {
				var ret = self.apply(this, arguments);
				if (hasConstructor) {
					ret = constructor.apply(this, arguments);
				}
				return ret;
			};

		// Add properties to the object
		_extend(fn, this);

		// Duplicate the prototype
		var NoOp = function() {};
		NoOp.prototype = this.prototype;
		fn.prototype = new NoOp();

		// Merge the prototypes
		_extend(fn.prototype, this.prototype, extension);
		fn.prototype.constructor = constructor || fn;

		return fn;
	};

	Signal.prototype = {

		constructor: Signal,

		subscribe: function(name, func) {
			this._subscriptions = this._subscriptions || {};

			var id = this._uniqueSubId(),
				location = this._subscriptions[name] || (this._subscriptions[name] = []);

			func.__subid__ = id;
			location.push(func);

			return id;
		},

		unsubscribe: function(name, id) {
			this._subscriptions = this._subscriptions || {};

			var location = this._subscriptions[name];
			if (!location) { return; }

			var idx = 0, length = location.length;
			for (; idx < length; idx += 1) {
				if (location[idx].__subid__ === id) {
					location.splice(idx, 1);
					return true;
				}
			}

			return false;
		},

		dispatch: function() {
			this._subscriptions = this._subscriptions || {};

			var args = arguments,
				name = _splicer.call(args, 0, 1)[0],
				location = this._subscriptions[name] || (this._subscriptions[name] = []),
				idx = 0, length = location.length,
				func;
			for (; idx < length; idx++) {
				func = location[idx];
				if (func) { func.apply(null, args); }
			}
		},

		/* Disable | Enable *************************************/
		disable: function(handle) {
			this._inactive = this._inactive || {};
			this._inactive[handle] = this._inactive[handle] || {};
			this._inactive[handle] = _extend({}, this._active[handle]);
			delete this._active[handle];

			return this;
		},

		enable: function(handle) {
			this._inactive = this._inactive || {};
			this._active[handle] = this._active[handle] || {};
			this._active[handle] = _extend({}, this._inactive[handle]);
			delete this._inactive[handle];

			return this;
		},

		/* On | Off ************************************************/
		on: function(eventname, callback) {
			var eventConfig, location,
				cacheConfig = this._cache[eventname];

			if (cacheConfig) {
				eventConfig = cacheConfig;
				location = this._getEventLocation(eventConfig);
			} else {
				eventConfig = this._cache[eventname] = this._parseConfig(eventname);
				location = this._createEventLocation(eventConfig);
			}

			location.push(callback);

			return this;
		},
		bind: function() { this.on.apply(this, arguments); },

		off: function(eventname) {
			var eventConfig,
				cacheConfig = this._cache[eventname];

			if (cacheConfig) {
				eventConfig = cacheConfig;
			} else {
				eventConfig = this._cache[eventname] = this._parseConfig(eventname);
			}

			if (eventConfig.hasNamespace) { // Has a namespace
				this._active[eventConfig.handle][eventConfig.evt][eventConfig.namespace].length = 0;
			} else { // Does not have a namespace
				this._active[eventConfig.handle][eventConfig.evt] = { '': [] };
			}

			return this;
		},
		unbind: function() { this.off.apply(this, arguments); },

		once: function(eventname, callback) {
			var hasRan = false, memo;

			return this.on(eventname, function() {
				return function() {
					if (hasRan) { return memo; }
					hasRan = true;

					memo = callback.apply(this, arguments);
					callback = null;

					return memo;
				};
			});
		},

		/* Trigger ************************************************/
		trigger: function() {
			var args = arguments,
				eventname = _splicer.call(args, 0, 1)[0],
				cacheConfig = this._cache[eventname];

			if (cacheConfig) {
				eventConfig = cacheConfig;
			} else {
				eventConfig = this._cache[eventname] = this._parseConfig(eventname);
			}

			var location = this._getEventLocation(eventConfig);
			if (!location) { return this; }

			if (eventConfig.hasNamespace) { // If there's a namespace, trigger only that array
				this._callEventArray(location, args);
			} else { // Else, trigger everything registered to the event
				var subSignal = this._active[eventConfig.handle][eventConfig.evt], key;
				for (key in subSignal) {
					this._callEventArray(subSignal[key], args);
				}
			}

			return this;
		},

		/* ListenTo | StopListening ********************************/
		listenTo: function(obj, eventname, callback) {
			obj.on(eventname, callback);
			return this;
		},
		stopListening: function(obj, eventname) {
			obj.off(eventname);
			return this;
		},

		/* Private *************************************************/
		_uniqueSubId: function() {
			return 's' + _subid++;
		},

		_callEventArray: function(events, args) {
			args = args || [];

			var idx = 0, length = events.length,
				evt;
			for (; idx < length; idx += 1) {
				evt = events[idx];
				if (!evt) { continue; }
				if (evt.apply(null, args) === false) { return; }
			}
		},

		_parseConfig: function(eventname) {
			var hasHandle = (eventname.indexOf(':') !== -1) ? true : false,
				hasNamespace = (eventname.indexOf('.') !== -1) ? true : false,
				matches = eventname.match(_NAME_REGEX),
				eventConfig = {};

			if (hasHandle && hasNamespace) { // Has handle, event, namespace

				eventConfig.handle = matches[0];
				eventConfig.evt = matches[1];
				eventConfig.namespace = matches[2];

			} else if (hasHandle && !hasNamespace) { // Has handle and event

				eventConfig.handle = matches[0];
				eventConfig.evt = matches[1];
				eventConfig.namespace = '';

			} else if (hasNamespace && !hasHandle) { // Has event and namespace

				eventConfig.handle = '';
				eventConfig.evt = matches[0];
				eventConfig.namespace = matches[1];

			} else { // Has event

				eventConfig.handle = '';
				eventConfig.evt = matches[0];
				eventConfig.namespace = '';

			}

			eventConfig.hasHandle = hasHandle;
			eventConfig.hasNamespace = hasNamespace;

			return eventConfig;
		},

		_getEventLocation: function(eventConfig, location) {
			location = location || this._active;

			var handle = location[eventConfig.handle];
			if (!handle) { return; }

			var evts = handle[eventConfig.evt];
			if (!evts) { return; }

			if (!eventConfig.hasNamespace) { return evts; }

			var namespace = evts[eventConfig.namespace];
			if (!namespace) { return; }

			// Return the location
			return namespace;
		},

		_createEventLocation: function(eventConfig, location) {
			location = location || this._active;

			var handle = location[eventConfig.handle] || (location[eventConfig.handle] = {}),
				evt = handle[eventConfig.evt] || (handle[eventConfig.evt] = {}),
				namespace = evt[eventConfig.namespace] || (evt[eventConfig.namespace] = []);

			return namespace;
		},

		toString: function() {
			return '[Signal]';
		}
	};

	// Create a pub/sub to expose Signal as
	// e.g. Signal.on(), Signal.trigger()
	var pubSub = new Signal();

	// Attach the Signal object as a property
	// of the exposed object so that new instances
	// can be constructed/extended
	// e.g. Signal.core.construct(), Signal.core.extend({})
	pubSub.core = Signal;

	// Expose
	return pubSub;

}());
<commit_msg>Fix bug where location is undefined<commit_after>/*! Signal.js - v0.0.2 - 2013-11-23
 * https://github.com/JosephClay/Signal
 * Signal may be freely distributed under the MIT license. */

var Signal = (function() {

		/**
		 * Cached regex used to parse event string
		 * @type {RegExp}
		 */
	var _NAME_REGEX = /\w([^:\.])*/g,
		/**
		 * Quick reference to Array.prototype.splice
		 * for duplicating arrays
		 * @type {Function}
		 */
		_splicer = ([]).splice,
		/**
		 * Object merger
		 * @param {Objects}
		 * @return {Object}
		 */
		_extend = function() {
			var args = arguments,
				base = args[0],
				idx = 1, length = args.length,
				key, merger;
			for (; idx < length; idx += 1) {
				merger = args[idx];

				for (key in merger) {
					base[key] = merger[key];
				}
			}
		},
		/**
		 * Unique Id
		 * @type {Number}
		 */
		_subid = 0;

	var Signal = function() {
		/**
		 * Holds cached, parsed event keys by string
		 * @type {Object}
		 */
		this._cache = {};

		/**
		 * Holds active events by handle + event + namespace
		 * @type {Object}
		 */
		this._active = {};

		/**
		 * Holds inactive events by handle - lazy creation
		 * @type {Object}
		 */
		// this._inactive;

		/**
		 * Holds subscriptions - lazy creation
		 * @type {Object}
		 */
		// this._subscriptions;
	};

	/**
	 * Returns a new Signal instance
	 * @return {Signal}
	 */
	Signal.construct = function() {
		return new Signal();
	};

	/**
	 * Klass extend method
	 * @param  {Function} constructor
	 * @param  {Object} extension   prototype extension
	 * @return {Function} constructor
	 */
	Signal.extend = function(constructor, extension) {
		var hasConstructor = (typeof constructor === 'function');
		if (!hasConstructor) { extension = constructor; }

		var self = this,
			fn = function() {
				var ret = self.apply(this, arguments);
				if (hasConstructor) {
					ret = constructor.apply(this, arguments);
				}
				return ret;
			};

		// Add properties to the object
		_extend(fn, this);

		// Duplicate the prototype
		var NoOp = function() {};
		NoOp.prototype = this.prototype;
		fn.prototype = new NoOp();

		// Merge the prototypes
		_extend(fn.prototype, this.prototype, extension);
		fn.prototype.constructor = constructor || fn;

		return fn;
	};

	Signal.prototype = {

		constructor: Signal,

		subscribe: function(name, func) {
			this._subscriptions = this._subscriptions || {};

			var id = this._uniqueSubId(),
				location = this._subscriptions[name] || (this._subscriptions[name] = []);

			func.__subid__ = id;
			location.push(func);

			return id;
		},

		unsubscribe: function(name, id) {
			this._subscriptions = this._subscriptions || {};

			var location = this._subscriptions[name];
			if (!location) { return; }

			var idx = 0, length = location.length;
			for (; idx < length; idx += 1) {
				if (location[idx].__subid__ === id) {
					location.splice(idx, 1);
					return true;
				}
			}

			return false;
		},

		dispatch: function() {
			this._subscriptions = this._subscriptions || {};

			var args = arguments,
				name = _splicer.call(args, 0, 1)[0],
				location = this._subscriptions[name] || (this._subscriptions[name] = []),
				idx = 0, length = location.length,
				func;
			for (; idx < length; idx++) {
				func = location[idx];
				if (func) { func.apply(null, args); }
			}
		},

		/* Disable | Enable *************************************/
		disable: function(handle) {
			this._inactive = this._inactive || {};
			this._inactive[handle] = this._inactive[handle] || {};
			this._inactive[handle] = _extend({}, this._active[handle]);
			delete this._active[handle];

			return this;
		},

		enable: function(handle) {
			this._inactive = this._inactive || {};
			this._active[handle] = this._active[handle] || {};
			this._active[handle] = _extend({}, this._inactive[handle]);
			delete this._inactive[handle];

			return this;
		},

		/* On | Off ************************************************/
		on: function(eventname, callback) {
			var eventConfig, location,
				cacheConfig = this._cache[eventname];

			if (cacheConfig) {
				eventConfig = cacheConfig;
				location = this._getEventLocation(eventConfig);
			} else {
				eventConfig = this._cache[eventname] = this._parseConfig(eventname);
				location = this._getEventLocation(eventConfig);
			}

			location.push(callback);

			return this;
		},
		bind: function() { this.on.apply(this, arguments); },

		off: function(eventname) {
			var eventConfig,
				cacheConfig = this._cache[eventname];

			if (cacheConfig) {
				eventConfig = cacheConfig;
			} else {
				eventConfig = this._cache[eventname] = this._parseConfig(eventname);
			}

			if (eventConfig.hasNamespace) { // Has a namespace
				this._active[eventConfig.handle][eventConfig.evt][eventConfig.namespace].length = 0;
			} else { // Does not have a namespace
				this._active[eventConfig.handle][eventConfig.evt] = { '': [] };
			}

			return this;
		},
		unbind: function() { this.off.apply(this, arguments); },

		once: function(eventname, callback) {
			var hasRan = false, memo;

			return this.on(eventname, function() {
				return function() {
					if (hasRan) { return memo; }
					hasRan = true;

					memo = callback.apply(this, arguments);
					callback = null;

					return memo;
				};
			});
		},

		/* Trigger ************************************************/
		trigger: function() {
			var args = arguments,
				eventname = _splicer.call(args, 0, 1)[0],
				cacheConfig = this._cache[eventname];

			if (cacheConfig) {
				eventConfig = cacheConfig;
			} else {
				eventConfig = this._cache[eventname] = this._parseConfig(eventname);
			}

			var location = this._getEventLocation(eventConfig);

			if (eventConfig.hasNamespace) { // If there's a namespace, trigger only that array
				this._callEventArray(location, args);
			} else { // Else, trigger everything registered to the event
				var subSignal = this._active[eventConfig.handle][eventConfig.evt], key;
				for (key in subSignal) {
					this._callEventArray(subSignal[key], args);
				}
			}

			return this;
		},

		/* ListenTo | StopListening ********************************/
		listenTo: function(obj, eventname, callback) {
			obj.on(eventname, callback);
			return this;
		},
		stopListening: function(obj, eventname) {
			obj.off(eventname);
			return this;
		},

		/* Private *************************************************/
		_uniqueSubId: function() {
			return 's' + _subid++;
		},

		_callEventArray: function(events, args) {
			args = args || [];

			var idx = 0, length = events.length,
				evt;
			for (; idx < length; idx += 1) {
				evt = events[idx];
				if (!evt) { continue; }
				if (evt.apply(null, args) === false) { return; }
			}
		},

		_parseConfig: function(eventname) {
			var hasHandle = (eventname.indexOf(':') !== -1) ? true : false,
				hasNamespace = (eventname.indexOf('.') !== -1) ? true : false,
				matches = eventname.match(_NAME_REGEX),
				eventConfig = {};

			if (hasHandle && hasNamespace) { // Has handle, event, namespace

				eventConfig.handle = matches[0];
				eventConfig.evt = matches[1];
				eventConfig.namespace = matches[2];

			} else if (hasHandle && !hasNamespace) { // Has handle and event

				eventConfig.handle = matches[0];
				eventConfig.evt = matches[1];
				eventConfig.namespace = '';

			} else if (hasNamespace && !hasHandle) { // Has event and namespace

				eventConfig.handle = '';
				eventConfig.evt = matches[0];
				eventConfig.namespace = matches[1];

			} else { // Has event

				eventConfig.handle = '';
				eventConfig.evt = matches[0];
				eventConfig.namespace = '';

			}

			eventConfig.hasHandle = hasHandle;
			eventConfig.hasNamespace = hasNamespace;

			return eventConfig;
		},

		_getEventLocation: function(eventConfig, location) {
			location = location || this._active;

			var handle = location[eventConfig.handle] || (location[eventConfig.handle] = {}),
				evt = handle[eventConfig.evt] || (handle[eventConfig.evt] = {}),
				namespace = evt[eventConfig.namespace] || (evt[eventConfig.namespace] = []);

			return namespace;
		},

		toString: function() {
			return '[Signal]';
		}
	};

	// Create a pub/sub to expose Signal as
	// e.g. Signal.on(), Signal.trigger()
	var pubSub = new Signal();

	// Attach the Signal object as a property
	// of the exposed object so that new instances
	// can be constructed/extended
	// e.g. Signal.core.construct(), Signal.core.extend({})
	pubSub.core = Signal;

	// Expose
	return pubSub;

}());<|endoftext|>


<commit_before>var Mocha = require('mocha'),
    fs = require('fs'),
    path = require('path'),
    mocha = null,
    location = null;
var options = {
  include: new RegExp("integration\\/test\\-.*\\.js$")
};

function runClassicTests() {
  if (process.env.FILTER) {
    options.include = new RegExp("integration\\/test\\-.*" + process.env.FILTER + '.*\\.js$');
  }
  process.stdout.write("\033[1;34m[i] \033[0;34mTesting \033[1;34m" + process.env.ORM_PROTOCOL + "\033[0m\n");
  process.stdout.write("\033[1;34m[i] \033[0;34mURI: \033[1;34m" + require('./common').getConnectionString() + "\033[0m\n");

  require('urun')(__dirname, options);
}

location = path.normalize(path.join(__dirname, 'integration2'));
mocha    = new Mocha({reporter: 'nyan'});

fs.readdirSync(location).filter(function(file){
  return file.substr(-3) === '.js';
}).forEach(function(file){
  mocha.addFile(
    path.join(location, file)
  );
});

mocha.run(function(failures){
  if (failures > 0) {
    process.exit(failures);
  } else {
    runClassicTests();
  }
});

<commit_msg>Updates test/run to show which tests are from mocha and which tests are from urun<commit_after>var Mocha    = require('mocha');
var fs       = require('fs');
var path     = require('path');
var location = path.normalize(path.join(__dirname, "integration2"));
var mocha    = new Mocha({
	reporter: "progress"
});

runTests();

function runClassicTests() {
	var options  = {
		include  : new RegExp("integration\\/test\\-.*\\.js$")
	};

	if (process.env.FILTER) {
		options.include = new RegExp("integration\\/test\\-.*" + process.env.FILTER + '.*\\.js$');
	}

	process.stdout.write("\033[1;34m[i] \033[0;34mFramework \033[1;34murun\033[0m\n");
	process.stdout.write("\033[1;34m[i] \033[0;34mTesting \033[1;34m" + process.env.ORM_PROTOCOL + "\033[0m\n");
	process.stdout.write("\033[1;34m[i] \033[0;34mURI: \033[1;34m" + require('./common').getConnectionString() + "\033[0m\n");

	require('urun')(__dirname, options);
}

function runTests() {
	fs.readdirSync(location).filter(function(file){
		return file.substr(-3) === '.js';
	}).forEach(function(file){
		mocha.addFile(
			path.join(location, file)
		);
	});

	process.stdout.write("\033[1;34m[i] \033[0;34mFramework \033[1;34mmocha\033[0m\n");
	process.stdout.write("\033[1;34m[i] \033[0;34mTesting \033[1;34m" + process.env.ORM_PROTOCOL + "\033[0m\n");
	process.stdout.write("\033[1;34m[i] \033[0;34mURI: \033[1;34m" + require('./common').getConnectionString() + "\033[0m\n");

	mocha.run(function (failures) {
		if (failures > 0) {
			process.exit(failures);
		} else {
			runClassicTests();
		}
	});
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var ts = require('gulp-typescript');
var del = require('del');
var webpack = require('webpack');
var gulpFormat = require('gulp-clang-format');
var clangFormat = require('clang-format');

gulp.task('clean', function (cb) {
  del('dist/', cb);
});

gulp.task('es5', function () {
  var tsProject = ts.createProject('tsconfig.json', {
    module: 'commonjs',
    target: 'es5'
  });

  var tsResult = gulp.src(['typings/tsd.d.ts', 'src/**/*.ts'])
    .pipe(ts(tsProject));

  return tsResult.js.pipe(gulp.dest('dist/cjs'));
});

gulp.task('es6', function () {
  var tsProject = ts.createProject('tsconfig.json');

  var tsResult = gulp.src(['typings/tsd.d.ts', 'src/**/*.ts'])
    .pipe(ts(tsProject));

  return tsResult.js.pipe(gulp.dest('dist/es6'));
});

gulp.task('umd', ['es5', 'es6'], function (cb) {
  webpack({
    entry: './dist/cjs/core.js',
    output: {
      filename: 'dist/global/ng-bootstrap.js',
      libraryTarget: 'umd'
    },
    externals: {
      'angular2/angular2': 'angular2/angular2'
    }
  }, function (err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log("[webpack]", stats.toString());
    cb();
  })
});

gulp.task('check-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("NOTE: this will be promoted to an ERROR in the continuous build");
  });
});

gulp.task('enforce-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("ERROR: You forgot to run clang-format on your change.");
    console.log("See https://github.com/ng-bootstrap/core/blob/master/DEVELOPER.md#clang-format");
    process.exit(1);
  });
});

gulp.task('build', ['clean', 'umd', 'check-format']);
gulp.task('default', ['build']);

//formatting
function doCheckFormat() {
  return gulp.src(['src/**/*.ts'])
    .pipe(gulpFormat.checkFormat('file', clangFormat));
}<commit_msg>chore(tooling): add lib.es6 for es5 compilation<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var ts = require('gulp-typescript');
var del = require('del');
var webpack = require('webpack');
var gulpFormat = require('gulp-clang-format');
var clangFormat = require('clang-format');

gulp.task('clean', function (cb) {
  del('dist/', cb);
});

gulp.task('es5', function () {
  var tsProject = ts.createProject('tsconfig.json', {
    module: 'commonjs',
    target: 'es5'
  });

  var tsResult = gulp.src([
      'node_modules/typescript/lib/lib.es6.d.ts',
      'typings/tsd.d.ts',
      'src/**/*.ts'
    ])
    .pipe(ts(tsProject));

  return tsResult.js.pipe(gulp.dest('dist/cjs'));
});

gulp.task('es6', function () {
  var tsProject = ts.createProject('tsconfig.json');

  var tsResult = gulp.src([
      'typings/tsd.d.ts',
      'src/**/*.ts'
    ])
    .pipe(ts(tsProject));

  return tsResult.js.pipe(gulp.dest('dist/es6'));
});

gulp.task('umd', ['es5', 'es6'], function (cb) {
  webpack({
    entry: './dist/cjs/core.js',
    output: {
      filename: 'dist/global/ng-bootstrap.js',
      libraryTarget: 'umd'
    },
    externals: {
      'angular2/angular2': 'angular2/angular2'
    }
  }, function (err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log("[webpack]", stats.toString());
    cb();
  })
});

gulp.task('check-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("NOTE: this will be promoted to an ERROR in the continuous build");
  });
});

gulp.task('enforce-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("ERROR: You forgot to run clang-format on your change.");
    console.log("See https://github.com/ng-bootstrap/core/blob/master/DEVELOPER.md#clang-format");
    process.exit(1);
  });
});

gulp.task('build', ['clean', 'umd', 'check-format']);
gulp.task('default', ['build']);

//formatting
function doCheckFormat() {
  return gulp.src(['src/**/*.ts'])
    .pipe(gulpFormat.checkFormat('file', clangFormat));
}<|endoftext|>


<commit_before>var data = require("./data");
var signup_email = "signup@satisfive.datatactics.ml";
var domain = "satisfive.datatactics.ml";
var sparkpost = require('./sparkpost');

module.exports.isSignup = function(msg) {
	// checks if a user is signing in
    return msg.rcpt_to == signup_email;
};

module.exports.handleSignup = function(msg, res) {
	// creates a new user for that email
	var company_name = msg.content.subject,
		email = msg.msg_from;

	console.log("new signup from", company_name);

	res.send(200);

	return  data.User.findOrCreate({where: {company_email: email},
	defaults: {
		name: company_name,
		company_email: email,
		personnal_email: "",
		alias: company_name + "@" + domain
	}}).then(value, function(){
	    var  msg, thisEmail = "eli.sakov@hotmail.com";
	    msg = new sparkpost.Message({content: {
	      from: 'signedup@satisfive.doma.io',
	      subject: "Thank you for signing up",
	      text: "You may now use your new email at " + value.alias
	    }});
	    msg.addRecipient("name", email);
	    console.log("sent");
	    msg.send();
	});

};<commit_msg>user signup<commit_after>var data = require("./data");
var signup_email = "signup@satisfive.datatactics.ml";
var domain = "satisfive.datatactics.ml";
var sparkpost = require('./sparkpost');

module.exports.isSignup = function(msg) {
	// checks if a user is signing in
    return msg.rcpt_to == signup_email;
};

module.exports.handleSignup = function(msg, res) {
	// creates a new user for that email
	var company_name = msg.content.subject,
		email = msg.msg_from;

	console.log("new signup from", company_name);

	res.send(200);

	return  data.User.findOrCreate({where: {company_email: email},
	defaults: {
		name: company_name,
		company_email: email,
		personnal_email: "",
		alias: company_name + "@" + domain
	}}).then(value, function(){
		if (!value) return;
	    var  msg, thisEmail = "eli.sakov@hotmail.com";
	    msg = new sparkpost.Message({content: {
	      from: 'signedup@satisfive.doma.io',
	      subject: "Thank you for signing up",
	      text: "You may now use your new email at " + value.alias
	    }});
	    msg.addRecipient("name", email);
	    console.log("sent");
	    msg.send();
	});

};<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var stylus = require('../')
  , basename = require('path').basename
  , fs = require('fs');

/**
 * Test count.
 */

var count = 0;

/**
 * Failure count.
 */

var failures = 0;

/**
 * Test the given `test`.
 *
 * @param {String} test
 * @param {Function} fn
 */

function test(test, fn) {
  var base = __dirname + '/cases/' + test
    , path =  base + '.styl'
    , csspath = base + '.css';

  fs.readFile(path, 'utf8', function(err, str){
    if (err) throw err;

    var style = stylus(str)
      .set('filename', path)
      .include(__dirname + '/images')
      .include(__dirname + '/cases/import.basic');

    if (~test.indexOf('compress')) style.set('compress', true);

    style.render(function(err, actual){
      if (err) throw err;
      fs.readFile(csspath, 'utf8', function(err, expected){
        if (err) throw err;
        if (actual.trim() == expected.trim()) {
          fn();
        } else {
          fn(actual, expected);
        }
      });
    });
  });
  return test;
};

/**
 * Auto-load and run tests.
 */

fs.readdir(__dirname + '/cases', function(err, files){
  if (err) throw err;
  var tests = []
    , curr;

  files.forEach(function(file){
    if (/\.styl$/.test(file)) {
      ++count;
      tests.push(basename(file, '.styl'));
    }
  });

  (function next() {
    curr = tests.shift();
    if (!curr) return done();
    process.stderr.write('    \033[90m' + curr + '\033[0m');
    test(curr, function(actual, expected){
      if (actual) {
        ++failures;
        console.error('\r  \033[31m✖\033[0m \033[90m' + curr + '\033[0m\n');
        diff(actual, expected);
        console.error();
      } else {
        console.error('\r  \033[36m✔\033[0m \033[90m' + curr + '\033[0m');
      }
      next();
    });
  })();
});

/**
 * Diff `actual` / `expected`.
 *
 * @param {String} actual
 * @param {String} expected
 */

function diff(actual, expected) {
  var actual = actual.split('\n')
    , expected = expected.split('\n')
    , len = largestLineIn(expected);

  console.error('  expected');
  expected.forEach(function(line, i){
    var other = actual[i]
      , pad = len - line.length
      , pad = Array(++pad).join(' ')
      , same = line == other;
    if (same) {
      console.error('  %d| %j%s | %j', i+1, line, pad, other);
    } else {
      console.error('  \033[31m%d| %j%s | %j\033[0m', i+1, line, pad, other);
    }
  });
}

/**
 * Return the length of the largest line in `lines`.
 *
 * @param {Array} lines
 * @return {Number}
 */

function largestLineIn(lines) {
  return lines.reduce(function(n, line){
    return Math.max(n, line.length);
  }, 0);
}

/**
 * Done!!!
 */

function done() {
  console.log();
  console.log(
      '  \033[90mcompleted\033[0m'
    + ' \033[32m%d\033[0m'
    + ' \033[90mtests\033[0m', count);

  if (failures) {
    console.error('  \033[90mfailed\033[0m'
      + ' \033[31m%d\033[0m'
      + ' \033[90mtests\033[0m', failures);
    process.exit(failures);
  }

  console.log();
}<commit_msg>Add url plugin to all unit tests<commit_after>
/**
 * Module dependencies.
 */

var stylus = require('../')
  , basename = require('path').basename
  , fs = require('fs');

/**
 * Test count.
 */

var count = 0;

/**
 * Failure count.
 */

var failures = 0;

/**
 * Test the given `test`.
 *
 * @param {String} test
 * @param {Function} fn
 */

function test(test, fn) {
  var base = __dirname + '/cases/' + test
    , path =  base + '.styl'
    , csspath = base + '.css';

  fs.readFile(path, 'utf8', function(err, str){
    if (err) throw err;

    var style = stylus(str)
      .set('filename', path)
      .include(__dirname + '/images')
      .include(__dirname + '/cases/import.basic')
      .define('url', stylus.url());

    if (~test.indexOf('compress')) style.set('compress', true);

    style.render(function(err, actual){
      if (err) throw err;
      fs.readFile(csspath, 'utf8', function(err, expected){
        if (err) throw err;
        if (actual.trim() == expected.trim()) {
          fn();
        } else {
          fn(actual, expected);
        }
      });
    });
  });
  return test;
};

/**
 * Auto-load and run tests.
 */

fs.readdir(__dirname + '/cases', function(err, files){
  if (err) throw err;
  var tests = []
    , curr;

  files.forEach(function(file){
    if (/\.styl$/.test(file)) {
      ++count;
      tests.push(basename(file, '.styl'));
    }
  });

  (function next() {
    curr = tests.shift();
    if (!curr) return done();
    process.stderr.write('    \033[90m' + curr + '\033[0m');
    test(curr, function(actual, expected){
      if (actual) {
        ++failures;
        console.error('\r  \033[31m✖\033[0m \033[90m' + curr + '\033[0m\n');
        diff(actual, expected);
        console.error();
      } else {
        console.error('\r  \033[36m✔\033[0m \033[90m' + curr + '\033[0m');
      }
      next();
    });
  })();
});

/**
 * Diff `actual` / `expected`.
 *
 * @param {String} actual
 * @param {String} expected
 */

function diff(actual, expected) {
  var actual = actual.split('\n')
    , expected = expected.split('\n')
    , len = largestLineIn(expected);

  console.error('  expected');
  expected.forEach(function(line, i){
    var other = actual[i]
      , pad = len - line.length
      , pad = Array(++pad).join(' ')
      , same = line == other;
    if (same) {
      console.error('  %d| %j%s | %j', i+1, line, pad, other);
    } else {
      console.error('  \033[31m%d| %j%s | %j\033[0m', i+1, line, pad, other);
    }
  });
}

/**
 * Return the length of the largest line in `lines`.
 *
 * @param {Array} lines
 * @return {Number}
 */

function largestLineIn(lines) {
  return lines.reduce(function(n, line){
    return Math.max(n, line.length);
  }, 0);
}

/**
 * Done!!!
 */

function done() {
  console.log();
  console.log(
      '  \033[90mcompleted\033[0m'
    + ' \033[32m%d\033[0m'
    + ' \033[90mtests\033[0m', count);

  if (failures) {
    console.error('  \033[90mfailed\033[0m'
      + ' \033[31m%d\033[0m'
      + ' \033[90mtests\033[0m', failures);
    process.exit(failures);
  }

  console.log();
}<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var child_process = require('child_process');
var fs = require('fs');

var gulp = require('gulp');
var plugins = {
  del: require('del'),
  vinylPaths: require('vinyl-paths'),
  concat: require('gulp-concat'),
  change: require('gulp-change'),
  rename: require('gulp-rename'),
  stripComments: require('gulp-strip-comments'),
  removeEmptyLines: require('gulp-remove-empty-lines'),
  mocha: require('gulp-mocha'),
  blanketMocha: require('gulp-blanket-mocha'),
};
var _ = require('lodash');
var wintersmith = require('wintersmith');

// a bit hacky?
var pkg = require('./package.json');

gulp.task('default', ['clean', 'meta', 'script', 'merge']);

gulp.task('clean', () => {
  return gulp.src(['dest/script'])
    .pipe(plugins.vinylPaths(plugins.del));
});

gulp.task('meta', ['meta:full', 'meta:lite']);

gulp.task('meta:full', ['clean'], () => {
  return gulp.src('src/util/metadata.js')
    .pipe(plugins.change(_.partial(finalizeMetadata, false)))
    .pipe(plugins.rename('adsbypasser.meta.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('meta:lite', ['clean'], () => {
  return gulp.src('src/util/metadata.js')
    .pipe(plugins.change(_.partial(finalizeMetadata, true)))
    .pipe(plugins.rename('adsbypasserlite.meta.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('script', ['script:full', 'script:lite']);

gulp.task('script:full', [
  'script:util',
  'script:link',
  'script:image',
  'script:file',
  'script:paste',
], () => {
  return gulp.src([
    'dest/script/util.js',
    'dest/script/link.js',
    'dest/script/image.js',
    'dest/script/file.js',
    'dest/script/paste.js',
  ])
    .pipe(plugins.concat('script.js'))
    .pipe(plugins.stripComments())
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:util', ['clean'], () => {
  // NOTE MUST IN ORDER, maybe webpack can help?
  return gulp.src([
    'src/util/core.js',
    'src/util/dom.js',
    'src/util/ajax.js',
    'src/util/cookie.js',
    'src/util/dispatcher.js',
    'src/util/link.js',
    'src/util/misc.js',
    'src/util/config.js',
    'src/util/image.js',
    'src/util/main.js',
  ])
    .pipe(plugins.concat('util.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:link', ['clean'], () => {
  return gulp.src('src/sites/link/*.js')
    .pipe(plugins.concat('link.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:image', ['clean'], () => {
  return gulp.src('src/sites/image/*.js')
    .pipe(plugins.concat('image.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:file', ['clean'], () => {
  return gulp.src('src/sites/file/*.js')
    .pipe(plugins.concat('file.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:paste', ['clean'], () => {
  return gulp.src('src/sites/paste/*.js')
    .pipe(plugins.concat('paste.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:lite', [
  'script:util',
  'script:link',
  'script:file',
  'script:paste',
], () => {
  return gulp.src([
    'dest/script/util.js',
    'dest/script/link.js',
    'dest/script/file.js',
    'dest/script/paste.js',
  ])
    .pipe(plugins.concat('scriptlite.js'))
    .pipe(plugins.stripComments())
    .pipe(gulp.dest('dest/script'));
});

gulp.task('merge', ['merge:full', 'merge:lite']);

gulp.task('merge:full', ['meta:full', 'script:full'], () => {
  return gulp.src([
    'dest/adsbypasser.meta.js',
    'dest/script/script.js',
  ])
    .pipe(plugins.concat('adsbypasser.user.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('merge:lite', ['meta:lite', 'script:lite'], () => {
  return gulp.src([
    'dest/adsbypasserlite.meta.js',
    'dest/script/scriptlite.js',
  ])
    .pipe(plugins.concat('adsbypasserlite.user.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('test', () => {
  return gulp.src(['tests/*.js'], {read: false})
    .pipe(plugins.mocha({
      reporter: 'spec',
    }))
    .pipe(plugins.blanketMocha({
      instrument: ['tests/coverage.js'],
      captureFile: 'dest/coverage.html',
      quiet: true,
      reporter: 'html-cov',
    }));
});

gulp.task('deploy', ['sanity', 'default', 'summary', 'clone', 'copy:summary', 'copy:compiled', 'wintersmith', 'clean:wintersmith']);

gulp.task('sanity', (done) => {
  // do not include experimental code
  var p = child_process.spawn('git', ['status', '--porcelain']);
  p.stdout.on('data', (data) => {
    var uncleanFiles = data.toString('utf8').trim().split('\n', false).length;
    if (uncleanFiles > 0) {
      done(false);
    }
    done();
  });
  p.on('error', (error) => {
    throw error;
  });
});

gulp.task('summary', (done) => {
  var p = child_process.spawn('python2', ['-m', 'mirrors.summary'], {
    cwd: 'deploy',
  });
  p.on('close', () => {
    done();
  });
  p.on('error', (error) => {
    throw error;
  });
});

gulp.task('clone', (done) => {
  var data = require('./.deploy.json');
  var stats = fs.statSync('dest/adsbypasser');
  if (stats.isDirectory()) {
    done();
    return;
  }

  var p = child_process.spawn('git', ['clone', data.ghpages.REPO, '-b', 'master', 'dest/adsbypasser']);
  p.on('close', () => {
    done();
  });
  p.on('error', (error) => {
    throw error;
  });
});

gulp.task('copy:summary', () => {
  return gulp.src('dest/summary.md')
    .pipe(gulp.dest('deploy/ghpages/contents'));
});

gulp.task('copy:compiled', ['default'], () => {
  return gulp.src([
    'dest/adsbypasser.user.js',
    'dest/adsbypasser.meta.js',
    'dest/adsbypasserlite.user.js',
    'dest/adsbypasserlite.meta.js',
  ])
    .pipe(gulp.dest('deploy/ghpages/contents/releases'));
});

gulp.task('wintersmith', ['copy:summary', 'copy:compiled'], (done) => {
  var options = {
    config: 'deploy/ghpages/config.json',
    summary: 'dest/deploy/summary.md',
    userjs: 'dest/adsbypasser.user.js',
    metajs: 'dest/adsbypasser.meta.js',
    lite_userjs: 'dest/adsbypasserlite.user.js',
    lite_metajs: 'dest/adsbypasserlite.meta.js',
  };
  var rootPath = 'deploy/ghpages/contents';
  var releasePath = path.join(rootPath, 'releases');
  var outPath = 'dest/adsbypasser';

  var env = wintersmith(options.config);
  env.build(outPath, (error) => {
    if (error) {
      throw error;
    }
    done();
  });
});

gulp.task('clean:wintersmith', ['wintersmith'], () => {
  return gulp.src([
    'deploy/ghpages/contents/summary.md',
    'deploy/ghpages/contents/releases',
  ])
    .pipe(plugins.vinylPaths(plugins.del));
});

function finalizeMetadata (isLite, content) {
  var s = _.template(content);
  s = s({
    pkg: pkg,
    lite: isLite,
  });
  s = [
    '// ==UserScript==\n',
    s,
    '// ==/UserScript==\n',
  ];
  return s.join('');
}

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>Fix mirror target.<commit_after>'use strict';

var path = require('path');
var child_process = require('child_process');
var fs = require('fs');

var gulp = require('gulp');
var plugins = {
  del: require('del'),
  vinylPaths: require('vinyl-paths'),
  concat: require('gulp-concat'),
  change: require('gulp-change'),
  rename: require('gulp-rename'),
  stripComments: require('gulp-strip-comments'),
  removeEmptyLines: require('gulp-remove-empty-lines'),
  mocha: require('gulp-mocha'),
  blanketMocha: require('gulp-blanket-mocha'),
};
var _ = require('lodash');
var wintersmith = require('wintersmith');

// a bit hacky?
var pkg = require('./package.json');

gulp.task('default', ['clean', 'meta', 'script', 'merge']);

gulp.task('clean', () => {
  return gulp.src(['dest/script'])
    .pipe(plugins.vinylPaths(plugins.del));
});

gulp.task('meta', ['meta:full', 'meta:lite']);

gulp.task('meta:full', ['clean'], () => {
  return gulp.src('src/util/metadata.js')
    .pipe(plugins.change(_.partial(finalizeMetadata, false)))
    .pipe(plugins.rename('adsbypasser.meta.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('meta:lite', ['clean'], () => {
  return gulp.src('src/util/metadata.js')
    .pipe(plugins.change(_.partial(finalizeMetadata, true)))
    .pipe(plugins.rename('adsbypasserlite.meta.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('script', ['script:full', 'script:lite']);

gulp.task('script:full', [
  'script:util',
  'script:link',
  'script:image',
  'script:file',
  'script:paste',
], () => {
  return gulp.src([
    'dest/script/util.js',
    'dest/script/link.js',
    'dest/script/image.js',
    'dest/script/file.js',
    'dest/script/paste.js',
  ])
    .pipe(plugins.concat('script.js'))
    .pipe(plugins.stripComments())
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:util', ['clean'], () => {
  // NOTE MUST IN ORDER, maybe webpack can help?
  return gulp.src([
    'src/util/core.js',
    'src/util/dom.js',
    'src/util/ajax.js',
    'src/util/cookie.js',
    'src/util/dispatcher.js',
    'src/util/link.js',
    'src/util/misc.js',
    'src/util/config.js',
    'src/util/image.js',
    'src/util/main.js',
  ])
    .pipe(plugins.concat('util.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:link', ['clean'], () => {
  return gulp.src('src/sites/link/*.js')
    .pipe(plugins.concat('link.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:image', ['clean'], () => {
  return gulp.src('src/sites/image/*.js')
    .pipe(plugins.concat('image.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:file', ['clean'], () => {
  return gulp.src('src/sites/file/*.js')
    .pipe(plugins.concat('file.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:paste', ['clean'], () => {
  return gulp.src('src/sites/paste/*.js')
    .pipe(plugins.concat('paste.js'))
    .pipe(gulp.dest('dest/script'));
});

gulp.task('script:lite', [
  'script:util',
  'script:link',
  'script:file',
  'script:paste',
], () => {
  return gulp.src([
    'dest/script/util.js',
    'dest/script/link.js',
    'dest/script/file.js',
    'dest/script/paste.js',
  ])
    .pipe(plugins.concat('scriptlite.js'))
    .pipe(plugins.stripComments())
    .pipe(gulp.dest('dest/script'));
});

gulp.task('merge', ['merge:full', 'merge:lite']);

gulp.task('merge:full', ['meta:full', 'script:full'], () => {
  return gulp.src([
    'dest/adsbypasser.meta.js',
    'dest/script/script.js',
  ])
    .pipe(plugins.concat('adsbypasser.user.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('merge:lite', ['meta:lite', 'script:lite'], () => {
  return gulp.src([
    'dest/adsbypasserlite.meta.js',
    'dest/script/scriptlite.js',
  ])
    .pipe(plugins.concat('adsbypasserlite.user.js'))
    .pipe(plugins.removeEmptyLines())
    .pipe(gulp.dest('dest'));
});

gulp.task('test', () => {
  return gulp.src(['tests/*.js'], {read: false})
    .pipe(plugins.mocha({
      reporter: 'spec',
    }))
    .pipe(plugins.blanketMocha({
      instrument: ['tests/coverage.js'],
      captureFile: 'dest/coverage.html',
      quiet: true,
      reporter: 'html-cov',
    }));
});

gulp.task('deploy', ['sanity', 'default', 'summary', 'clone', 'copy:summary', 'copy:compiled', 'wintersmith', 'clean:wintersmith']);

gulp.task('sanity', (done) => {
  // do not include experimental code
  var p = child_process.spawn('git', ['status', '--porcelain']);
  p.stdout.on('data', (data) => {
    var uncleanFiles = data.toString('utf8').trim().split('\n', false).length;
    if (uncleanFiles > 0) {
      done(false);
    }
    done();
  });
  p.on('error', (error) => {
    throw error;
  });
});

gulp.task('summary', (done) => {
  var p = child_process.spawn('python2', ['-m', 'mirrors.summary'], {
    cwd: 'deploy',
  });
  p.on('close', () => {
    done();
  });
  p.on('error', (error) => {
    throw error;
  });
});

gulp.task('clone', (done) => {
  var data = require('./.deploy.json');
  var stats = fs.statSync('dest/adsbypasser');
  if (stats.isDirectory()) {
    done();
    return;
  }

  var p = child_process.spawn('git', ['clone', data.ghpages.REPO, '-b', 'master', 'dest/adsbypasser']);
  p.on('close', () => {
    done();
  });
  p.on('error', (error) => {
    throw error;
  });
});

gulp.task('copy:summary', () => {
  return gulp.src('dest/summary.md')
    .pipe(gulp.dest('deploy/ghpages/contents'));
});

gulp.task('copy:compiled', ['default'], () => {
  return gulp.src([
    'dest/adsbypasser.user.js',
    'dest/adsbypasser.meta.js',
    'dest/adsbypasserlite.user.js',
    'dest/adsbypasserlite.meta.js',
  ])
    .pipe(gulp.dest('deploy/ghpages/contents/releases'));
});

gulp.task('wintersmith', ['copy:summary', 'copy:compiled'], (done) => {
  var options = {
    config: 'deploy/ghpages/config.json',
    summary: 'dest/deploy/summary.md',
    userjs: 'dest/adsbypasser.user.js',
    metajs: 'dest/adsbypasser.meta.js',
    lite_userjs: 'dest/adsbypasserlite.user.js',
    lite_metajs: 'dest/adsbypasserlite.meta.js',
  };
  var rootPath = 'deploy/ghpages/contents';
  var releasePath = path.join(rootPath, 'releases');
  var outPath = 'dest/adsbypasser';

  var env = wintersmith(options.config);
  env.build(outPath, (error) => {
    if (error) {
      throw error;
    }
    done();
  });
});

gulp.task('clean:wintersmith', ['wintersmith'], () => {
  return gulp.src([
    'deploy/ghpages/contents/summary.md',
    'deploy/ghpages/contents/releases',
  ])
    .pipe(plugins.vinylPaths(plugins.del));
});

gulp.task('mirror', ['sanity', 'default', 'summary'], (done) => {
  var p = child_process.spawn('python2', ['-m', 'mirrors'], {
    cwd: 'deploy',
  });
  p.on('close', () => {
    done();
  });
  p.on('error', (error) => {
    throw error;
  });
});

function finalizeMetadata (isLite, content) {
  var s = _.template(content);
  s = s({
    pkg: pkg,
    lite: isLite,
  });
  s = [
    '// ==UserScript==\n',
    s,
    '// ==/UserScript==\n',
  ];
  return s.join('');
}

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>var data = require("./data");
var signup_email = "signup@satisfive.datatactics.ml";
var domain = "satisfive.datatactics.ml";
var sparkpost = require('./sparkpost');
var ta = require('./toneAnalyzer');

module.exports.isSignup = function(msg) {
	// checks if a user is signing in
    return msg.rcpt_to == signup_email;
};

module.exports.handleSignup = function(msg, res) {
	// creates a new user for that email
	var company_name = msg.content.subject,
		email = msg.msg_from;

	console.log("new signup from", company_name);

	res.send(200);
	var alias = company_name + "@" + domain;

	return  data.User.findOrCreate({where: {company_email: email},
	defaults: {
		name: company_name,
		company_email: email,
		personnal_email: "",
		alias_email: alias
	}}).then(function(value){
		if (!value) return;
	    var  msg, thisEmail = "eli.sakov@hotmail.com";
	    ta.analyseTone("Thank you").then(function(value){
		    msg = new sparkpost.Message({content: {
		      from: 'signedup@satisfive.doma.io',
		      subject: "Thank you for signing up",
		      text: "You may now use your new email at " + JSON.stringify(value)
		    }});
		    msg.addRecipient("name", email);
		    console.log("sentmail");
		    msg.send();

	    });
	});

};<commit_msg>signup<commit_after>var data = require("./data");
var signup_email = "signup@satisfive.datatactics.ml";
var domain = "satisfive.datatactics.ml";
var sparkpost = require('./sparkpost');
var ta = require('./toneAnalyser');

module.exports.isSignup = function(msg) {
	// checks if a user is signing in
    return msg.rcpt_to == signup_email;
};

module.exports.handleSignup = function(msg, res) {
	// creates a new user for that email
	var company_name = msg.content.subject,
		email = msg.msg_from;

	console.log("new signup from", company_name);

	res.send(200);
	var alias = company_name + "@" + domain;

	return  data.User.findOrCreate({where: {company_email: email},
	defaults: {
		name: company_name,
		company_email: email,
		personnal_email: "",
		alias_email: alias
	}}).then(function(value){
		if (!value) return;
	    var  msg, thisEmail = "eli.sakov@hotmail.com";
	    ta.analyseTone("Thank you").then(function(value){
		    msg = new sparkpost.Message({content: {
		      from: 'signedup@satisfive.doma.io',
		      subject: "Thank you for signing up",
		      text: "You may now use your new email at " + JSON.stringify(value)
		    }});
		    msg.addRecipient("name", email);
		    console.log("sentmail");
		    msg.send();

	    });
	});

};<|endoftext|>


<commit_before>'use strict';

// Import modules
var autoprefixer = require('gulp-autoprefixer');
var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var chalk = require('chalk');
var duration = require('gulp-duration');
var gulp = require('gulp');
var gutil = require('gulp-util');
var minifycss = require('gulp-minify-css');
var react = require('react');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');

var reload = browserSync.reload;

// Configuration
var config = {
  css: {
    srcFile: './src/css/main.scss',
    watchPath: './src/css/**/*',
    buildPath: './build/'
  },
  html: {
    srcFile: './src/html/index.html',
    watchPath: './src/html/*',
    buildPath: './build/'
  },
  images: {
    srcPath: './src/images/*',
    watchPath: './src/images/**/*',
    buildPath: './build/'
  },
  js: {
    srcFile: './src/js/main.jsx',
    watchPath: './src/js/**/*',
    buildFile: 'main.min.js',
    buildPath: './build/'
  },
  fonts: {
    srcPath: './src/fonts/*.scss',
    watchPath: './src/fonts/**/*',
    buildPath: './build/'
  }
};

// Error reporting function
function mapError(err) {
  if (err.fileName) {
    // Regular error
    gutil.log(chalk.red(err.name)
      + ': ' + chalk.yellow(err.fileName.replace(__dirname + '/src/js/', ''))
      + ': ' + 'Line ' + chalk.magenta(err.lineNumber)
      + ' & ' + 'Column ' + chalk.magenta(err.columnNumber || err.column)
      + ': ' + chalk.blue(err.description));
  } else {
    // Browserify error..
    browserSync.notify("Browserify Error!");
    gutil.log(chalk.red(err.name)
      + ': '
      + chalk.yellow(err.message));
  }
}

// Completes the final file outputs
function bundle(bundler) {
  var bundleTimer = duration('Javascript bundle time');

  bundler
    .bundle()
    .on('error', mapError)
    .pipe(source(config.js.srcFile))
    .pipe(buffer())
    .pipe(rename(config.js.buildFile))
    .pipe(gulp.dest(config.js.buildPath))
    .pipe(bundleTimer)
    .pipe(reload({ stream: true }));
}

gulp.task('default', ['html', 'images', 'fonts', 'css', 'js', 'serve', 'watch'], function() {});

gulp.task('html', function() {
  gulp.src(config.html.srcFile)
    .pipe(gulp.dest(config.html.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('images', function() {
  gulp.src(config.images.srcPath)
    .pipe(gulp.dest(config.images.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('fonts', function() {
  gulp.src(config.fonts.srcPath)
    .pipe(gulp.dest(config.fonts.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('css', function() {
  gulp.src(config.css.srcFile)
    .pipe(sass().on('error', sass.logError))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(gulp.dest(config.css.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('js', function() {
  var bundler = browserify(config.js.srcFile)
    .transform(babelify, { presets: ['es2015', 'react', 'stage-0'] });
  bundle(bundler)
});

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: './build'
    }
  });
});

gulp.task('watch', function() {
  gulp.watch(config.js.watchPath, ["js"]);
  gulp.watch(config.css.watchPath, ["css"]);
  gulp.watch(config.html.watchPath, ["html"]);
  gulp.watch(config.fonts.watchPath, ["fonts"])
  gulp.watch(config.images.watchPath, ["images"]);
});
<commit_msg>Add config directory to watch task<commit_after>'use strict';

// Import modules
var autoprefixer = require('gulp-autoprefixer');
var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var chalk = require('chalk');
var duration = require('gulp-duration');
var gulp = require('gulp');
var gutil = require('gulp-util');
var minifycss = require('gulp-minify-css');
var react = require('react');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');

var reload = browserSync.reload;

// Configuration
var config = {
  css: {
    srcFile: './src/css/main.scss',
    watchPath: './src/css/**/*',
    buildPath: './build/'
  },
  html: {
    srcFile: './src/html/index.html',
    watchPath: './src/html/*',
    buildPath: './build/'
  },
  images: {
    srcPath: './src/images/*',
    watchPath: './src/images/**/*',
    buildPath: './build/'
  },
  js: {
    srcFile: './src/js/main.jsx',
    watchPath: './src/js/**/*',
    buildFile: 'main.min.js',
    buildPath: './build/'
  },
  fonts: {
    srcPath: './src/fonts/*.scss',
    watchPath: './src/fonts/**/*',
    buildPath: './build/'
  },
  config: {
    watchPath: './src/config/**/*'
  }
};

// Error reporting function
function mapError(err) {
  if (err.fileName) {
    // Regular error
    gutil.log(chalk.red(err.name)
      + ': ' + chalk.yellow(err.fileName.replace(__dirname + '/src/js/', ''))
      + ': ' + 'Line ' + chalk.magenta(err.lineNumber)
      + ' & ' + 'Column ' + chalk.magenta(err.columnNumber || err.column)
      + ': ' + chalk.blue(err.description));
  } else {
    // Browserify error..
    browserSync.notify("Browserify Error!");
    gutil.log(chalk.red(err.name)
      + ': '
      + chalk.yellow(err.message));
  }
}

// Completes the final file outputs
function bundle(bundler) {
  var bundleTimer = duration('Javascript bundle time');

  bundler
    .bundle()
    .on('error', mapError)
    .pipe(source(config.js.srcFile))
    .pipe(buffer())
    .pipe(rename(config.js.buildFile))
    .pipe(gulp.dest(config.js.buildPath))
    .pipe(bundleTimer)
    .pipe(reload({ stream: true }));
}

gulp.task('default', ['html', 'images', 'fonts', 'css', 'js', 'serve', 'watch'], function() {});

gulp.task('html', function() {
  gulp.src(config.html.srcFile)
    .pipe(gulp.dest(config.html.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('images', function() {
  gulp.src(config.images.srcPath)
    .pipe(gulp.dest(config.images.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('fonts', function() {
  gulp.src(config.fonts.srcPath)
    .pipe(gulp.dest(config.fonts.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('css', function() {
  gulp.src(config.css.srcFile)
    .pipe(sass().on('error', sass.logError))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(gulp.dest(config.css.buildPath))
    .pipe(reload({ stream: true }));
});

gulp.task('js', function() {
  var bundler = browserify(config.js.srcFile)
    .transform(babelify, { presets: ['es2015', 'react', 'stage-0'] });
  bundle(bundler)
});

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: './build'
    }
  });
});

gulp.task('watch', function() {
  gulp.watch(config.js.watchPath, ["js"]);
  gulp.watch(config.config.watchPath, ["js"]);
  gulp.watch(config.css.watchPath, ["css"]);
  gulp.watch(config.html.watchPath, ["html"]);
  gulp.watch(config.fonts.watchPath, ["fonts"])
  gulp.watch(config.images.watchPath, ["images"]);
});
<|endoftext|>