<commit_before>/* global require */

var gulp = require('gulp');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var uglify = require('gulp-uglify');
var del = require('del');
var fs = require('fs');
var merge = require('merge2');

// See the uglify documentation for more details
var uglifySettings = {
    compress: {
        comparisons: true,
        conditionals: true,
        dead_code: true,
        drop_console: true,
        unsafe: true,
        unused: true
    }
};

// Assets for the project
var Assets = {
    dest: 'dist',
    main: 'loady.js',
    minified: 'loady.min.js',
    other: [
        '/.system.js',
        './user.js'
    ]
};
Assets.other.push('./' + Assets.main);

// Clean the 'dist' directory
gulp.task('clean', function (cb) {
    del([Assets.dest + '/*.js'], cb);
});

// Run the babel transpiler to convert from ES2015 to ES5
gulp.task('es6to5', function () {
    return gulp.src(Assets.other)
        .pipe(babel())
        .pipe(gulp.dest('./' + Assets.dest));
});

// Check the code meets the following standards outlined in .jshintrc
gulp.task('jshint', function () {
    return gulp.src('./' + Assets.main)
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

// Uglify aka minify the main file
gulp.task('uglify', ['clean', 'es6to5'], function () {
    return gulp.src('./' + Assets.dest + '/' + Assets.main)
        .pipe(concat(Assets.minified))
        .pipe(uglify(uglifySettings))
        .pipe(rename(Assets.minified))
        .pipe(gulp.dest('./' + Assets.dest));
});

// Watch for changes to the main file
gulp.task('watch', function () {
    gulp.watch('./' + Assets.main, ['jshint', 'uglify']);
});

// Update version numbers based on the main file version comment
gulp.task('version', function () {
    // SemVer matching is done using (?:\d+\.){2}\d+

    var reVersion = /\n\s*\*\s+Version:\s+((?:\d+\.){2}\d+)/;
    var version = fs.readFileSync('./' + Assets.main, {
            encoding: 'utf8'
        })
        // Match is found in the 2nd element
        .match(reVersion)[1];

    var streams = merge();

    // package.json version property
    streams.add(
        gulp.src('./package.json')
        .pipe(replace(/"version":\s+"(?:\d+\.){2}\d+",/, '"version": "' + version + '",'))
        .pipe(gulp.dest('./'))
    );

    // README.md version number
    streams.add(
        gulp.src('./README.md')
        .pipe(replace(/^#\s+([\w\-]+)\s+-\s+v(?:\d+\.){2}\d+/, '# $1 - v' + version))
        .pipe(gulp.dest('./'))
    );

    return streams;
});

// Register the default task
gulp.task('default', ['version', 'jshint', 'uglify']);

// 'gulp es6to5' to transpile from ES2015 to ES5
// 'gulp jshint' to check the syntax
// 'gulp uglify' to uglify the main file
// 'gulp watch' to watch for changes to the main file
// 'gulp version' to update the version numbers based on the main file version comment
<commit_msg>Fixed file error<commit_after>/* global require */

var gulp = require('gulp');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var uglify = require('gulp-uglify');
var del = require('del');
var fs = require('fs');
var merge = require('merge2');

// See the uglify documentation for more details
var uglifySettings = {
    compress: {
        comparisons: true,
        conditionals: true,
        dead_code: true,
        drop_console: true,
        unsafe: true,
        unused: true
    }
};

// Assets for the project
var Assets = {
    dest: 'dist',
    main: 'loady.js',
    minified: 'loady.min.js',
    other: [
        './system.js',
        './user.js'
    ]
};
Assets.other.push('./' + Assets.main);

// Clean the 'dist' directory
gulp.task('clean', function (cb) {
    del([Assets.dest + '/*.js'], cb);
});

// Run the babel transpiler to convert from ES2015 to ES5
gulp.task('es6to5', function () {
    return gulp.src(Assets.other)
        .pipe(babel())
        .pipe(gulp.dest('./' + Assets.dest));
});

// Check the code meets the following standards outlined in .jshintrc
gulp.task('jshint', function () {
    return gulp.src('./' + Assets.main)
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

// Uglify aka minify the main file
gulp.task('uglify', ['clean', 'es6to5'], function () {
    return gulp.src('./' + Assets.dest + '/' + Assets.main)
        .pipe(concat(Assets.minified))
        .pipe(uglify(uglifySettings))
        .pipe(rename(Assets.minified))
        .pipe(gulp.dest('./' + Assets.dest));
});

// Watch for changes to the main file
gulp.task('watch', function () {
    gulp.watch('./' + Assets.main, ['jshint', 'uglify']);
});

// Update version numbers based on the main file version comment
gulp.task('version', function () {
    // SemVer matching is done using (?:\d+\.){2}\d+

    var reVersion = /\n\s*\*\s+Version:\s+((?:\d+\.){2}\d+)/;
    var version = fs.readFileSync('./' + Assets.main, {
            encoding: 'utf8'
        })
        // Match is found in the 2nd element
        .match(reVersion)[1];

    var streams = merge();

    // package.json version property
    streams.add(
        gulp.src('./package.json')
        .pipe(replace(/"version":\s+"(?:\d+\.){2}\d+",/, '"version": "' + version + '",'))
        .pipe(gulp.dest('./'))
    );

    // README.md version number
    streams.add(
        gulp.src('./README.md')
        .pipe(replace(/^#\s+([\w\-]+)\s+-\s+v(?:\d+\.){2}\d+/, '# $1 - v' + version))
        .pipe(gulp.dest('./'))
    );

    return streams;
});

// Register the default task
gulp.task('default', ['version', 'jshint', 'uglify']);

// 'gulp es6to5' to transpile from ES2015 to ES5
// 'gulp jshint' to check the syntax
// 'gulp uglify' to uglify the main file
// 'gulp watch' to watch for changes to the main file
// 'gulp version' to update the version numbers based on the main file version comment
<|endoftext|>


<commit_before>const babelify = require('babelify')
const browserify = require('browserify')
const del = require('del')
const glob = require('glob')
const gulp = require('gulp')
const merge2 = require('merge2')
const path = require('path')
const runSequence = require('run-sequence')
const source = require('vinyl-source-stream')

function bundle (indexFile, dir, deps, cb) {
  let stream = merge2(
    browserify(indexFile, { debug: true })
      .transform(babelify)
      .bundle()
      .pipe(source('bundle.js'))
      .pipe(gulp.dest(dir))
  )

  for (let key in deps) {
    stream.add(
      gulp.src(key)
        .pipe(gulp.dest(path.join(dir, deps[key])))
    )
  }

  stream.on('queueDrain', cb)
}

function createTasks (name) {
  gulp.task(`clean-${name}`, () => del(`./build/${name}`, { force: true }))

  gulp.task(`build-${name}`, (cb) => {
    bundle('./src/shared/index.js', `./build/${name}`, {
      [`./src/${name}/manifest.json`]: '',
      './src/shared/content.js': '',
      './src/shared/images/*': 'images',
      './src/shared/popup/*': 'popup'
    }, cb)
  })

  gulp.task(name, (cb) => {
    runSequence(`clean-${name}`, `build-${name}`, cb)
  })
}

createTasks('firefox')

createTasks('chrome')
<commit_msg>Make gulpfile work with older versions of Node<commit_after>var babelify = require('babelify')
var browserify = require('browserify')
var del = require('del')
var glob = require('glob')
var gulp = require('gulp')
var merge2 = require('merge2')
var path = require('path')
var runSequence = require('run-sequence')
var source = require('vinyl-source-stream')

function bundle (indexFile, dir, deps, cb) {
  var stream = merge2(
    browserify(indexFile, { debug: true })
      .transform(babelify)
      .bundle()
      .pipe(source('bundle.js'))
      .pipe(gulp.dest(dir))
  )

  for (var key in deps) {
    stream.add(
      gulp.src(key)
        .pipe(gulp.dest(path.join(dir, deps[key])))
    )
  }

  stream.on('queueDrain', cb)
}

function createTasks (name) {
  gulp.task(`clean-${name}`, function () {
    return del(`./build/${name}`, { force: true })
  })

  gulp.task(`build-${name}`, function (cb) {
    bundle('./src/shared/index.js', `./build/${name}`, {
      [`./src/${name}/manifest.json`]: '',
      './src/shared/content.js': '',
      './src/shared/images/*': 'images',
      './src/shared/popup/*': 'popup'
    }, cb)
  })

  gulp.task(name, function (cb) {
    runSequence(`clean-${name}`, `build-${name}`, cb)
  })
}

createTasks('firefox')

createTasks('chrome')
<|endoftext|>


<commit_before>(function (gulp, gulpLoadPlugins, pkg) {
	'use strict';
	//|**
	//|
	//| Gulpfile
	//|
	//| This file is the streaming build system
	//|
	//| .-------------------------------------------------------------------.
	//| | NAMING CONVENTIONS:                                               |
	//| |-------------------------------------------------------------------|
	//| | Singleton-literals and prototype objects      | PascalCase        |
	//| |-------------------------------------------------------------------|
	//| | Functions and public variables                | camelCase         |
	//| |-------------------------------------------------------------------|
	//| | Global variables and constants                | UPPERCASE         |
	//| |-------------------------------------------------------------------|
	//| | Private variables                             | _underscorePrefix |
	//| '-------------------------------------------------------------------'
	//|
	//| Comment syntax for the entire project follows JSDoc:
	//| - http://code.google.com/p/jsdoc-toolkit/wiki/TagReference
	//|
	//| For performance reasons we're only matching one level down:
	//| - 'test/spec/{,*/}*.js'
	//|
	//| Use this if you want to recursively match all subfolders:
	//| - 'test/spec/**/*.js'
	//|
	//'*/
	var $ = gulpLoadPlugins({ pattern: '*', lazy: false }),
		_ = { dist: './dist', test: './test' },
		source = require('./.amrc').source,
		module = 'utils',
		inline = '// <%= pkg.name %>@v<%= pkg.version %>, <%= pkg.license[0].type %> licensed. <%= pkg.homepage %>\n',
		extended = [
		'/**',
		' * <%= pkg.title %>',
		' * @description <%= pkg.description %>',
		' * @version v<%= pkg.version %>',
		' * @author <%= pkg.author.name %>',
		' * @link <%= pkg.homepage %>',
		' * @license <%= pkg.license[0].type %> Licensed',
		' */\n'
	].join('\n');

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ validate
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('jsonlint', function() {
		var stream = gulp.src([
			'package.json',
			'bower.json',
			'.bowerrc',
			'.jshintrc',
			'.jscs.json'
		])
		.pipe($.plumber())
		.pipe($.jsonlint())
		.pipe($.jsonlint.reporter())
		.pipe($.notify({
			message: '<%= options.date %> ✓ jsonlint: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}));
		return stream;
	});

	gulp.task('jshint', function () {
		var stream = gulp.src(wrap(source[module].files, source[module].name))
		.pipe($.plumber())
		.pipe($.notify({
			message: '<%= options.date %> ✓ jshint: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}))
		.pipe($.concat(source[module].name + '.js'))
		.pipe($.removeUseStrict())
		.pipe($.jshint('.jshintrc'))
		.pipe($.jshint.reporter('default'))
		.pipe($.jscs());
		return stream;
	});

	gulp.task('mocha', function () {
		var stream = gulp.src(_.test + '/**/*.js')
		.pipe($.plumber())
		.pipe($.mocha({ reporter: 'list' }));
		return stream;
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ compress
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('src', ['validate'], function () {
		var stream = gulp.src(wrap(source[module].files, source[module].name))
		.pipe($.plumber())
		.pipe($.notify({
			message: '<%= options.date %> ✓ src: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}))
		.pipe($.concat(source[module].name + '.js'))
		.pipe($.removeUseStrict())
		.pipe($.header(extended, { pkg: pkg }))
		.pipe($.size())
		.pipe(gulp.dest(_.dist));
		return stream;
	});

	gulp.task('min', ['src'], function () {
		var min = gulp.src(_.dist + '/' + source[module].name + '.js')
		.pipe($.plumber())
		.pipe($.notify({
			message: '<%= options.date %> ✓ min: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}))
		.pipe($.rename(source[module].name + '.min.js'))
		.pipe($.uglify())
		.pipe($.header(inline, { pkg: pkg }))
		.pipe($.size())
		.pipe(gulp.dest(_.dist));
		return min;
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ versioning
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('bump', function () {
		var bumpType = process.env.BUMP || 'patch';
		var stream = gulp.src(['package.json', 'bower.json'])
		.pipe($.bump({ type: bumpType }))
		.pipe(gulp.dest('./'));
		return stream;
	});

	gulp.task('tag', ['bump', 'min'], function () {
		var version = 'v' + pkg.version;
		var message = 'Release ' + version;
		var stream = gulp.src('./')
		.pipe($.git.commit(message))
		.pipe($.git.tag(version, message))
		.pipe($.git.push('origin', 'master', '--tags'))
		.pipe($.gulp.dest('./'));
		return stream;
	});

	gulp.task('npm', ['tag'], function (done) {
		var process = require('child_process')
		.spawn('npm', ['publish'], { stdio: 'inherit' })
		.on('close', done);
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ default
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('clean', function () {
		var stream = gulp.src(_.dist, { read: false })
		.pipe($.plumber())
		.pipe($.clean());
		return stream;
	});

	gulp.task('default', function() {
		gulp.start('min');
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ shortcuts
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('validate', ['jsonlint', 'jshint']);
	gulp.task('release', ['npm']);
	gulp.task('test', ['mocha']);
	gulp.task('ci', ['min']);

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ utils
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	function wrap(src) {
		src.unshift('source/AM.prefix');
		src.push('source/AM.suffix');
		return src;
	}

}(require('gulp'), require('gulp-load-plugins'), require('./package.json')));
<commit_msg>v0.0.2<commit_after>(function (gulp, gulpLoadPlugins, pkg) {
	'use strict';
	//|**
	//|
	//| Gulpfile
	//|
	//| This file is the streaming build system
	//|
	//| .-------------------------------------------------------------------.
	//| | NAMING CONVENTIONS:                                               |
	//| |-------------------------------------------------------------------|
	//| | Singleton-literals and prototype objects      | PascalCase        |
	//| |-------------------------------------------------------------------|
	//| | Functions and public variables                | camelCase         |
	//| |-------------------------------------------------------------------|
	//| | Global variables and constants                | UPPERCASE         |
	//| |-------------------------------------------------------------------|
	//| | Private variables                             | _underscorePrefix |
	//| '-------------------------------------------------------------------'
	//|
	//| Comment syntax for the entire project follows JSDoc:
	//| - http://code.google.com/p/jsdoc-toolkit/wiki/TagReference
	//|
	//| For performance reasons we're only matching one level down:
	//| - 'test/spec/{,*/}*.js'
	//|
	//| Use this if you want to recursively match all subfolders:
	//| - 'test/spec/**/*.js'
	//|
	//'*/
	var $ = gulpLoadPlugins({ pattern: '*', lazy: false }),
		_ = { dist: './dist', test: './test' },
		source = require('./.amrc').source,
		module = 'utils',
		inline = '// <%= pkg.name %>@v<%= pkg.version %>, <%= pkg.license[0].type %> licensed. <%= pkg.homepage %>\n',
		extended = [
		'/**',
		' * <%= pkg.title %>',
		' * @description <%= pkg.description %>',
		' * @version v<%= pkg.version %>',
		' * @author <%= pkg.author.name %>',
		' * @link <%= pkg.homepage %>',
		' * @license <%= pkg.license[0].type %> Licensed',
		' */\n'
	].join('\n');

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ validate
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('jsonlint', function() {
		var stream = gulp.src([
			'package.json',
			'bower.json',
			'.bowerrc',
			'.jshintrc',
			'.jscs.json'
		])
		.pipe($.plumber())
		.pipe($.jsonlint())
		.pipe($.jsonlint.reporter())
		.pipe($.notify({
			message: '<%= options.date %> ✓ jsonlint: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}));
		return stream;
	});

	gulp.task('jshint', function () {
		var stream = gulp.src(wrap(source[module].files, source[module].name))
		.pipe($.plumber())
		.pipe($.notify({
			message: '<%= options.date %> ✓ jshint: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}))
		.pipe($.concat(source[module].name + '.js'))
		.pipe($.removeUseStrict())
		.pipe($.jshint('.jshintrc'))
		.pipe($.jshint.reporter('default'))
		.pipe($.jscs());
		return stream;
	});

	gulp.task('mocha', function () {
		var stream = gulp.src(_.test + '/**/*.js')
		.pipe($.plumber())
		.pipe($.mocha({ reporter: 'list' }));
		return stream;
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ compress
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('src', ['validate'], function () {
		var stream = gulp.src(wrap(source[module].files, source[module].name))
		.pipe($.plumber())
		.pipe($.notify({
			message: '<%= options.date %> ✓ src: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}))
		.pipe($.concat(source[module].name + '.js'))
		.pipe($.removeUseStrict())
		.pipe($.header(extended, { pkg: pkg }))
		.pipe($.size())
		.pipe(gulp.dest(_.dist));
		return stream;
	});

	gulp.task('min', ['src'], function () {
		var min = gulp.src(_.dist + '/' + source[module].name + '.js')
		.pipe($.plumber())
		.pipe($.notify({
			message: '<%= options.date %> ✓ min: <%= file.relative %>',
			templateOptions: {
				date: new Date()
			}
		}))
		.pipe($.rename(source[module].name + '.min.js'))
		.pipe($.uglify())
		.pipe($.header(inline, { pkg: pkg }))
		.pipe($.size())
		.pipe(gulp.dest(_.dist));
		return min;
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ versioning
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('bump', function () {
		var bumpType = process.env.BUMP || 'patch';
		var stream = gulp.src(['package.json', 'bower.json'])
		.pipe($.bump({ type: bumpType }))
		.pipe(gulp.dest('./'));
		return stream;
	});

	gulp.task('tag', ['bump', 'min'], function () {
		var version = 'v' + pkg.version;
		var message = 'Release ' + version;
		var stream = gulp.src('./')
		.pipe($.git.commit(message))
		.pipe($.git.tag(version, message))
		.pipe($.git.push('origin', 'master', '--tags'))
		.pipe($.gulp.dest('./'));
		return stream;
	});

	gulp.task('npm', ['tag'], function (done) {
		var process = require('child_process')
		.spawn('npm', ['publish'], { stdio: 'inherit' })
		.on('close', done);
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ default
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('clean', function () {
		var stream = gulp.src(_.dist, { read: false })
		.pipe($.plumber())
		.pipe($.clean());
		return stream;
	});

	gulp.task('default', function() {
		gulp.start('min');
	});

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ shortcuts
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	gulp.task('validate', ['jsonlint', 'jshint']);
	gulp.task('release', ['npm']);
	gulp.task('test', ['mocha']);
	gulp.task('ci', ['min']);

	//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//| ✓ utils
	//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	function wrap(src) {
		src.unshift('source/AM.prefix');
		src.push('source/AM.suffix');
		return src;
	}

}(require('gulp'), require('gulp-load-plugins'), require('./package.json')));
<|endoftext|>


<commit_before>const gulp        = require('gulp');
const install     = require('gulp-install');
const realFavicon = require('gulp-real-favicon');
const source 			= require('vinyl-source-stream');
const buffer      = require('vinyl-buffer');
const browserify  = require('browserify');
const watchify 		= require('watchify');
const uglify      = require('gulp-uglify');
const tsify       = require('tsify');
const fs          = require('fs');
const gulpTypings = require("gulp-typings");
const tsconfig 		= require('./tsconfig.json');
const FAVICON_DATA_FILE = 'faviconData.json';

gulp.task('generate-favicon', function(done) {
	realFavicon.generateFavicon({
		masterPicture: './crypt.svg',
		dest: 'dist/client/favicons',
		iconsPath: '/favicons',
		design: {
			ios: {
				pictureAspect: 'backgroundAndMargin',
				backgroundColor: '#352f2f',
				margin: '14%',
				assets: {
					ios6AndPriorIcons: false,
					ios7AndLaterIcons: false,
					precomposedIcons: false,
					declareOnlyDefaultIcon: true
				},
				appName: 'Crypt'
			},
			desktopBrowser: {},
			windows: {
				pictureAspect: 'noChange',
				backgroundColor: '#352f2f',
				onConflict: 'override',
				assets: {
					windows80Ie10Tile: false,
					windows10Ie11EdgeTiles: {
						small: false,
						medium: true,
						big: false,
						rectangle: false
					}
				},
				appName: 'Crypt'
			},
			androidChrome: {
				pictureAspect: 'noChange',
				themeColor: '#352f2f',
				manifest: {
					name: 'Crypt',
					display: 'standalone',
					orientation: 'notSet',
					onConflict: 'override',
					declared: true
				},
				assets: {
					legacyIcon: false,
					lowResolutionIcons: false
				}
			},
			safariPinnedTab: {
				pictureAspect: 'silhouette',
				themeColor: '#01cccc'
			}
		},
		settings: {
			compression: 5,
			scalingAlgorithm: 'Cubic',
			errorOnImageTooSmall: false
		},
		versioning: {
			paramName: 'v',
			paramValue: 'vMroeOKLRG'
		},
		markupFile: FAVICON_DATA_FILE
	}, function() {
		done();
	});
});

gulp.task('inject-favicon-markups', ['generate-favicon', 'copy_client_root'],function() {
	gulp.src('dist/client/index.html')
		.pipe(realFavicon.injectFaviconMarkups(JSON.parse(fs.readFileSync(FAVICON_DATA_FILE)).favicon.html_code))
		.pipe(gulp.dest('dist/client/'));
});

gulp.task('check-for-favicon-update', function(done) {
	var currentVersion = JSON.parse(fs.readFileSync(FAVICON_DATA_FILE)).version;
	realFavicon.checkForUpdates(currentVersion, function(err) {
		if (err) {
			throw err;
		}
	});
});

function handleTsErrors(err){
	if(typeof err != typeof ''){
		err = JSON.stringify(err, null, 2);
	}
	console.error(err);
}

function bundle(watch){
	var props = {debug:true};
	var b = watch ? watchify(browserify(props)) : browserify(props);
	b.add('src/client/src/main.ts')
	.plugin(tsify, tsconfig);
	function rebundle(){
		b.bundle()
		.on('error', handleTsErrors)
		.pipe(source('main.min.js'))
		// .pipe(buffer())
		// .pipe(uglify())
		.pipe(gulp.dest('./dist/client/app/'));
	}
	b.on('update', function() {
		console.log('Rebundling...');
		rebundle();
	});
	return rebundle();
}

gulp.task('browserify', ['install_client', 'install_typings'], function(){
	return bundle(false);
});

gulp.task('watchify', ['install_client', 'install_typings'], function(){
	return bundle(true);
});

gulp.task('copy_templates', function(){
  return gulp.src(['src/client/templates/*.html'])
      .pipe(gulp.dest('dist/client/templates'));
});

gulp.task('copy_client_root', function(){
  return gulp.src(['src/client/index.html'])
      .pipe(gulp.dest('dist/client/'));
});

gulp.task('copy_node', function(){
  return gulp.src(['src/**/*', '!src/client/**/*', './package.json', '!./node_modules', '!./config.json'])
      .pipe(gulp.dest('dist/'));
});

gulp.task('copy_bootstrap', ['install_client'], function(){
	gulp.src(['!src/client/node_modules/bootstrap/dist/js/**','!src/client/node_modules/bootstrap/dist/js/','src/client/node_modules/bootstrap/dist/**'])
	.pipe(gulp.dest('dist/client/lib'));
});

gulp.task('install_api', ['copy_node'], function(){
  return gulp.src('dist/package.json')
    .pipe(install({production:true, ignoreScripts:true}));
});

gulp.task('install_client', function(){
  return gulp.src('src/client/package.json')
    .pipe(install({production:true, ignoreScripts:true}));
});

gulp.task('install_typings', function(){
	return gulp.src("./typings.json")
  	.pipe(gulpTypings());
});

gulp.task('copy', ['copy_node', 'copy_client_root', 'copy_templates', 'copy_bootstrap']);
gulp.task('install', ['install_api', 'install_client', 'install_typings']);

gulp.task('watch', function(){
  console.log('watching for changes...');
  gulp.watch(['src/client/**/*.html'], ['copy_client_root', 'copy_templates']);
  gulp.watch(['./crypt.png'], ['inject-favicon-markups']);
  gulp.watch(['src/**/*', '!src/client/**/*'], ['copy_node']);
  gulp.watch(['./package.json'], ['install_api']);
  //gulp.watch(['src/client/package.json', 'src/client/src/**/*.ts'], ['install_client', 'browserify']);
	return bundle(true);
});

// Default Task
gulp.task('default', ['copy', 'inject-favicon-markups', 'install', 'browserify']);
<commit_msg>minify the app<commit_after>const gulp        = require('gulp');
const install     = require('gulp-install');
const realFavicon = require('gulp-real-favicon');
const source 			= require('vinyl-source-stream');
const buffer      = require('vinyl-buffer');
const browserify  = require('browserify');
const watchify 		= require('watchify');
const uglify      = require('gulp-uglify');
const tsify       = require('tsify');
const fs          = require('fs');
const gulpTypings = require("gulp-typings");
const tsconfig 		= require('./tsconfig.json');
const FAVICON_DATA_FILE = 'faviconData.json';

gulp.task('generate-favicon', function(done) {
	realFavicon.generateFavicon({
		masterPicture: './crypt.svg',
		dest: 'dist/client/favicons',
		iconsPath: '/favicons',
		design: {
			ios: {
				pictureAspect: 'backgroundAndMargin',
				backgroundColor: '#352f2f',
				margin: '14%',
				assets: {
					ios6AndPriorIcons: false,
					ios7AndLaterIcons: false,
					precomposedIcons: false,
					declareOnlyDefaultIcon: true
				},
				appName: 'Crypt'
			},
			desktopBrowser: {},
			windows: {
				pictureAspect: 'noChange',
				backgroundColor: '#352f2f',
				onConflict: 'override',
				assets: {
					windows80Ie10Tile: false,
					windows10Ie11EdgeTiles: {
						small: false,
						medium: true,
						big: false,
						rectangle: false
					}
				},
				appName: 'Crypt'
			},
			androidChrome: {
				pictureAspect: 'noChange',
				themeColor: '#352f2f',
				manifest: {
					name: 'Crypt',
					display: 'standalone',
					orientation: 'notSet',
					onConflict: 'override',
					declared: true
				},
				assets: {
					legacyIcon: false,
					lowResolutionIcons: false
				}
			},
			safariPinnedTab: {
				pictureAspect: 'silhouette',
				themeColor: '#01cccc'
			}
		},
		settings: {
			compression: 5,
			scalingAlgorithm: 'Cubic',
			errorOnImageTooSmall: false
		},
		versioning: {
			paramName: 'v',
			paramValue: 'vMroeOKLRG'
		},
		markupFile: FAVICON_DATA_FILE
	}, function() {
		done();
	});
});

gulp.task('inject-favicon-markups', ['generate-favicon', 'copy_client_root'],function() {
	gulp.src('dist/client/index.html')
		.pipe(realFavicon.injectFaviconMarkups(JSON.parse(fs.readFileSync(FAVICON_DATA_FILE)).favicon.html_code))
		.pipe(gulp.dest('dist/client/'));
});

gulp.task('check-for-favicon-update', function(done) {
	var currentVersion = JSON.parse(fs.readFileSync(FAVICON_DATA_FILE)).version;
	realFavicon.checkForUpdates(currentVersion, function(err) {
		if (err) {
			throw err;
		}
	});
});

function handleTsErrors(err){
	if(typeof err != typeof ''){
		err = JSON.stringify(err, null, 2);
	}
	console.error(err);
}

function bundle(watch){
	var props = {debug:true};
	var b = watch ? watchify(browserify(props)) : browserify(props);
	b.add('src/client/src/main.ts')
	.plugin(tsify, tsconfig);
	function rebundle(){
		b.bundle()
		.on('error', handleTsErrors)
		.pipe(source('main.min.js'))
		.pipe(buffer())
		.pipe(uglify())
		.pipe(gulp.dest('./dist/client/app/'));
	}
	b.on('update', function() {
		console.log('Rebundling...');
		rebundle();
	});
	return rebundle();
}

gulp.task('browserify', ['install_client', 'install_typings'], function(){
	return bundle(false);
});

gulp.task('watchify', ['install_client', 'install_typings'], function(){
	return bundle(true);
});

gulp.task('copy_templates', function(){
  return gulp.src(['src/client/templates/*.html'])
      .pipe(gulp.dest('dist/client/templates'));
});

gulp.task('copy_client_root', function(){
  return gulp.src(['src/client/index.html'])
      .pipe(gulp.dest('dist/client/'));
});

gulp.task('copy_node', function(){
  return gulp.src(['src/**/*', '!src/client/**/*', './package.json', '!./node_modules', '!./config.json'])
      .pipe(gulp.dest('dist/'));
});

gulp.task('copy_bootstrap', ['install_client'], function(){
	gulp.src(['!src/client/node_modules/bootstrap/dist/js/**','!src/client/node_modules/bootstrap/dist/js/','src/client/node_modules/bootstrap/dist/**'])
	.pipe(gulp.dest('dist/client/lib'));
});

gulp.task('install_api', ['copy_node'], function(){
  return gulp.src('dist/package.json')
    .pipe(install({production:true, ignoreScripts:true}));
});

gulp.task('install_client', function(){
  return gulp.src('src/client/package.json')
    .pipe(install({production:true, ignoreScripts:true}));
});

gulp.task('install_typings', function(){
	return gulp.src("./typings.json")
  	.pipe(gulpTypings());
});

gulp.task('copy', ['copy_node', 'copy_client_root', 'copy_templates', 'copy_bootstrap']);
gulp.task('install', ['install_api', 'install_client', 'install_typings']);

gulp.task('watch', function(){
  console.log('watching for changes...');
  gulp.watch(['src/client/**/*.html'], ['copy_client_root', 'copy_templates']);
  gulp.watch(['./crypt.png'], ['inject-favicon-markups']);
  gulp.watch(['src/**/*', '!src/client/**/*'], ['copy_node']);
  gulp.watch(['./package.json'], ['install_api']);
	return bundle(true);
});

// Default Task
gulp.task('default', ['copy', 'inject-favicon-markups', 'install', 'browserify']);
<|endoftext|>


<commit_before>var vows      = require('vows'),
    assert    = require('assert'),
    server    = require('../lib/appserver'),
    mrequest  = require('./mocks/request'),
    mresponse = require('./mocks/response');

vows.describe('Run Routes').addBatch({
    'string route added for request': {
        topic: function () {
            var appserver = new server.appserver();
            var thisp = this;
            appserver.addRoute("/foo", function (request, response, options) {
                thisp.callback(undefined, request, response, options);
            });

            var req = new mrequest.request();
            req.url = "/foo";
            var res = new mresponse.response();

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(response.statusCode(), 200);
        }
    },
    'string regex route added for request': {
        topic: function () {
            var appserver = new server.appserver();
            var thisp = this;
            appserver.addRoute(".+", function (request, response, options) {
                thisp.callback(undefined, request, response, options);
            });

            var req = new mrequest.request();
            req.url = "/foo";
            var res = new mresponse.response();

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(response.statusCode(), 200);
        }
    },
    'plugin route added for request': {
        topic: function () {
            var thisp = this;
            var plugin = { init: function () { }, plugin: function (a,b,c) { thisp.callback(undefined, a, b, c); } };

            var appserver = new server.appserver();

            appserver.addRoute("^\/foo", plugin);

            var res = new mresponse.response();
            var req = new mrequest.request();
            req.url = "/foo";

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(response.statusCode(), 200);
        }
    },
    'route not fired': {
        topic: function () {
            var thisp = this;

            var appserver = new server.appserver();

            appserver.addRoute("^\/foo", function(a,b,c) { thisp.callback(1,a,b,c); });

            setTimeout(function() { thisp.callback('callback not fired'); }, 50);
            var res = new mresponse.response();
            var req = new mrequest.request();
            req.url = "/bar";

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(err, 'callback not fired');
        }
    },
    'replacing the router with a default true': {
        topic: function () {
            var thisp = this;

            var appserver = new server.appserver({ checkRoute: function () { return true; } });

            appserver.addRoute("blah blah blah", function (request, response, options) {
                thisp.callback(undefined, request, response, options);
            });

            var res = new mresponse.response();
            var req = new mrequest.request();
            req.url = "/bar";

            appserver.handleRequest(req, res, appserver);
        },
        'should cause any route to fire': function (err, request, response, options) {
            assert.equal(err, undefined);
        }
    }
}).export(module);
<commit_msg>added test for event order<commit_after>var vows      = require('vows'),
    assert    = require('assert'),
    server    = require('../lib/appserver'),
    mrequest  = require('./mocks/request'),
    mresponse = require('./mocks/response');

vows.describe('Run Routes').addBatch({
    'string route added for request': {
        topic: function () {
            var appserver = new server.appserver();
            var thisp = this;
            appserver.addRoute("/foo", function (request, response, options) {
                thisp.callback(undefined, request, response, options);
            });

            var req = new mrequest.request();
            req.url = "/foo";
            var res = new mresponse.response();

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(response.statusCode(), 200);
        }
    },
    'string regex route added for request': {
        topic: function () {
            var appserver = new server.appserver();
            var thisp = this;
            appserver.addRoute(".+", function (request, response, options) {
                thisp.callback(undefined, request, response, options);
            });

            var req = new mrequest.request();
            req.url = "/foo";
            var res = new mresponse.response();

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(response.statusCode(), 200);
        }
    },
    'plugin route added for request': {
        topic: function () {
            var thisp = this;
            var plugin = { init: function () { }, plugin: function (a,b,c) { thisp.callback(undefined, a, b, c); } };

            var appserver = new server.appserver();

            appserver.addRoute("^\/foo", plugin);

            var res = new mresponse.response();
            var req = new mrequest.request();
            req.url = "/foo";

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(response.statusCode(), 200);
        }
    },
    'route not fired': {
        topic: function () {
            var thisp = this;

            var appserver = new server.appserver();

            appserver.addRoute("^\/foo", function(a,b,c) { thisp.callback(1,a,b,c); });

            setTimeout(function() { thisp.callback('callback not fired'); }, 50);
            var res = new mresponse.response();
            var req = new mrequest.request();
            req.url = "/bar";

            appserver.handleRequest(req, res, appserver);
        },
        'results from run': function (err, request, response, options) {
            assert.equal(err, 'callback not fired');
        }
    },
    'replacing the router with a default true': {
        topic: function () {
            var thisp = this;

            var appserver = new server.appserver({ checkRoute: function () { return true; } });

            appserver.addRoute("blah blah blah", function (request, response, options) {
                thisp.callback(undefined, request, response, options);
            });

            var res = new mresponse.response();
            var req = new mrequest.request();
            req.url = "/bar";

            appserver.handleRequest(req, res, appserver);
        },
        'should cause any route to fire': function (err, request, response, options) {
            assert.equal(err, undefined);
        }
    },
    'events fired at the end of routes': {
        topic: function () {
            var thisp = this;

            var appserver = new server.appserver();

            var msg = [ ];
            appserver.addRoute(".+", function (request, response) {
                response.on("pre.complete", function () { msg.push("pre.complete"); });
                response.next();
            }, { section: "pre" });
            appserver.addRoute(".+", function (request, response, options) {
                msg.push("main");
                thisp.callback(undefined, msg);
            });

            var res = new mresponse.response();
            var req = new mrequest.request();
            req.url = "/bar";

            appserver.handleRequest(req, res, appserver);
        },
        'should be dealt with before the next route starts': function (err, msg) {
            assert.equal(err, undefined);
            assert.equal(msg[0], "pre.complete");
            assert.equal(msg[1], "main");
        }
    }
}).export(module);
<|endoftext|>


<commit_before><commit_msg>:new: add decrypt/encrypt tasks to gulpfile.<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
'use strict'

var path = require('path');
var os = require('os')
var fs = require('fs')
const BlinkDiff = require('blink-diff');

var platform = process.env.platform || 'android';
platform = platform.toLowerCase();
var browser = process.env.browser || '';

const isIOS = platform === 'ios';
const isRunInCI = process.env.run_in_ci?true:false;

var iOSOpts = {
  deviceName: 'iPhone 6',
  target: 'ios',
  platformName: 'iOS',
  slowEnv: isRunInCI,
  app: path.join(__dirname, '..', '../ios/playground/build/Debug-iphonesimulator/WeexDemo.app')
};

var androidOpts = {
  platformName: 'Android',
  target: 'android',
  slowEnv: isRunInCI,
  app: path.join(__dirname, '..', '../android/playground/app/build/outputs/apk/playground-debug.apk')
};

var androidChromeOpts = {
  platformName: 'Android',
  target: 'web',
  browserName: 'Chrome'
};

if(isRunInCI){
    console.log("Running in CI Envirment");
}

function getIpAddress(){
    let ifs = os.networkInterfaces()
    let addresses = ['127.0.0.1'];
    for( var i in ifs){
        let interfaces = ifs[i];
        interfaces.forEach((face)=>{
            if(!face.internal && face.family == 'IPv4'){
                addresses.unshift(face.address);
            }
        })
    }
    return addresses[0];
}

function diffImage(imageAPath, imageB, threshold, outputPath) {
  if (!fs.existsSync(imageAPath)) {
    fs.writeFileSync(imageAPath, imageB, 'base64', function(err) {
        console.log(err);
    });
  }

  return new Promise((resolve, reject) => {
    var diff = new BlinkDiff({
      imageAPath: imageAPath, // Path
      imageB: imageB,         // Buffer
      thresholdType: BlinkDiff.THRESHOLD_PIXEL,
      threshold: threshold,
      imageOutputPath: outputPath,
      cropImageA:isIOS?{y:128}:{y:72,height:1700},
      cropImageB:isIOS?{y:128}:{y:72,height:1700}
    });

    diff.run((err, result) => {
      if (err) {
        return reject(err);
      }
      var ifPassed = diff.hasPassed(result.code);
      console.log(ifPassed ? 'Image Comparison Passed' : 'Image Comparison Failed');
      console.log(`Found ${result.differences} pixel differences between two images.`);
      resolve(ifPassed);
    });
  });
}

module.exports = {
    getConfig:function(){
        if(browser){
            return androidChromeOpts;
        }
        return isIOS? iOSOpts : androidOpts;
    },
    getDeviceHost:function(){
        return getIpAddress()+":12581";
    },
    getPage:function(name){
        let url
        if(browser){
             url = 'http://'+ getIpAddress()+':12581/vue.html?page=/test/build-web'+name
        }else{
            url = 'wxpage://' + getIpAddress()+":12581/test/build"+name;
        }
        console.log(url)
        return url
    },
    getTimeoutMills:function(){
        return ( isRunInCI ? 60 : 10 ) * 60 * 1000;
    },
    getGETActionWaitTimeMills:function(){
        return (isRunInCI ? 120 : 5 ) * 1000;
    },
    diffImage,
    createDriver:function(wd){
        var driver = global._wxDriver;
        if(!driver){
            console.log('Create new driver');
            let driverFactory = wd(this.getConfig())
            driverFactory.addPromiseChainMethod('dragUpAndDown',function(){
                return this
                .getWindowSize()
                .then(size=>{
                    let middleX = size.width * 0.5
                    return this
                    .touch('drag', {fromX:middleX, fromY:size.height*0.7, toX:middleX, toY: size.height*0.3, duration: 1})
                    .sleep(1000)
                    .touch('drag', {fromX:middleX, fromY:size.height*0.3, toX:middleX, toY: size.height*0.7, duration: 1})
                    .sleep(1000)
                })
            })
            driverFactory.addPromiseChainMethod('dragUp',function(distance){
                return this
                .getWindowSize()
                .then(size=>{
                    let middleX = size.width * 0.5
                    let startY = size.height * 0.3
                    return this
                    .touch('drag', {fromX:middleX, fromY:startY+distance, toX:middleX, toY: startY, duration: 1})
                    .sleep(1000)
                })
            })
          driverFactory.addPromiseChainMethod('swipeLeft', function (distanceRatio, yRatio) {
                return this
                  .getWindowSize()
                  .then(size => {
                    let y = yRatio * size.height;
                    let startX = size.width * 0.8;
                    let endX = startX - size.width * distanceRatio;
                    return this
                      .touch('drag', {fromX: startX, toX: endX, fromY: y, toY: y, duration: 1})
                      .sleep(1000)
                  })
          })
          driverFactory.addPromiseChainMethod('swipeRight', function (distanceRatio, yRatio) {
            return this
              .getWindowSize()
              .then(size => {
                let y = yRatio * size.height;
                let startX = size.width * 0.2;
                let endX = startX + size.width * distanceRatio;
                return this
                  .touch('drag', {fromX: startX, toX: endX, fromY: y, toY: y, duration: 1})
                  .sleep(1000)
              })
          })
            driver = driverFactory.initPromiseChain();
            driver.configureHttp({
                timeout: 100000
            });
            global._wxDriver = driver;
        }

        return driver;
    },
    init:function(driver){
        if(driver._isInit)
            return driver.status()
        else{
            driver._isInit = true;
            return driver.initDriver()
        }
    },
    quit:function(driver){
        if(browser)
            return driver.quit()
        return driver.sleep(1000).back().sleep(1000);
    }
}
<commit_msg>* [test] ignore android nav bar in screenshot diff test<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
'use strict'

var path = require('path');
var os = require('os')
var fs = require('fs')
const BlinkDiff = require('blink-diff');

var platform = process.env.platform || 'android';
platform = platform.toLowerCase();
var browser = process.env.browser || '';

const isIOS = platform === 'ios';
const isRunInCI = process.env.run_in_ci?true:false;

var iOSOpts = {
  deviceName: 'iPhone 6',
  target: 'ios',
  platformName: 'iOS',
  slowEnv: isRunInCI,
  app: path.join(__dirname, '..', '../ios/playground/build/Debug-iphonesimulator/WeexDemo.app')
};

var androidOpts = {
  platformName: 'Android',
  target: 'android',
  slowEnv: isRunInCI,
  app: path.join(__dirname, '..', '../android/playground/app/build/outputs/apk/playground-debug.apk')
};

var androidChromeOpts = {
  platformName: 'Android',
  target: 'web',
  browserName: 'Chrome'
};

if(isRunInCI){
    console.log("Running in CI Envirment");
}

function getIpAddress(){
    let ifs = os.networkInterfaces()
    let addresses = ['127.0.0.1'];
    for( var i in ifs){
        let interfaces = ifs[i];
        interfaces.forEach((face)=>{
            if(!face.internal && face.family == 'IPv4'){
                addresses.unshift(face.address);
            }
        })
    }
    return addresses[0];
}

function diffImage(imageAPath, imageB, threshold, outputPath) {
  if (!fs.existsSync(imageAPath)) {
    fs.writeFileSync(imageAPath, imageB, 'base64', function(err) {
        console.log(err);
    });
  }

  return new Promise((resolve, reject) => {
    var diff = new BlinkDiff({
      imageAPath: imageAPath, // Path
      imageB: imageB,         // Buffer
      thresholdType: BlinkDiff.THRESHOLD_PIXEL,
      threshold: threshold,
      imageOutputPath: outputPath,
      cropImageA:isIOS?{y:128}:{y:242,height:1530},//android: 242 - status bar(72)+navigator bar(170)
      cropImageB:isIOS?{y:128}:{y:242,height:1530}
    });

    diff.run((err, result) => {
      if (err) {
        return reject(err);
      }
      var ifPassed = diff.hasPassed(result.code);
      console.log(ifPassed ? 'Image Comparison Passed' : 'Image Comparison Failed');
      console.log(`Found ${result.differences} pixel differences between two images.`);
      resolve(ifPassed);
    });
  });
}

module.exports = {
    getConfig:function(){
        if(browser){
            return androidChromeOpts;
        }
        return isIOS? iOSOpts : androidOpts;
    },
    getDeviceHost:function(){
        return getIpAddress()+":12581";
    },
    getPage:function(name){
        let url
        if(browser){
             url = 'http://'+ getIpAddress()+':12581/vue.html?page=/test/build-web'+name
        }else{
            url = 'wxpage://' + getIpAddress()+":12581/test/build"+name;
        }
        console.log(url)
        return url
    },
    getTimeoutMills:function(){
        return ( isRunInCI ? 60 : 10 ) * 60 * 1000;
    },
    getGETActionWaitTimeMills:function(){
        return (isRunInCI ? 120 : 5 ) * 1000;
    },
    diffImage,
    createDriver:function(wd){
        var driver = global._wxDriver;
        if(!driver){
            console.log('Create new driver');
            let driverFactory = wd(this.getConfig())
            driverFactory.addPromiseChainMethod('dragUpAndDown',function(){
                return this
                .getWindowSize()
                .then(size=>{
                    let middleX = size.width * 0.5
                    return this
                    .touch('drag', {fromX:middleX, fromY:size.height*0.7, toX:middleX, toY: size.height*0.3, duration: 1})
                    .sleep(1000)
                    .touch('drag', {fromX:middleX, fromY:size.height*0.3, toX:middleX, toY: size.height*0.7, duration: 1})
                    .sleep(1000)
                })
            })
            driverFactory.addPromiseChainMethod('dragUp',function(distance){
                return this
                .getWindowSize()
                .then(size=>{
                    let middleX = size.width * 0.5
                    let startY = size.height * 0.3
                    return this
                    .touch('drag', {fromX:middleX, fromY:startY+distance, toX:middleX, toY: startY, duration: 1})
                    .sleep(1000)
                })
            })
          driverFactory.addPromiseChainMethod('swipeLeft', function (distanceRatio, yRatio) {
                return this
                  .getWindowSize()
                  .then(size => {
                    let y = yRatio * size.height;
                    let startX = size.width * 0.8;
                    let endX = startX - size.width * distanceRatio;
                    return this
                      .touch('drag', {fromX: startX, toX: endX, fromY: y, toY: y, duration: 1})
                      .sleep(1000)
                  })
          })
          driverFactory.addPromiseChainMethod('swipeRight', function (distanceRatio, yRatio) {
            return this
              .getWindowSize()
              .then(size => {
                let y = yRatio * size.height;
                let startX = size.width * 0.2;
                let endX = startX + size.width * distanceRatio;
                return this
                  .touch('drag', {fromX: startX, toX: endX, fromY: y, toY: y, duration: 1})
                  .sleep(1000)
              })
          })
            driver = driverFactory.initPromiseChain();
            driver.configureHttp({
                timeout: 100000
            });
            global._wxDriver = driver;
        }

        return driver;
    },
    init:function(driver){
        if(driver._isInit)
            return driver.status()
        else{
            driver._isInit = true;
            return driver.initDriver()
        }
    },
    quit:function(driver){
        if(browser)
            return driver.quit()
        return driver.sleep(1000).back().sleep(1000);
    }
}
<|endoftext|>


<commit_before>'use strict';

var config = require('./gulp.config.js')();
var argv = require('yargs').argv;
var gulp = require('gulp');
var exec = require('child_process').exec;
var sass = require('gulp-sass');
var merge = require('merge2');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var cssnano = require('gulp-cssnano');
var embedTemplates = require('gulp-angular-embed-templates');
var SystemBuilder = require('systemjs-builder');
var typescript = require('gulp-typescript');
var tsconfig = require('./tsconfig.json');
var tsProject = typescript.createProject(tsconfig.compilerOptions);

if (!argv.production) {
    var clean = require('gulp-clean');
    var tslint = require('gulp-tslint');
    var sassLint = require('gulp-sass-lint');
    var Server = require('karma').Server;
    var remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul');
}

gulp.task('copy:npmfiles', function() {
    return gulp.src(config.npm.files, {base: config.path.npm})
        .pipe(gulp.dest(config.path.build));
});

gulp.task('copy:systemjsconfig', function() {
    return gulp.src(config.systemjs.files)
        .pipe(gulp.dest(config.path.build));
});

gulp.task('copy:frontendImgFiles', function() {
    return gulp.src(config.frontend.imgFiles, {base: config.path.frontend})
        .pipe(gulp.dest(config.path.build));
});

gulp.task('copy:staticfiles', ['copy:npmfiles', 'copy:systemjsconfig', 'copy:frontendImgFiles']);

gulp.task('compile:sass', function() {
    return gulp.src(config.sass.files)
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(concat(config.sass.bundle.dev_name))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(config.path.build));
});

gulp.task('compile:typescript', function() {
    var tsResult = gulp.src(config.typescript.files)
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));
    return merge([
        tsResult.dts.pipe(gulp.dest(config.path.build)),
        tsResult.js
            .pipe(embedTemplates())
            .pipe(sourcemaps.write('./', {sourceRoot: config.path.partial.frontend}))
            .pipe(gulp.dest(config.path.build + config.path.partial.frontend))
    ]);
});

gulp.task('bundle:typescript', ['copy:staticfiles', 'compile:typescript'], function() {
    var builder = new SystemBuilder(config.path.build, config.systemjs.config);
    builder.loader.defaultJSExtensions = true;
    return builder.buildStatic('frontend/main', config.typescript.bundle.path, config.typescript.bundle.config);
});

gulp.task('bundle:dependencies', function() {
    return gulp.src(config.npm.angular_dependencies.files)
        .pipe(concat(config.npm.angular_dependencies.name))
        .pipe(uglify())
        .pipe(gulp.dest(config.path.dist));
});

gulp.task('bundle:sass', ['compile:sass'], function() {
    return gulp.src(config.sass.bundle.files)
        .pipe(concat(config.sass.bundle.name))
        .pipe(cssnano())
        .pipe(gulp.dest(config.path.dist));
});

gulp.task('optimize:frontendImgFiles', function() {
    return gulp.src(config.frontend.imgFiles, {base: config.path.frontend})
        .pipe(gulp.dest(config.path.dist));
});

gulp.task('dist', ['bundle:dependencies', 'bundle:typescript', 'bundle:sass', 'optimize:frontendImgFiles']);

gulp.task('watch:sass', ['compile:sass'], function() {
    return gulp.watch(config.sass.files, ['compile:sass']);
});

gulp.task('watch:typescript', ['compile:typescript'], function() {
    return gulp.watch(config.typescript.files, ['compile:typescript']);
});

gulp.task('watch:frontendImgFiles', ['copy:frontendImgFiles'], function() {
    return gulp.watch(config.frontend.imgFiles, {cwd: config.root}, ['copy:frontendImgFiles']);
});

gulp.task('watch:html', ['compile:typescript'], function() {
    return gulp.watch(config.frontend.htmlFiles, ['compile:typescript']);
});

gulp.task('watch', ['watch:sass', 'watch:typescript', 'watch:frontendImgFiles', 'watch:html']);

gulp.task('build', ['copy:staticfiles', 'compile:typescript', 'compile:sass']);

gulp.task('default', function() {
  // place code for your default task here
});

if (!argv.production) {
    gulp.task('lint:python', function(done) {
        var command = 'prospector crowdgezwitscher --profile ../.landscape.yml';
        var lint = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        lint.on('close', function(exitcode) {
            done(exitcode ? new Error('Python linting failed') : 0);
        });
    });

    gulp.task('lint:typescript', function() {
        return gulp.src(config.typescript.files)
            .pipe(tslint({
                configuration: 'tslint.json',
                formatter: 'prose'
            }))
            .pipe(tslint.report({
                emitError: false,
                summarizeFailureOutput: true
            }));
    });

    gulp.task('lint:sass', function() {
        return gulp.src(config.sass.files)
            .pipe(sassLint())
            .pipe(sassLint.format());
    });

    gulp.task('lint', ['lint:python', 'lint:typescript', 'lint:sass']);

    gulp.task('clean:build', function() {
        return gulp.src(config.path.build, {read: false})
            .pipe(clean());
    });

    gulp.task('clean:dist', function() {
        return gulp.src(config.path.dist, {read: false})
            .pipe(clean());
    });

    gulp.task('clean:report', function() {
        return gulp.src(config.path.report, {read: false})
            .pipe(clean());
    });

    gulp.task('clean', ['clean:build', 'clean:dist', 'clean:report']);

    gulp.task('test:typescript', ['build'], function(done) {
        new Server({
            configFile: config.report.karma.configFile,
            singleRun: true,
        }, function(exitCode) {
            done(exitcode ? new Error('Typescript tests failed') : 0);
        }).start();
    });

    gulp.task('test:e2e', function(done) {
        var command = 'PHANTOMJS_EXECUTABLE=./node_modules/phantomjs-prebuilt/bin/phantomjs ./node_modules/casperjs/bin/casperjs test ' + config.e2e.files;
        var casper = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        casper.on('close', function(exitcode) {
            done(exitcode ? new Error('E2E tests failed') : 0);
        });
    });

    gulp.task('test:python', function(done) {
        var command = 'python crowdgezwitscher/manage.py test crowdgezwitscher';
        var test = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        test.on('close', function(exitcode) {
            done(exitcode ? new Error('Python tests failed') : 0);
        });
    });

    gulp.task('coverage:typescript', function(done) {
        new Server({
            configFile: config.report.karma.configFile,
            singleRun: true,
        }, remapCoverage).start();

        function remapCoverage(exitcode) {
            console.log('path', config.report.path);
            gulp.src(config.report.path)
                .pipe(remapIstanbul({
                    reports: config.report.remap.reports,
                }))
                .on('finish', function() {
                    done(exitcode ? new Error('Typescript coverage report failed') : 0);
                });
        }
    });

    gulp.task('coverage:python', function(done) {
        var command = 'coverage run crowdgezwitscher/manage.py test crowdgezwitscher';
        var coverage = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        coverage.on('close', function(exitcode) {
            done(exitcode ? new Error('Python coverage report failed') : 0);
        });
    });
}
<commit_msg>Hotfix: gulp file.<commit_after>'use strict';

var config = require('./gulp.config.js')();
var argv = require('yargs').argv;
var gulp = require('gulp');
var exec = require('child_process').exec;
var sass = require('gulp-sass');
var merge = require('merge2');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var cssnano = require('gulp-cssnano');
var embedTemplates = require('gulp-angular-embed-templates');
var SystemBuilder = require('systemjs-builder');
var typescript = require('gulp-typescript');
var tsconfig = require('./tsconfig.json');
var tsProject = typescript.createProject(tsconfig.compilerOptions);

if (!argv.production) {
    var clean = require('gulp-clean');
    var tslint = require('gulp-tslint');
    var sassLint = require('gulp-sass-lint');
    var Server = require('karma').Server;
    var remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul');
}

gulp.task('copy:npmfiles', function() {
    return gulp.src(config.npm.files, {base: config.path.npm})
        .pipe(gulp.dest(config.path.build));
});

gulp.task('copy:systemjsconfig', function() {
    return gulp.src(config.systemjs.files)
        .pipe(gulp.dest(config.path.build));
});

gulp.task('copy:frontendImgFiles', function() {
    return gulp.src(config.frontend.imgFiles, {base: config.path.frontend})
        .pipe(gulp.dest(config.path.build));
});

gulp.task('copy:staticfiles', ['copy:npmfiles', 'copy:systemjsconfig', 'copy:frontendImgFiles']);

gulp.task('compile:sass', function() {
    return gulp.src(config.sass.files)
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(concat(config.sass.bundle.dev_name))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(config.path.build));
});

gulp.task('compile:typescript', function() {
    var tsResult = gulp.src(config.typescript.files)
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));
    return merge([
        tsResult.dts.pipe(gulp.dest(config.path.build)),
        tsResult.js
            .pipe(embedTemplates())
            .pipe(sourcemaps.write('./', {sourceRoot: config.path.partial.frontend}))
            .pipe(gulp.dest(config.path.build + config.path.partial.frontend))
    ]);
});

gulp.task('bundle:typescript', ['copy:staticfiles', 'compile:typescript'], function() {
    var builder = new SystemBuilder(config.path.build, config.systemjs.config);
    builder.loader.defaultJSExtensions = true;
    return builder.buildStatic('frontend/main', config.typescript.bundle.path, config.typescript.bundle.config);
});

gulp.task('bundle:dependencies', function() {
    return gulp.src(config.npm.angular_dependencies.files)
        .pipe(concat(config.npm.angular_dependencies.name))
        .pipe(uglify())
        .pipe(gulp.dest(config.path.dist));
});

gulp.task('bundle:sass', ['compile:sass'], function() {
    return gulp.src(config.sass.bundle.files)
        .pipe(concat(config.sass.bundle.name))
        .pipe(cssnano())
        .pipe(gulp.dest(config.path.dist));
});

gulp.task('optimize:frontendImgFiles', function() {
    return gulp.src(config.frontend.imgFiles, {base: config.path.frontend})
        .pipe(gulp.dest(config.path.dist));
});

gulp.task('dist', ['bundle:dependencies', 'bundle:typescript', 'bundle:sass', 'optimize:frontendImgFiles']);

gulp.task('watch:sass', ['compile:sass'], function() {
    return gulp.watch(config.sass.files, ['compile:sass']);
});

gulp.task('watch:typescript', ['compile:typescript'], function() {
    return gulp.watch(config.typescript.files, ['compile:typescript']);
});

gulp.task('watch:frontendImgFiles', ['copy:frontendImgFiles'], function() {
    return gulp.watch(config.frontend.imgFiles, {cwd: config.root}, ['copy:frontendImgFiles']);
});

gulp.task('watch:html', ['compile:typescript'], function() {
    return gulp.watch(config.frontend.htmlFiles, ['compile:typescript']);
});

gulp.task('watch', ['watch:sass', 'watch:typescript', 'watch:frontendImgFiles', 'watch:html']);

gulp.task('build', ['copy:staticfiles', 'compile:typescript', 'compile:sass']);

gulp.task('default', function() {
  // place code for your default task here
});

if (!argv.production) {
    gulp.task('lint:python', function(done) {
        var command = 'prospector crowdgezwitscher --profile ../.landscape.yml';
        var lint = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        lint.on('close', function(exitcode) {
            done(exitcode ? new Error('Python linting failed') : 0);
        });
    });

    gulp.task('lint:typescript', function() {
        return gulp.src(config.typescript.files)
            .pipe(tslint({
                configuration: 'tslint.json',
                formatter: 'prose'
            }))
            .pipe(tslint.report({
                emitError: false,
                summarizeFailureOutput: true
            }));
    });

    gulp.task('lint:sass', function() {
        return gulp.src(config.sass.files)
            .pipe(sassLint())
            .pipe(sassLint.format());
    });

    gulp.task('lint', ['lint:python', 'lint:typescript', 'lint:sass']);

    gulp.task('clean:build', function() {
        return gulp.src(config.path.build, {read: false})
            .pipe(clean());
    });

    gulp.task('clean:dist', function() {
        return gulp.src(config.path.dist, {read: false})
            .pipe(clean());
    });

    gulp.task('clean:report', function() {
        return gulp.src(config.path.report, {read: false})
            .pipe(clean());
    });

    gulp.task('clean', ['clean:build', 'clean:dist', 'clean:report']);

    gulp.task('test:typescript', ['build'], function(done) {
        new Server({
            configFile: config.report.karma.configFile,
            singleRun: true,
        }, function(exitcode) {
            done(exitcode ? new Error('Typescript tests failed') : 0);
        }).start();
    });

    gulp.task('test:e2e', function(done) {
        var command = 'PHANTOMJS_EXECUTABLE=./node_modules/phantomjs-prebuilt/bin/phantomjs ./node_modules/casperjs/bin/casperjs test ' + config.e2e.files;
        var casper = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        casper.on('close', function(exitcode) {
            done(exitcode ? new Error('E2E tests failed') : 0);
        });
    });

    gulp.task('test:python', function(done) {
        var command = 'python crowdgezwitscher/manage.py test crowdgezwitscher';
        var test = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        test.on('close', function(exitcode) {
            done(exitcode ? new Error('Python tests failed') : 0);
        });
    });

    gulp.task('coverage:typescript', function(done) {
        new Server({
            configFile: config.report.karma.configFile,
            singleRun: true,
        }, remapCoverage).start();

        function remapCoverage(exitcode) {
            console.log('path', config.report.path);
            gulp.src(config.report.path)
                .pipe(remapIstanbul({
                    reports: config.report.remap.reports,
                }))
                .on('finish', function() {
                    done(exitcode ? new Error('Typescript coverage report failed') : 0);
                });
        }
    });

    gulp.task('coverage:python', function(done) {
        var command = 'coverage run crowdgezwitscher/manage.py test crowdgezwitscher';
        var coverage = exec(command, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
        });
        coverage.on('close', function(exitcode) {
            done(exitcode ? new Error('Python coverage report failed') : 0);
        });
    });
}
<|endoftext|>


<commit_before>//@ts-check
var assert = require('assert')
    , test = require('selenium-webdriver/testing')
    , webdriver = require('selenium-webdriver')
    , server = require('../server')
    ;

var port = process.env.PORT || 9999;

test.describe('Google search', () => {
    var driver /*= (new webdriver.Builder()).
        withCapabilities(webdriver.Capabilities.chrome()).
        build()*/;

    var s;

    test.before(function () {
        // If we are using Travis, let's connect to Sauce Labs remote web drivers
        if (process.env.TRAVIS || false) {
            var username = process.env.SAUCE_USERNAME
                , accessKey = process.env.SAUCE_ACCESS_KEY
                ;
            process.env.SELENIUM_REMOTE_URL = `https://${username}:${accessKey}@localhost:4445`;
        }

        driver = (new webdriver.Builder()).
            withCapabilities(webdriver.Capabilities.chrome()).
            build();

        if (!process.env.TRAVIS) {
            return new Promise((resolve, reject) => {
                s = server.createAndListen(port, resolve);
            });
        }
    });

    test.after(() => {
        driver.quit();
        s.close();
    });

    test.it('Should work', function () {
        driver.get(`http://localhost:${port}/`);
        return driver.findElement(webdriver.By.tagName('p'))
            .then(el => el.getText())
            .then(text => assert.equal(text, "Hi everybody!"))
            ;
    });
});<commit_msg>Close server only if it was started.<commit_after>//@ts-check
var assert = require('assert')
    , test = require('selenium-webdriver/testing')
    , webdriver = require('selenium-webdriver')
    , server = require('../server')
    ;

var port = process.env.PORT || 9999;

test.describe('Google search', () => {
    var driver /*= (new webdriver.Builder()).
        withCapabilities(webdriver.Capabilities.chrome()).
        build()*/;

    var s;

    test.before(function () {
        // If we are using Travis, let's connect to Sauce Labs remote web drivers
        if (process.env.TRAVIS || false) {
            var username = process.env.SAUCE_USERNAME
                , accessKey = process.env.SAUCE_ACCESS_KEY
                ;
            process.env.SELENIUM_REMOTE_URL = `https://${username}:${accessKey}@localhost:4445`;
        }

        driver = (new webdriver.Builder()).
            withCapabilities(webdriver.Capabilities.chrome()).
            build();

        if (!process.env.TRAVIS) {
            return new Promise((resolve, reject) => {
                s = server.createAndListen(port, resolve);
            });
        }
    });

    test.after(() => {
        driver.quit();
        if (s) {
            s.close();
        }
    });

    test.it('Should work', function () {
        driver.get(`http://localhost:${port}/`);
        return driver.findElement(webdriver.By.tagName('p'))
            .then(el => el.getText())
            .then(text => assert.equal(text, "Hi everybody!"))
            ;
    });
});<|endoftext|>


<commit_before><commit_msg>SF - clean up gulpfile<commit_after><|endoftext|>


<commit_before>import path from 'path';
import { describe, it, before, after } from 'mocha'; // eslint-disable-line import/no-extraneous-dependencies
import { expect } from 'chai'; // eslint-disable-line import/no-extraneous-dependencies
import sinon from 'sinon'; // eslint-disable-line import/no-extraneous-dependencies
import apn from 'apn';
import PN from '../../src';

const method = 'apn';
const regIds = [
    '43e798c31a282d129a34d84472bbdd7632562ff0732b58a85a27c5d9fdf59b69',
    '43e798c31a282d129a34d84472bbdd7632562ff0732b58a85a27c5d9fdf59b69',
    '43e798c31a282d129a34d84472bbdd7632562ff0732b58a85a27c5d9fdf59b69',
];
const data = {
    title: 'title',
    body: 'body',
    sound: 'mySound.aiff',
    custom: {
        sender: 'appfeel-test',
    },
};
const pn = new PN({
    apn: {
        cert: path.resolve('./test/send/cert.pem'),
        key: path.resolve('./test/send/key.pem'),
    },
});
const fErr = new Error('Forced error');
let sendMethod;

function sendOkMethod() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => {
        expect(_regIds).to.be.instanceOf(Array);
        _regIds.forEach(regId => expect(regIds).to.include(regId));
        expect(message).to.be.instanceOf(apn.Notification);
        expect(message).to.have.deep.property('aps.sound', data.sound);
        expect(message).to.have.deep.property('aps.alert.title', data.title);
        expect(message).to.have.deep.property('aps.alert.body', data.body);
        expect(message).to.have.deep.property('priority', 10);
        expect(message).to.have.deep.property('payload', data.custom);
        return Promise.resolve({
            sent: _regIds,
        });
    });
}

function sendFailureMethod1() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => Promise.resolve({
        failed: _regIds.map(regId => ({
            device: regId,
            response: fErr.message,
        })),
    }));
}
function sendFailureMethod2() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => Promise.resolve({
        failed: _regIds.map(regId => ({
            device: regId,
            response: {
                reason: fErr.message,
            },
        })),
    }));
}

function sendErrorMethod() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => Promise.resolve({
        failed: _regIds.map(regId => ({
            device: regId,
            error: fErr,
        })),
    }));
}

function sendThrowExceptionMethod() {
    return sinon.stub(apn.Provider.prototype, 'send', () => Promise.reject(fErr));
}

describe('push-notifications-apn', () => {
    describe('send push notifications successfully', () => {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(regIds.length);
                    expect(result.failure).to.equal(0);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sendOkMethod();
        });

        after(() => {
            sendMethod.restore();
        });

        it('all responses should be successful (callback)', (done) => {
            pn.send(regIds, data, (err, results) => test(err, results, done));
        });

        it('all responses should be successful (promise)', (done) => {
            pn.send(regIds, data)
                .then(results => test(null, results, done))
                .catch(done);
        });
    });

    describe('once notification has been sent', () => {
        before(() => {
            sendMethod = sendOkMethod();
            sinon.stub(apn.Provider.prototype, 'shutdown')
        });

        after(() => {
            sendMethod.restore();
            apn.Provider.prototype.shutdown.restore()
        });

        it('shuts down the provider instance', (done) => {
            pn.send(regIds, data, (err, results) => {
                sinon.assert.calledOnce(apn.Provider.prototype.shutdown)
                done()
            });
        });
    });

    describe('send push notifications successfully (no payload)', () => {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(regIds.length);
                    expect(result.failure).to.equal(0);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => {
                expect(_regIds).to.be.instanceOf(Array);
                _regIds.forEach(regId => expect(regIds).to.include(regId));
                expect(message).to.be.instanceOf(apn.Notification);
                expect(message).to.have.deep.property('aps.sound', 'ping.aiff');
                expect(message).to.have.deep.property('aps.alert.title', data.title);
                expect(message).to.have.deep.property('aps.alert.body', data.body);
                expect(message).to.have.deep.property('payload').deep.equal({});
                return Promise.resolve({
                    sent: _regIds,
                });
            });
        });

        after(() => {
            sendMethod.restore();
        });

        it('all responses should be successful (callback no payload, no sound)', (done) => {
            const newData = Object.assign({}, data);
            delete newData.custom;
            delete newData.sound;
            pn.send(regIds, newData, (err, results) => test(err, results, done));
        });
    });

    describe('send push notifications with normal priority', () => {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(regIds.length);
                    expect(result.failure).to.equal(0);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => {
                expect(_regIds).to.be.instanceOf(Array);
                _regIds.forEach(regId => expect(regIds).to.include(regId));
                expect(message).to.be.instanceOf(apn.Notification);
                expect(message).to.have.deep.property('priority', 5);
                return Promise.resolve({
                    sent: _regIds,
                });
            });
        });

        after(() => {
            sendMethod.restore();
        });

        it('all responses should be successful (callback no payload, no sound)', (done) => {
            const normalPrioData = Object.assign({}, data);
            normalPrioData.priority = 'normal';
            pn.send(regIds, normalPrioData, (err, results) => test(err, results, done));
        });
    });

    {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(0);
                    expect(result.failure).to.equal(regIds.length);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                        expect(message).to.have.property('error');
                        expect(message.error).to.be.instanceOf(Error);
                        expect(message.error.message).to.equal(fErr.message);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        describe('send push notifications failure (response message)', () => {
            before(() => {
                sendMethod = sendFailureMethod1();
            });

            after(() => {
                sendMethod.restore();
            });

            it('all responses should be failed with response message (callback)', (done) => {
                pn.send(regIds, data, (err, results) => test(err, results, done));
            });

            it('all responses should be failed with response message (promise)', (done) => {
                pn.send(regIds, data)
                    .then(results => test(null, results, done))
                    .catch(done);
            });
        });

        describe('send push notifications failure (response reason)', () => {
            before(() => {
                sendMethod = sendFailureMethod2();
            });

            after(() => {
                sendMethod.restore();
            });

            it('all responses should be failed with response reason (callback)', (done) => {
                pn.send(regIds, data, (err, results) => test(err, results, done));
            });

            it('all responses should be failed with response reason (promise)', (done) => {
                pn.send(regIds, data)
                    .then(results => test(null, results, done))
                    .catch(done);
            });
        });

        describe('send push notifications error', () => {
            before(() => {
                sendMethod = sendErrorMethod();
            });

            after(() => {
                sendMethod.restore();
            });

            it('the error should be reported (callback)', (done) => {
                pn.send(regIds, data, (err, results) => test(err, results, done));
            });

            it('the error should be reported (promise)', (done) => {
                pn.send(regIds, data)
                    .then(results => test(null, results, done))
                    .catch(err => test(err, undefined, done));
            });
        });
    }

    describe('send push notifications throw exception', () => {
        const test = (err, results, done) => {
            try {
                expect(results).to.equal(undefined);
                expect(err).to.be.instanceOf(Error);
                expect(err.message).to.equal(fErr.message);
                done();
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sendThrowExceptionMethod();
        });

        after(() => {
            sendMethod.restore();
        });

        it('the exception should be catched (callback)', (done) => {
            pn.send(regIds, data, (err, results) => test(err, results, done))
                .catch(() => { }); // This is to avoid UnhandledPromiseRejectionWarning
        });

        it('the exception should be catched (promise)', (done) => {
            pn.send(regIds, data)
                .then(results => test(null, results, done))
                .catch(err => test(err, undefined, done));
        });
    });
});
<commit_msg>use expect() in sendAPN provider shutdown test<commit_after>import path from 'path';
import { describe, it, before, after } from 'mocha'; // eslint-disable-line import/no-extraneous-dependencies
import { expect } from 'chai'; // eslint-disable-line import/no-extraneous-dependencies
import sinon from 'sinon'; // eslint-disable-line import/no-extraneous-dependencies
import apn from 'apn';
import PN from '../../src';

const method = 'apn';
const regIds = [
    '43e798c31a282d129a34d84472bbdd7632562ff0732b58a85a27c5d9fdf59b69',
    '43e798c31a282d129a34d84472bbdd7632562ff0732b58a85a27c5d9fdf59b69',
    '43e798c31a282d129a34d84472bbdd7632562ff0732b58a85a27c5d9fdf59b69',
];
const data = {
    title: 'title',
    body: 'body',
    sound: 'mySound.aiff',
    custom: {
        sender: 'appfeel-test',
    },
};
const pn = new PN({
    apn: {
        cert: path.resolve('./test/send/cert.pem'),
        key: path.resolve('./test/send/key.pem'),
    },
});
const fErr = new Error('Forced error');
let sendMethod;

function sendOkMethod() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => {
        expect(_regIds).to.be.instanceOf(Array);
        _regIds.forEach(regId => expect(regIds).to.include(regId));
        expect(message).to.be.instanceOf(apn.Notification);
        expect(message).to.have.deep.property('aps.sound', data.sound);
        expect(message).to.have.deep.property('aps.alert.title', data.title);
        expect(message).to.have.deep.property('aps.alert.body', data.body);
        expect(message).to.have.deep.property('priority', 10);
        expect(message).to.have.deep.property('payload', data.custom);
        return Promise.resolve({
            sent: _regIds,
        });
    });
}

function sendFailureMethod1() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => Promise.resolve({
        failed: _regIds.map(regId => ({
            device: regId,
            response: fErr.message,
        })),
    }));
}
function sendFailureMethod2() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => Promise.resolve({
        failed: _regIds.map(regId => ({
            device: regId,
            response: {
                reason: fErr.message,
            },
        })),
    }));
}

function sendErrorMethod() {
    return sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => Promise.resolve({
        failed: _regIds.map(regId => ({
            device: regId,
            error: fErr,
        })),
    }));
}

function sendThrowExceptionMethod() {
    return sinon.stub(apn.Provider.prototype, 'send', () => Promise.reject(fErr));
}

describe('push-notifications-apn', () => {
    describe('send push notifications successfully', () => {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(regIds.length);
                    expect(result.failure).to.equal(0);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sendOkMethod();
        });

        after(() => {
            sendMethod.restore();
        });

        it('all responses should be successful (callback)', (done) => {
            pn.send(regIds, data, (err, results) => test(err, results, done));
        });

        it('all responses should be successful (promise)', (done) => {
            pn.send(regIds, data)
                .then(results => test(null, results, done))
                .catch(done);
        });
    });

    describe('once notification has been sent', () => {
        before(() => {
            sendMethod = sendOkMethod();
            sinon.stub(apn.Provider.prototype, 'shutdown');
        });

        after(() => {
            sendMethod.restore();
            apn.Provider.prototype.shutdown.restore();
        });

        it('shuts down the provider instance', (done) => {
            pn.send(regIds, data, () => {
                expect(apn.Provider.prototype.shutdown).to.have.been.calledOnce;
                done()
            });
        });
    });

    describe('send push notifications successfully (no payload)', () => {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(regIds.length);
                    expect(result.failure).to.equal(0);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => {
                expect(_regIds).to.be.instanceOf(Array);
                _regIds.forEach(regId => expect(regIds).to.include(regId));
                expect(message).to.be.instanceOf(apn.Notification);
                expect(message).to.have.deep.property('aps.sound', 'ping.aiff');
                expect(message).to.have.deep.property('aps.alert.title', data.title);
                expect(message).to.have.deep.property('aps.alert.body', data.body);
                expect(message).to.have.deep.property('payload').deep.equal({});
                return Promise.resolve({
                    sent: _regIds,
                });
            });
        });

        after(() => {
            sendMethod.restore();
        });

        it('all responses should be successful (callback no payload, no sound)', (done) => {
            const newData = Object.assign({}, data);
            delete newData.custom;
            delete newData.sound;
            pn.send(regIds, newData, (err, results) => test(err, results, done));
        });
    });

    describe('send push notifications with normal priority', () => {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(regIds.length);
                    expect(result.failure).to.equal(0);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sinon.stub(apn.Provider.prototype, 'send', (message, _regIds) => {
                expect(_regIds).to.be.instanceOf(Array);
                _regIds.forEach(regId => expect(regIds).to.include(regId));
                expect(message).to.be.instanceOf(apn.Notification);
                expect(message).to.have.deep.property('priority', 5);
                return Promise.resolve({
                    sent: _regIds,
                });
            });
        });

        after(() => {
            sendMethod.restore();
        });

        it('all responses should be successful (callback no payload, no sound)', (done) => {
            const normalPrioData = Object.assign({}, data);
            normalPrioData.priority = 'normal';
            pn.send(regIds, normalPrioData, (err, results) => test(err, results, done));
        });
    });

    {
        const test = (err, results, done) => {
            try {
                expect(err).to.equal(null);
                results.forEach((result) => {
                    expect(result.method).to.equal(method);
                    expect(result.success).to.equal(0);
                    expect(result.failure).to.equal(regIds.length);
                    expect(result.message.length).to.equal(regIds.length);
                    result.message.forEach((message) => {
                        expect(message).to.have.property('regId');
                        expect(regIds).to.include(message.regId);
                        expect(message).to.have.property('error');
                        expect(message.error).to.be.instanceOf(Error);
                        expect(message.error.message).to.equal(fErr.message);
                    });
                });
                done(err);
            } catch (e) {
                done(err || e);
            }
        };

        describe('send push notifications failure (response message)', () => {
            before(() => {
                sendMethod = sendFailureMethod1();
            });

            after(() => {
                sendMethod.restore();
            });

            it('all responses should be failed with response message (callback)', (done) => {
                pn.send(regIds, data, (err, results) => test(err, results, done));
            });

            it('all responses should be failed with response message (promise)', (done) => {
                pn.send(regIds, data)
                    .then(results => test(null, results, done))
                    .catch(done);
            });
        });

        describe('send push notifications failure (response reason)', () => {
            before(() => {
                sendMethod = sendFailureMethod2();
            });

            after(() => {
                sendMethod.restore();
            });

            it('all responses should be failed with response reason (callback)', (done) => {
                pn.send(regIds, data, (err, results) => test(err, results, done));
            });

            it('all responses should be failed with response reason (promise)', (done) => {
                pn.send(regIds, data)
                    .then(results => test(null, results, done))
                    .catch(done);
            });
        });

        describe('send push notifications error', () => {
            before(() => {
                sendMethod = sendErrorMethod();
            });

            after(() => {
                sendMethod.restore();
            });

            it('the error should be reported (callback)', (done) => {
                pn.send(regIds, data, (err, results) => test(err, results, done));
            });

            it('the error should be reported (promise)', (done) => {
                pn.send(regIds, data)
                    .then(results => test(null, results, done))
                    .catch(err => test(err, undefined, done));
            });
        });
    }

    describe('send push notifications throw exception', () => {
        const test = (err, results, done) => {
            try {
                expect(results).to.equal(undefined);
                expect(err).to.be.instanceOf(Error);
                expect(err.message).to.equal(fErr.message);
                done();
            } catch (e) {
                done(err || e);
            }
        };

        before(() => {
            sendMethod = sendThrowExceptionMethod();
        });

        after(() => {
            sendMethod.restore();
        });

        it('the exception should be catched (callback)', (done) => {
            pn.send(regIds, data, (err, results) => test(err, results, done))
                .catch(() => { }); // This is to avoid UnhandledPromiseRejectionWarning
        });

        it('the exception should be catched (promise)', (done) => {
            pn.send(regIds, data)
                .then(results => test(null, results, done))
                .catch(err => test(err, undefined, done));
        });
    });
});
<|endoftext|>