<commit_before>var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var fs = require('fs');
var del = require('del');
var download = require('download');
var downloadStatus = require('download-status');
var walk = require('walk');
var path = require('path');

module.exports = class extends Generator {
  prompting() {
      this.log(yosay(
        '(test gulp insert) With great power comes great ' + chalk.red('theme generator!')
      ));

      return this.prompt(
        [
          {
            type: 'input',
            name: 'proxy',
            message: 'Localhost address',
            default: 'localhost'
          },
					{
						type: 'input',
						name: 'domain',
						message: 'If you want to add a domain site',
						default: ''
				},
          {
            type: 'input',
            name: 'themename',
            message: 'Theme Name',
            default: 'Theme Name'
          },
          {
            type: 'input',
            name: 'themeSlug',
            message: 'Theme Slug',
            default: 'Theme Slug'
          },
          {
            type: 'input',
            name: 'themeuri',
            message: 'Theme URI',
            default: 'https://thatmuch.fr'
          },
          {
            type: 'input',
            name: 'author',
            message: 'Author',
            default: 'ThatMuch'
          },
          {
            type: 'input',
            name: 'authoruri',
            message: 'Author URI',
            default: 'https://thatmuch.fr'
          },
          {
            type: 'input',
            name: 'authoremail',
            message: 'Author Email',
            default: 'social@thatmuch.fr'
          },
          {
            type: 'input',
            name: 'description',
            message: 'Description',
            default: 'Description'
          },
          {
            type: 'input',
            name: 'bugreport',
            message: 'Bug Report',
            default: 'https://example.com/bugreport/'
          },
          {
            type: 'confirm',
            name: 'gitignore',
            message: 'Would you like to add a ' + chalk.white('.gitignore') + ' file?',
            default: true
          },
          {
            type: 'confirm',
            name: 'editorconfig',
            message: 'Would you like to add a ' + chalk.white('.editorconfig') + ' file?',
            default: true
          },
					{
						type: 'confirm',
						name: 'stylelintrc',
						message: 'Would you like to add a ' + chalk.white('.stylelintrc') + ' file?',
						default: true
				},
          {
            type: 'confirm',
            name: 'gulpsetup',
            message: 'Would you like to setup a Gulp configuration ready to use?',
            default: true
          }
      ]
    ).then((answers) => {
              this.proxy = answers.proxy;
              this.domain = answers.domain;
              this.themeName = answers.themeName;
              this.themeSlug = answers.themeSlug;
              this.themeURI = answers.themeURI;
              this.author = answers.author;
              this.authorURI = answers.authorURI;
              this.authorEmail = answers.authorEmail;
              this.description = answers.description;
              this.bugreport = answers.bugreport;
              this.gitignore = answers.gitignore;
              this.stylelintrc = answers.stylelintrc;
              this.gulpsetup = answers.gulpsetup;
      });
  }

  writing() {
// Download Stanlee theme
    var done = this.async();
		var dir = this.destinationRoot();
    var unusedFiles = ['.travis.yml', 'codesniffer.ruleset.xml', 'README.md'];

      this.log(chalk.yellow('\nLet\'s grab the latest version of Stanlee...'));

        Promise.all([
          'github.com/ThatMuch/stanLee-wordpress/archive/master.tar.gz'
        ].map(x => download(x, '.', {
    extract: true,
    strip: 1
  }))).then(() => {
    this.log(chalk.blue('End download!'));
  }).then(() => {
    // Delete unused files
    this.log(chalk.yellow('\nDeleting some unused files...'));

    unusedFiles = _.map(unusedFiles, function (file) {
      return dir + '/' + file;
    });

    del(unusedFiles).catch(function (error) {
        done(error);
      })
      .then(paths => {
        this.log(chalk.cyan(paths.join('\n')));
        done();
      });
    this.log(chalk.blue('Done!'));
  }).then(() => {
    // Parsing theme files
    var _this = this;
    var walker;
    var options;
    options = {
      followLinks: false
    };
    this.log(chalk.yellow('\nParsing theme files...'));

    walker = walk.walk('.');

    this.log(chalk.white('Please wait...'));

    walker.on("file", function (root, fileStats, next) {
      var filePath = root + '/' + fileStats.name;

      if (path.extname(fileStats.name) == '.php' || path.extname(fileStats.name) == '.scss') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/'_s'/g, "'" + _this.themeSlug + "'");
          result = data.replace(/'_a'/g, "'" + _this.author + "'");
          result = result.replace(/_s_/g, _this.themeSlug + "_");
          result = result.replace(/ _s/g, ' ' + _this.themeName);
          result = result.replace(/ _a/g, ' ' + _this.author);
          result = result.replace(/_s-/g, _this.themeSlug + '-');

          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          next();
        });
      } else if (path.extname(fileStats.name) == '.css' || fileStats.name == 'style.scss' || fileStats.name == 'woocommerce.scss' || fileStats.name == 'theme.scss') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/(Theme Name: )(.+)/g, '$1' + _this.themeName);
          result = result.replace(/(Theme URI: )(.+)/g, '$1' + _this.themeURI);
          result = result.replace(/(Author: )(.+)/g, '$1' + _this.author);
          result = result.replace(/(Author URI: )(.+)/g, '$1' + _this.authorURI);
          result = result.replace(/(Description: )(.+)/g, '$1' + _this.description);
          result = result.replace(/(Text Domain: )(.+)/g, '$1' + _this.themeSlug);
          result = result.replace(/_s is based on Underscores/g, _this.themeName + ' is based on Underscores');
          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          next();
        });
      } else if (fileStats.name === 'readme.txt') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/=== _s ===/g, '=== ' + _this.themeName + ' ===');
          result = result.replace(/A starter theme called _s, or underscores./g, _this.description);
          result = result.replace(/(== Description ==\n\n)(.+)/g, '$1' + 'Long description here');
          result = result.replace(/== Frequently Asked Questions ==[\s\S]*?== Credits ==/g, '== Credits ==');

          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          next();
        });
      } else if (fileStats.name === '_s.pot') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/Copyright (C) 2018 ThatMuch/g, 'Copyright (C) 2018 ' + _this.author);
          result = result.replace(/Project-Id-Version: _s/g, 'Project-Id-Version: ' + _this.themeName);
          result = result.replace(/Report-Msgid-Bugs-To: https:\/\/wordpress.org\/tags\/_s/g, 'Report-Msgid-Bugs-To: ' + _this.bugreport);
          result = result.replace(/Language-Team: LANGUAGE <LL@li\.org>/g, 'Language-Team: ' + _this.author + '<' + _this.authorEmail + '>');
          result = result.replace(/@ _s/g, '@ ' + _this.themeSlug);

          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          fs.rename(filePath, './languages/' + _this.themeSlug + '.pot');

          next();
        });
      } else {
        next();
      }
    });

    walker.on("error", function (root, nodeStatsArray, next) {
      done(error);
      next();
    });

    walker.on("end", function () {
      done();
    });

    this.log(chalk.blue('Parsing done!'));
  });

  this.log(chalk.yellow('\nCopying configuration files...'));
		if (this.gitignore) {
			this.fs.copy(
				this.templatePath('_gitignore'),
				this.destinationPath('.gitignore')
			);
		}
		if (this.editorconfig) {
			this.fs.copy(
				this.templatePath('_editorconfig'),
				this.destinationPath('.editorconfig')
			);
		}

		if (this.stylelintrc) {
			this.fs.copy(
				this.templatePath('_stylelintrc'),
				this.destinationPath('.stylelintrc')
			);
		}
		if (this.gulpsetup) {
			this.fs.copyTpl(
				this.templatePath('_package.json'),
				this.destinationPath('package.json'), {
					package_name: this.themeSlug,
					package_description: this.description,
					package_author: this.author,
					proxy_address: this.proxy,
					proxy_domain: this.domain,
					theme_name: this.themeName,
					theme_domain: this.themeSlug,
					theme_bugreport: this.bugreport,
					author_uri: this.authorURI,
					author_email: this.authorEmail
				}
			);

			this.fs.copyTpl(
				this.templatePath('_gulpfile.js'),
				this.destinationPath('gulpfile.js'), {
          theme_domain: this.themeSlug,
          proxy_address: this.proxy,
          package_name: this.themeSlug,
          theme_bugreport: this.bugreport,
          author_email: this.authorEmail,
          author: this.author
				}
			);
  }
  this.log(chalk.blue('Done!'));
}

  install() {
      if (this.gulpsetup) {
        this.log(chalk.yellow('\nInstalling required packages...'));

        this.npmInstall(['gulp'], { 'saveDev': true });
        this.npmInstall(['gulp-concat'], { 'saveDev': true });
        this.npmInstall(['gulp-rename'], { 'saveDev': true });
        this.npmInstall(['gulp-order'], { 'saveDev': true });
        this.npmInstall(['browser-sync'], { 'saveDev': true });
        this.npmInstall(['gulp-sass'], { 'saveDev': true });
        this.npmInstall(['gulp-clean-css'], { 'saveDev': true });
        this.npmInstall(['gulp-autoprefixer'], { 'saveDev': true });
        this.npmInstall(['gulp-csscomb'], { 'saveDev': true });
        this.npmInstall(['gulp-wp-pot'], { 'saveDev': true });
        this.npmInstall(['gulp-rev'], { 'saveDev': true });
        this.npmInstall(['gulp-uglify'], { 'saveDev': true });
        this.npmInstall(['gulp-notify'], { 'saveDev': true });
        this.npmInstall(['gulp-plumber'], { 'saveDev': true });
        this.npmInstall(['gulp-watch'], { 'saveDev': true });
        this.npmInstall(['del'], { 'saveDev': true });
        this.npmInstall(['gulp-zip'], { 'saveDev': true });
        this.npmInstall(['run-sequence'], { 'saveDev': true });

        this.npmInstall(['animate.css'], { 'saveDev': false });
        this.npmInstall(['bootstrap'], { 'saveDev': false });
        this.npmInstall(['hamburgers'], { 'saveDev': false });
        this.npmInstall(['normalize.css'], { 'saveDev': false });
        this.npmInstall(['wowjs'], { 'saveDev': false });
      }

  }

  end() {
      this.log(chalk.green('\nAll Done!!\n------------------------\n'));
      if (this.gulpsetup) {
        this.log('\nRun ' + chalk.green('gulp') + ' to start the development and ' + chalk.green('gulp build') + ' to create a zip file in ' + chalk.white('dist/' + this.themeSlug + '.zip') + ' ready for production.');
      }

  }
};
<commit_msg>Force Gulp 3.9.1<commit_after>var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var fs = require('fs');
var del = require('del');
var download = require('download');
var downloadStatus = require('download-status');
var walk = require('walk');
var path = require('path');

module.exports = class extends Generator {
  prompting() {
      this.log(yosay(
        '(test gulp insert) With great power comes great ' + chalk.red('theme generator!')
      ));

      return this.prompt(
        [
          {
            type: 'input',
            name: 'proxy',
            message: 'Localhost address',
            default: 'localhost'
          },
					{
						type: 'input',
						name: 'domain',
						message: 'If you want to add a domain site',
						default: ''
				},
          {
            type: 'input',
            name: 'themename',
            message: 'Theme Name',
            default: 'Theme Name'
          },
          {
            type: 'input',
            name: 'themeSlug',
            message: 'Theme Slug',
            default: 'Theme Slug'
          },
          {
            type: 'input',
            name: 'themeuri',
            message: 'Theme URI',
            default: 'https://thatmuch.fr'
          },
          {
            type: 'input',
            name: 'author',
            message: 'Author',
            default: 'ThatMuch'
          },
          {
            type: 'input',
            name: 'authoruri',
            message: 'Author URI',
            default: 'https://thatmuch.fr'
          },
          {
            type: 'input',
            name: 'authoremail',
            message: 'Author Email',
            default: 'social@thatmuch.fr'
          },
          {
            type: 'input',
            name: 'description',
            message: 'Description',
            default: 'Description'
          },
          {
            type: 'input',
            name: 'bugreport',
            message: 'Bug Report',
            default: 'https://example.com/bugreport/'
          },
          {
            type: 'confirm',
            name: 'gitignore',
            message: 'Would you like to add a ' + chalk.white('.gitignore') + ' file?',
            default: true
          },
          {
            type: 'confirm',
            name: 'editorconfig',
            message: 'Would you like to add a ' + chalk.white('.editorconfig') + ' file?',
            default: true
          },
					{
						type: 'confirm',
						name: 'stylelintrc',
						message: 'Would you like to add a ' + chalk.white('.stylelintrc') + ' file?',
						default: true
				},
          {
            type: 'confirm',
            name: 'gulpsetup',
            message: 'Would you like to setup a Gulp configuration ready to use?',
            default: true
          }
      ]
    ).then((answers) => {
              this.proxy = answers.proxy;
              this.domain = answers.domain;
              this.themeName = answers.themeName;
              this.themeSlug = answers.themeSlug;
              this.themeURI = answers.themeURI;
              this.author = answers.author;
              this.authorURI = answers.authorURI;
              this.authorEmail = answers.authorEmail;
              this.description = answers.description;
              this.bugreport = answers.bugreport;
              this.gitignore = answers.gitignore;
              this.stylelintrc = answers.stylelintrc;
              this.gulpsetup = answers.gulpsetup;
      });
  }

  writing() {
// Download Stanlee theme
    var done = this.async();
		var dir = this.destinationRoot();
    var unusedFiles = ['.travis.yml', 'codesniffer.ruleset.xml', 'README.md'];

      this.log(chalk.yellow('\nLet\'s grab the latest version of Stanlee...'));

        Promise.all([
          'github.com/ThatMuch/stanLee-wordpress/archive/master.tar.gz'
        ].map(x => download(x, '.', {
    extract: true,
    strip: 1
  }))).then(() => {
    this.log(chalk.blue('End download!'));
  }).then(() => {
    // Delete unused files
    this.log(chalk.yellow('\nDeleting some unused files...'));

    unusedFiles = _.map(unusedFiles, function (file) {
      return dir + '/' + file;
    });

    del(unusedFiles).catch(function (error) {
        done(error);
      })
      .then(paths => {
        this.log(chalk.cyan(paths.join('\n')));
        done();
      });
    this.log(chalk.blue('Done!'));
  }).then(() => {
    // Parsing theme files
    var _this = this;
    var walker;
    var options;
    options = {
      followLinks: false
    };
    this.log(chalk.yellow('\nParsing theme files...'));

    walker = walk.walk('.');

    this.log(chalk.white('Please wait...'));

    walker.on("file", function (root, fileStats, next) {
      var filePath = root + '/' + fileStats.name;

      if (path.extname(fileStats.name) == '.php' || path.extname(fileStats.name) == '.scss') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/'_s'/g, "'" + _this.themeSlug + "'");
          result = data.replace(/'_a'/g, "'" + _this.author + "'");
          result = result.replace(/_s_/g, _this.themeSlug + "_");
          result = result.replace(/ _s/g, ' ' + _this.themeName);
          result = result.replace(/ _a/g, ' ' + _this.author);
          result = result.replace(/_s-/g, _this.themeSlug + '-');

          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          next();
        });
      } else if (path.extname(fileStats.name) == '.css' || fileStats.name == 'style.scss' || fileStats.name == 'woocommerce.scss' || fileStats.name == 'theme.scss') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/(Theme Name: )(.+)/g, '$1' + _this.themeName);
          result = result.replace(/(Theme URI: )(.+)/g, '$1' + _this.themeURI);
          result = result.replace(/(Author: )(.+)/g, '$1' + _this.author);
          result = result.replace(/(Author URI: )(.+)/g, '$1' + _this.authorURI);
          result = result.replace(/(Description: )(.+)/g, '$1' + _this.description);
          result = result.replace(/(Text Domain: )(.+)/g, '$1' + _this.themeSlug);
          result = result.replace(/_s is based on Underscores/g, _this.themeName + ' is based on Underscores');
          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          next();
        });
      } else if (fileStats.name === 'readme.txt') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/=== _s ===/g, '=== ' + _this.themeName + ' ===');
          result = result.replace(/A starter theme called _s, or underscores./g, _this.description);
          result = result.replace(/(== Description ==\n\n)(.+)/g, '$1' + 'Long description here');
          result = result.replace(/== Frequently Asked Questions ==[\s\S]*?== Credits ==/g, '== Credits ==');

          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          next();
        });
      } else if (fileStats.name === '_s.pot') {
        fs.readFile(filePath, 'utf8', function (err, data) {
          if (err) {
            done(error);
          }

          var result;

          result = data.replace(/Copyright (C) 2018 ThatMuch/g, 'Copyright (C) 2018 ' + _this.author);
          result = result.replace(/Project-Id-Version: _s/g, 'Project-Id-Version: ' + _this.themeName);
          result = result.replace(/Report-Msgid-Bugs-To: https:\/\/wordpress.org\/tags\/_s/g, 'Report-Msgid-Bugs-To: ' + _this.bugreport);
          result = result.replace(/Language-Team: LANGUAGE <LL@li\.org>/g, 'Language-Team: ' + _this.author + '<' + _this.authorEmail + '>');
          result = result.replace(/@ _s/g, '@ ' + _this.themeSlug);

          fs.writeFile(filePath, result, 'utf8', function (err) {
            if (err) {
              done(error);
            }
          });

          fs.rename(filePath, './languages/' + _this.themeSlug + '.pot');

          next();
        });
      } else {
        next();
      }
    });

    walker.on("error", function (root, nodeStatsArray, next) {
      done(error);
      next();
    });

    walker.on("end", function () {
      done();
    });

    this.log(chalk.blue('Parsing done!'));
  });

  this.log(chalk.yellow('\nCopying configuration files...'));
		if (this.gitignore) {
			this.fs.copy(
				this.templatePath('_gitignore'),
				this.destinationPath('.gitignore')
			);
		}
		if (this.editorconfig) {
			this.fs.copy(
				this.templatePath('_editorconfig'),
				this.destinationPath('.editorconfig')
			);
		}

		if (this.stylelintrc) {
			this.fs.copy(
				this.templatePath('_stylelintrc'),
				this.destinationPath('.stylelintrc')
			);
		}
		if (this.gulpsetup) {
			this.fs.copyTpl(
				this.templatePath('_package.json'),
				this.destinationPath('package.json'), {
					package_name: this.themeSlug,
					package_description: this.description,
					package_author: this.author,
					proxy_address: this.proxy,
					proxy_domain: this.domain,
					theme_name: this.themeName,
					theme_domain: this.themeSlug,
					theme_bugreport: this.bugreport,
					author_uri: this.authorURI,
					author_email: this.authorEmail
				}
			);

			this.fs.copyTpl(
				this.templatePath('_gulpfile.js'),
				this.destinationPath('gulpfile.js'), {
          theme_domain: this.themeSlug,
          proxy_address: this.proxy,
          package_name: this.themeSlug,
          theme_bugreport: this.bugreport,
          author_email: this.authorEmail,
          author: this.author
				}
			);
  }
  this.log(chalk.blue('Done!'));
}
writing() {
  const pkgJson = {
    devDependencies: {
      gulp: '^3.9.1'
    }
  };

  // Extend or create package.json file in destination path
  this.fs.extendJSON(this.destinationPath('package.json'), pkgJson);
}

  install() {
      if (this.gulpsetup) {
        this.log(chalk.yellow('\nInstalling required packages...'));

        this.npmInstall(['gulp'], { 'saveDev': true });
        this.npmInstall(['gulp-concat'], { 'saveDev': true });
        this.npmInstall(['gulp-rename'], { 'saveDev': true });
        this.npmInstall(['gulp-order'], { 'saveDev': true });
        this.npmInstall(['browser-sync'], { 'saveDev': true });
        this.npmInstall(['gulp-sass'], { 'saveDev': true });
        this.npmInstall(['gulp-clean-css'], { 'saveDev': true });
        this.npmInstall(['gulp-autoprefixer'], { 'saveDev': true });
        this.npmInstall(['gulp-csscomb'], { 'saveDev': true });
        this.npmInstall(['gulp-wp-pot'], { 'saveDev': true });
        this.npmInstall(['gulp-rev'], { 'saveDev': true });
        this.npmInstall(['gulp-uglify'], { 'saveDev': true });
        this.npmInstall(['gulp-notify'], { 'saveDev': true });
        this.npmInstall(['gulp-plumber'], { 'saveDev': true });
        this.npmInstall(['gulp-watch'], { 'saveDev': true });
        this.npmInstall(['del'], { 'saveDev': true });
        this.npmInstall(['gulp-zip'], { 'saveDev': true });
        this.npmInstall(['run-sequence'], { 'saveDev': true });

        this.npmInstall(['animate.css'], { 'saveDev': false });
        this.npmInstall(['bootstrap'], { 'saveDev': false });
        this.npmInstall(['hamburgers'], { 'saveDev': false });
        this.npmInstall(['normalize.css'], { 'saveDev': false });
        this.npmInstall(['wowjs'], { 'saveDev': false });
      }

  }

  end() {
      this.log(chalk.green('\nAll Done!!\n------------------------\n'));
      if (this.gulpsetup) {
        this.log('\nRun ' + chalk.green('gulp') + ' to start the development and ' + chalk.green('gulp build') + ' to create a zip file in ' + chalk.white('dist/' + this.themeSlug + '.zip') + ' ready for production.');
      }

  }
};
<|endoftext|>


<commit_before>var app = require('express')(),
    chalk = require('chalk'),
    express = require('express'),
    redis = require('redis'),
    session = require('express-session'),
    redisStore = require('connect-redis')(session),
    redisClient = redis.createClient(),
    path = require('path'),
    socketHandler = require(path.join(__dirname, '/sockets')),
    favicon = require('serve-favicon');

var userRoutes = require(path.join(__dirname, '..', 'routes', 'userRoutes'));

app.set('views', path.join(__dirname, '..', 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, '..', 'public')));
app.use(favicon(path.join(__dirname, '..', 'public', 'favicon.png')))

// ========== Session ==========

var newSession = require('express-session')({
  secret: 'iHopeDubstepNeverEnds',
  store: new redisStore({ host: 'localhost', port: 6376, client: redisClient, ttl: 260}),
  resave: false,
  saveUninitialized: true
});

app.use(newSession);

app.use(function (req, res, next) {
  console.log(chalk.yellow(`      === session ID: ${req.sessionID}`));
  if (req.session.username) {
    console.log(`user ${req.session.username} is logged in`);
  } else {
    console.log(`user isn't logged in`);
  }
  next();
})

// ========== Routing ==========

app.get('/', function (req, res) {
  req.session.username ? res.render('index', { title: 'Unity Web Player | Earth Invasion' }) : res.redirect('/login');
});

app.use('/', userRoutes);

app.use('/usernameReq', function (req, res) {
  res.send(req.session.username);
});

// ========== Errors ==========

app
  .use(function (req, res, next) {
    res.status(404).send('This page does not exist');
  })
  .use(function (err, req, res, next) {
    console.log('error', err.stack);
    res.status(500).send('An error has occurred');
  });

// ========== Server ==========

function startNodeListener() {
  var port = process.env.PORT || 3000;
  var server = app.listen(port, function () {
    var port = server.address().port;
    var mode = app.get('env');

    console.log(chalk.blue(`\n=== === === `) + chalk.cyan(`Server listening on port ${port} in ${mode} mode...`) + chalk.blue(` === === ===\n`));
    // ========== Sockets ==========
    socketHandler(newSession, server);
  })
}

startNodeListener();
<commit_msg>redis ready for heroku deployment<commit_after>var app = require('express')(),
    chalk = require('chalk'),
    express = require('express'),
    redis = require('redis'),
    session = require('express-session'),
    redisStore = require('connect-redis')(session),
    redisClient = redis.createClient(),
    path = require('path'),
    socketHandler = require(path.join(__dirname, '/sockets')),
    favicon = require('serve-favicon');

var userRoutes = require(path.join(__dirname, '..', 'routes', 'userRoutes'));

app.set('views', path.join(__dirname, '..', 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, '..', 'public')));
app.use(favicon(path.join(__dirname, '..', 'public', 'favicon.png')))

// ========== Session ==========

var newSession = require('express-session')({
  secret: 'iHopeDubstepNeverEnds',
  store: new redisStore({ host: process.env.REDIS_URL ? 'ec2-54-235-152-160.compute-1.amazonaws.com': 'localhost',
                          port: process.env.REDIS_URL ? 17469: 6376,
                          client: redisClient,
                          ttl: 260
                        }),
  resave: false,
  saveUninitialized: true
});

app.use(newSession);

app.use(function (req, res, next) {
  console.log(chalk.yellow(`      === session ID: ${req.sessionID}`));
  if (req.session.username) {
    console.log(`user ${req.session.username} is logged in`);
  } else {
    console.log(`user isn't logged in`);
  }
  next();
})

// ========== Routing ==========

app.get('/', function (req, res) {
  req.session.username ? res.render('index', { title: 'Unity Web Player | Earth Invasion' }) : res.redirect('/login');
});

app.use('/', userRoutes);

app.use('/usernameReq', function (req, res) {
  res.send(req.session.username);
});

// ========== Errors ==========

app
  .use(function (req, res, next) {
    res.status(404).send('This page does not exist');
  })
  .use(function (err, req, res, next) {
    console.log('error', err.stack);
    res.status(500).send('An error has occurred');
  });

// ========== Server ==========

function startNodeListener() {
  var port = process.env.PORT || 3000;
  var server = app.listen(port, function () {
    var port = server.address().port;
    var mode = app.get('env');

    console.log(chalk.blue(`\n=== === === `) + chalk.cyan(`Server listening on port ${port} in ${mode} mode...`) + chalk.blue(` === === ===\n`));
    // ========== Sockets ==========
    socketHandler(newSession, server);
  })
}

startNodeListener();
<|endoftext|>


<commit_before>/**
 * XadillaX created at 2016-04-06 23:43:51 With ♥
 *
 * Copyright (c) 2016 Souche.com, all rights
 * reserved.
 */
"use strict";

const EventEmitter = require("events").EventEmitter;

const async = require("async");
const Scarlet = require("scarlet-task");
const spidex = require("spidex");

const ConfigSchema = require("./config_schema");
const Record = require("./record");

const BASE_URI = "https://dnsapi.cn";

/** The DNSPod dynamic domain class. */
class DDNS extends EventEmitter {
    /**
     * Create a DDNS object.
     * @param {ConfigSchema} cfg the config schema object
     */
    constructor(cfg) {
        super();

        if(!(cfg instanceof ConfigSchema) || !cfg.check()) {
            throw new Error("Broken config schema.");
        }

        /** @member {ConfigSchema} - the config schema object. */
        this.cfg = cfg;
        /** @member {String} - the token string. */
        this.token = cfg.token;
        /** @member {String|NULL} - the domain id. */
        this.domainId = null;
        /** @member {String[]} - the subdomains to be run. */
        this.subdomains = cfg.subdomains;
        /** @member {Function} - the ip getter function. */
        this.ipGetter = cfg.ipGetter;

        /** @member {Boolean} - whether this DDNS is running or not. */
        this.started = false;
    }

    /**
     * Initialize the DDNS object.
     * @param {CommonCallback} callback the callback function
     */
    initialize(callback) {
        spidex.post(`${BASE_URI}/Domain.List`, {
            timeout: 60000,
            charset: "utf8",
            data: {
                "login_token": this.token,
                format: "json",
                lang: this.cfg.remoteLang,
                "error_on_empty": "no",

                type: "mine",
                keyword: this.cfg.domain
            }
        }, (content, status) => {
            if(status !== 200) {
                return callback(new Error(`Server returns a wrong status ${status}`));
            }

            let json;
            try {
                json = JSON.parse(content);
            } catch(e) {
                return callback(e);
            }

            if(!json.status) {
                return callback(new Error("Broken server content: " + content));
            }

            if(json.status.code !== "1") {
                return callback(new Error(json.status.message));
            }

            let domains = json.domains;
            if(!domains.length) {
                return callback(new Error("No target domain: " + this.cfg.domain));
            }

            for(let i = 0; i < domains.length; i++) {
                if(domains[i].name === this.cfg.domain) {
                    this.domainId = domains[i].id;
                    return callback();
                }
            }

            callback(new Error("No fit domain."));
        }).on("error", callback);
    }

    /**
     * Fetch the specified record(s).
     * @param {String[]} subdomains the subdomains' name
     * @param {RecordCallback} callback the callback function
     */
    fetchSpecifiedRecord(subdomains, callback) {
        const token = this.token;
        const domainId = this.domainId;

        // 从 API 获取记录
        spidex.post(`${BASE_URI}/Record.List`, {
            timeout: 60000,
            charset: "utf8",
            data: {
                "login_token": this.token,
                format: "json",
                lang: this.cfg.remoteLang,
                "error_on_empty": "no",

                "domain_id": this.domainId
            }
        }, (content, status) => {
            if(status !== 200) {
                return callback(new Error(`Server returns a wrong status ${status}`));
            }

            let json;
            try {
                json = JSON.parse(content);
            } catch(e) {
                return callback(e);
            }

            if(!json.status) {
                return callback(new Error("Broken server content: " + content));
            }

            if(json.status.code !== "1") {
                return callback(new Error(json.status.message));
            }

            const raw = json.records;
            const records = [];
            for(let i = 0; i < raw.length; i++) {
                if(raw[i].type === "A" && subdomains.indexOf(raw[i].name) > -1) {
                    let record = new Record(raw[i], domainId, token);
                    records.push(record);
                }
            }

            callback(undefined, records);
        });
    }

    /**
     * Start running DDNS work.
     */
    start() {
        if(this.started) return;
        this.started = true;
        process.nextTick(this._interval.bind(this));
    }

    /**
     * Each DDNS round processor.
     * @protected
     *
     * @fires DDNS#changed
     * @fires DDNS#changing
     * @fires DDNS#detected
     * @fires DDNS#detecting
     * @fires DDNS#equal
     * @fires DDNS#error
     * @fires DDNS#round
     * @fires DDNS#roundEnd
     * @fires DDNS#saveError
     * @fires DDNS#warn
     */
    _interval() {
        /**
         * Fired when a new round is started.
         * @event DDNS#round
         */
        this.emit("round");

        const self = this;
        const getIP = this.ipGetter;
        async.waterfall([
            callback => {
                /**
                 * Fired when DDNS is detecting current IP.
                 * @event DDNS#detecting
                 */
                self.emit("detecting");
                getIP((err, ip) => {
                    if(err) return callback(err);
                    /**
                     * Fired when current IP was detected.
                     * @event DDNS#detected
                     * @param {String} ip the IP detected
                     */
                    self.emit("detected", ip);
                    return callback(undefined, ip);
                });
            },

            (ip, callback) => this.fetchSpecifiedRecord(this.subdomains, (err, records) => {
                callback(err, records, ip);
            }),

            (records, ip, callback) => {
                if(!records.length) {
                    /**
                     * Warning occurred.
                     * @event DDNS#warn
                     * @param {Error} err the error object
                     */
                    self.emit("warn", new Error("No available subdomains."));
                    return callback();
                }

                const scarlet = new Scarlet(10);

                let processor = function(TO) {
                    const record = TO.task;
                    if(record.ip === ip) {
                        /**
                         * Fired when a record's IP equals to the IP just detected.
                         * @event DDNS#equal
                         * @param {Record} record the record object
                         * @param {String} ip current IP
                         */
                        self.emit("equal", record, ip);
                        return scarlet.taskDone(TO);
                    }

                    /**
                     * Fired when DDNS is to change record's IP.
                     * @event DDNS#changing
                     * @param {Record} record the record object
                     * @param {String} ip current ip
                     */
                    self.emit("changing", record, ip);
                    record.ip = ip;
                    record.save(err => {
                        if(err) {
                            /**
                             * Fired when an error occurred while saving a record
                             * @event DDNS#saveError
                             * @param {Error} err the error object
                             * @param {Record} record the record object
                             */
                            self.emit("saveError", err, record);
                        }

                        /**
                         * Fired when a record just saved
                         * @event DDNS#changed
                         * @param {Record} record the record object
                         */
                        self.emit("changed", record);
                        scarlet.taskDone(TO);
                    });
                };

                for(let i = 0; i < records.length; i++) {
                    scarlet.push(records[i], processor);
                }

                scarlet.afterFinish(records.length, function() {
                    callback();
                }, false);
            }
        ], (err) => {
            if(err) {
                /**
                 * onError
                 * @event DDNS#error
                 * @param {Error} err the error object
                 */
                self.emit("error", err);
            }

            /**
             * Fired when a round is ending.
             * @event DDNS#roundEnd
             */
            self.emit("roundEnd");
            setTimeout(self._interval.bind(self), self.cfg.interval);
        });
    }
}

module.exports = DDNS;
<commit_msg>update ddns.js<commit_after>/**
 * XadillaX created at 2016-04-06 23:43:51 With ♥
 *
 * Copyright (c) 2016 Souche.com, all rights
 * reserved.
 */
"use strict";

const EventEmitter = require("events").EventEmitter;

const async = require("async");
const Scarlet = require("scarlet-task");
const spidex = require("spidex");

const ConfigSchema = require("./config_schema");
const Record = require("./record");

const BASE_URI = "https://dnsapi.cn";

/** The DNSPod dynamic domain class. */
class DDNS extends EventEmitter {
    /**
     * Create a DDNS object.
     * @param {ConfigSchema} cfg the config schema object
     */
    constructor(cfg) {
        super();

        if(!(cfg instanceof ConfigSchema) || !cfg.check()) {
            throw new Error("Broken config schema.");
        }

        /** @member {ConfigSchema} - the config schema object. */
        this.cfg = cfg;
        /** @member {String} - the token string. */
        this.token = cfg.token;
        /** @member {String|NULL} - the domain id. */
        this.domainId = null;
        /** @member {String[]} - the subdomains to be run. */
        this.subdomains = cfg.subdomains;
        /** @member {Function} - the ip getter function. */
        this.ipGetter = cfg.ipGetter;

        /** @member {Boolean} - whether this DDNS is running or not. */
        this.started = false;
    }

    /**
     * Initialize the DDNS object.
     * @param {CommonCallback} callback the callback function
     */
    initialize(callback) {
        spidex.post(`${BASE_URI}/Domain.List`, {
            timeout: 60000,
            charset: "utf8",
            data: {
                "login_token": this.token,
                format: "json",
                lang: this.cfg.remoteLang,
                "error_on_empty": "no",

                type: "mine"
            }
        }, (content, status) => {
            if(status !== 200) {
                return callback(new Error(`Server returns a wrong status ${status}`));
            }

            let json;
            try {
                json = JSON.parse(content);
            } catch(e) {
                return callback(e);
            }

            if(!json.status) {
                return callback(new Error("Broken server content: " + content));
            }

            if(json.status.code !== "1") {
                return callback(new Error(json.status.message));
            }

            let domains = json.domains;
            if(!domains.length) {
                return callback(new Error("No target domain: " + this.cfg.domain));
            }

            for(let i = 0; i < domains.length; i++) {
                if(domains[i].name === this.cfg.domain) {
                    this.domainId = domains[i].id;
                    return callback();
                }
            }

            callback(new Error("No fit domain."));
        }).on("error", callback);
    }

    /**
     * Fetch the specified record(s).
     * @param {String[]} subdomains the subdomains' name
     * @param {RecordCallback} callback the callback function
     */
    fetchSpecifiedRecord(subdomains, callback) {
        const token = this.token;
        const domainId = this.domainId;

        // 从 API 获取记录
        spidex.post(`${BASE_URI}/Record.List`, {
            timeout: 60000,
            charset: "utf8",
            data: {
                "login_token": this.token,
                format: "json",
                lang: this.cfg.remoteLang,
                "error_on_empty": "no",

                "domain_id": this.domainId
            }
        }, (content, status) => {
            if(status !== 200) {
                return callback(new Error(`Server returns a wrong status ${status}`));
            }

            let json;
            try {
                json = JSON.parse(content);
            } catch(e) {
                return callback(e);
            }

            if(!json.status) {
                return callback(new Error("Broken server content: " + content));
            }

            if(json.status.code !== "1") {
                return callback(new Error(json.status.message));
            }

            const raw = json.records;
            const records = [];
            for(let i = 0; i < raw.length; i++) {
                if(raw[i].type === "A" && subdomains.indexOf(raw[i].name) > -1) {
                    let record = new Record(raw[i], domainId, token);
                    records.push(record);
                }
            }

            callback(undefined, records);
        });
    }

    /**
     * Start running DDNS work.
     */
    start() {
        if(this.started) return;
        this.started = true;
        process.nextTick(this._interval.bind(this));
    }

    /**
     * Each DDNS round processor.
     * @protected
     *
     * @fires DDNS#changed
     * @fires DDNS#changing
     * @fires DDNS#detected
     * @fires DDNS#detecting
     * @fires DDNS#equal
     * @fires DDNS#error
     * @fires DDNS#round
     * @fires DDNS#roundEnd
     * @fires DDNS#saveError
     * @fires DDNS#warn
     */
    _interval() {
        /**
         * Fired when a new round is started.
         * @event DDNS#round
         */
        this.emit("round");

        const self = this;
        const getIP = this.ipGetter;
        async.waterfall([
            callback => {
                /**
                 * Fired when DDNS is detecting current IP.
                 * @event DDNS#detecting
                 */
                self.emit("detecting");
                getIP((err, ip) => {
                    if(err) return callback(err);
                    /**
                     * Fired when current IP was detected.
                     * @event DDNS#detected
                     * @param {String} ip the IP detected
                     */
                    self.emit("detected", ip);
                    return callback(undefined, ip);
                });
            },

            (ip, callback) => this.fetchSpecifiedRecord(this.subdomains, (err, records) => {
                callback(err, records, ip);
            }),

            (records, ip, callback) => {
                if(!records.length) {
                    /**
                     * Warning occurred.
                     * @event DDNS#warn
                     * @param {Error} err the error object
                     */
                    self.emit("warn", new Error("No available subdomains."));
                    return callback();
                }

                const scarlet = new Scarlet(10);

                let processor = function(TO) {
                    const record = TO.task;
                    if(record.ip === ip) {
                        /**
                         * Fired when a record's IP equals to the IP just detected.
                         * @event DDNS#equal
                         * @param {Record} record the record object
                         * @param {String} ip current IP
                         */
                        self.emit("equal", record, ip);
                        return scarlet.taskDone(TO);
                    }

                    /**
                     * Fired when DDNS is to change record's IP.
                     * @event DDNS#changing
                     * @param {Record} record the record object
                     * @param {String} ip current ip
                     */
                    self.emit("changing", record, ip);
                    record.ip = ip;
                    record.save(err => {
                        if(err) {
                            /**
                             * Fired when an error occurred while saving a record
                             * @event DDNS#saveError
                             * @param {Error} err the error object
                             * @param {Record} record the record object
                             */
                            self.emit("saveError", err, record);
                        }

                        /**
                         * Fired when a record just saved
                         * @event DDNS#changed
                         * @param {Record} record the record object
                         */
                        self.emit("changed", record);
                        scarlet.taskDone(TO);
                    });
                };

                for(let i = 0; i < records.length; i++) {
                    scarlet.push(records[i], processor);
                }

                scarlet.afterFinish(records.length, function() {
                    callback();
                }, false);
            }
        ], (err) => {
            if(err) {
                /**
                 * onError
                 * @event DDNS#error
                 * @param {Error} err the error object
                 */
                self.emit("error", err);
            }

            /**
             * Fired when a round is ending.
             * @event DDNS#roundEnd
             */
            self.emit("roundEnd");
            setTimeout(self._interval.bind(self), self.cfg.interval);
        });
    }
}

module.exports = DDNS;
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

module.exports = AppGenerator;

function AppGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  // setup the test-framework property, Gruntfile template will need this
  this.testFramework = options['test-framework'] || 'mocha';

  // for hooks to resolve on mocha by default
  if (!options['test-framework']) {
    options['test-framework'] = 'mocha';
  }

  // resolved to mocha by default (could be switched to jasmine for instance)
  this.hookFor('test-framework', { as: 'app' });

  this.indexFile = this.readFileAsString(path.join(this.sourceRoot(), 'index.html'));
  this.mainJsFile = '';

  this.on('end', function () {
    console.log('\nI\'m all done. Just run ' + 'npm install && bower install'.bold.yellow + ' to install the required dependencies.');
  });
}

util.inherits(AppGenerator, yeoman.generators.NamedBase);

AppGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
  '\n     _-----_' +
  '\n    |       |' +
  '\n    |'+'--(o)--'.red+'|   .--------------------------.' +
  '\n   `---------´  |    '+'Welcome to Yeoman,'.yellow.bold+'    |' +
  '\n    '+'( '.yellow+'_'+'´U`'.yellow+'_'+' )'.yellow+'   |   '+'ladies and gentlemen!'.yellow.bold+'  |' +
  '\n    /___A___\\   \'__________________________\'' +
  '\n     |  ~  |'.yellow +
  '\n   __'+'\'.___.\''.yellow+'__' +
  '\n ´   '+'`  |'.red+'° '+'´ Y'.red+' `\n';

  console.log(welcome);
  console.log('Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.');

  var prompts = [{
    name: 'compassBootstrap',
    message: 'Would you like to include Twitter Bootstrap for Sass?',
    default: 'Y/n',
    warning: 'Yes: All Twitter Bootstrap files will be placed into the styles directory.'
  },
  {
    name: 'includeRequireJS',
    message: 'Would you like to include RequireJS (for AMD support)?',
    default: 'Y/n',
    warning: 'Yes: RequireJS will be placed into the JavaScript vendor directory.'
  }];

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    // manually deal with the response, get back and store the results.
    // we change a bit this way of doing to automatically do this in the self.prompt() method.
    this.compassBootstrap = (/y/i).test(props.compassBootstrap);
    this.includeRequireJS = (/y/i).test(props.includeRequireJS);

    cb();
  }.bind(this));
};

AppGenerator.prototype.gruntfile = function gruntfile() {
  this.template('Gruntfile.js');
};

AppGenerator.prototype.packageJSON = function packageJSON() {
  this.template('_package.json', 'package.json');
};

AppGenerator.prototype.git = function git() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
};

AppGenerator.prototype.bower = function bower() {
  this.copy('bowerrc', '.bowerrc');
  this.copy('_component.json', 'component.json');
};

AppGenerator.prototype.jshint = function jshint() {
  this.copy('jshintrc', '.jshintrc');
};

AppGenerator.prototype.editorConfig = function editorConfig() {
  this.copy('editorconfig', '.editorconfig');
};

AppGenerator.prototype.h5bp = function h5bp() {
  this.copy('favicon.ico', 'app/favicon.ico');
  this.copy('404.html', 'app/404.html');
  this.copy('robots.txt', 'app/robots.txt');
  this.copy('htaccess', 'app/.htaccess');
};

AppGenerator.prototype.bootstrapJs = function bootstrapJs() {
  // TODO: create a Bower component for this
  if (this.includeRequireJS) {
    this.copy('bootstrap.js', 'app/scripts/vendor/bootstrap.js');
  }
};

AppGenerator.prototype.mainStylesheet = function mainStylesheet() {
  if (this.compassBootstrap) {
    this.write('app/styles/main.scss', '@import \'sass-bootstrap/lib/bootstrap\';\n\n.hero-unit {\n    margin: 50px auto 0 auto;\n    width: 300px;\n}');
  } else {
    this.write('app/styles/main.css', 'body {\n    background: #fafafa;\n}\n\n.hero-unit {\n    margin: 50px auto 0 auto;\n    width: 300px;\n}');
  }
};

AppGenerator.prototype.writeIndex = function writeIndex() {
  // prepare default content text
  var defaults = ['HTML5 Boilerplate', 'Twitter Bootstrap'];
  var contentText = [
    '
',
    '
',
    '
\'Allo, \'Allo!
',
    '
You now have
',
    '
'
  ];

  if (this.compassBootstrap && !this.includeRequireJS) {
    // wire Twitter Bootstrap plugins
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/plugins.js', [
      'components/sass-bootstrap/js/bootstrap-affix.js',
      'components/sass-bootstrap/js/bootstrap-alert.js',
      'components/sass-bootstrap/js/bootstrap-dropdown.js',
      'components/sass-bootstrap/js/bootstrap-tooltip.js',
      'components/sass-bootstrap/js/bootstrap-modal.js',
      'components/sass-bootstrap/js/bootstrap-transition.js',
      'components/sass-bootstrap/js/bootstrap-button.js',
      'components/sass-bootstrap/js/bootstrap-popover.js',
      'components/sass-bootstrap/js/bootstrap-typeahead.js',
      'components/sass-bootstrap/js/bootstrap-carousel.js',
      'components/sass-bootstrap/js/bootstrap-scrollspy.js',
      'components/sass-bootstrap/js/bootstrap-collapse.js',
      'components/sass-bootstrap/js/bootstrap-tab.js'
    ]);
  }

  if (this.includeRequireJS) {
    defaults.push('RequireJS');
  } else {
    this.mainJsFile = 'console.log(\'\\\'Allo \\\'Allo!\');';
  }

  // iterate over defaults and create content string
  defaults.forEach(function (el) {
    contentText.push('
' + el  +'
');
  });

  contentText = contentText.concat([
    '
',
    '
installed.
',
    '
Enjoy coding! - Yeoman
',
    '
',
    '
',
    ''
  ]);

  // append the default content
  this.indexFile = this.indexFile.replace('', '\n' + contentText.join('\n'));
};

// TODO(mklabs): to be put in a subgenerator like rjs:app
AppGenerator.prototype.requirejs = function requirejs() {
  if (this.includeRequireJS) {
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/main.js', ['components/requirejs/require.js'], {
      'data-main': 'scripts/main'
    });

    // add a basic amd module
    this.write('app/scripts/app.js', [
      '/*global define */',
      'define([], function () {',
      '    \'use strict\';\n',
      '    return \'\\\'Allo \\\'Allo!\';',
      '});'
    ].join('\n'));

    this.mainJsFile = [
      'require.config({',
      '    paths: {',
      '        jquery: \'../components/jquery/jquery\',',
      '        bootstrap: \'vendor/bootstrap\'',
      '    },',
      '    shim: {',
      '        bootstrap: {',
      '            deps: [\'jquery\'],',
      '            exports: \'jquery\'',
      '        }',
      '    }',
      '});',
      '',
      'require([\'app\', \'jquery\', \'bootstrap\'], function (app, $) {',
      '    \'use strict\';',
      '    // use app here',
      '    console.log(app);',
      '    console.log(\'Running jQuery %s\', $().jquery);',
      '});'
    ].join('\n');
  }
};

AppGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
  this.mkdir('app/styles');
  this.mkdir('app/images');
  this.write('app/index.html', this.indexFile);
  this.write('app/scripts/main.js', this.mainJsFile);
};
<commit_msg>Include jquery in non-AMD build<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

module.exports = AppGenerator;

function AppGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  // setup the test-framework property, Gruntfile template will need this
  this.testFramework = options['test-framework'] || 'mocha';

  // for hooks to resolve on mocha by default
  if (!options['test-framework']) {
    options['test-framework'] = 'mocha';
  }

  // resolved to mocha by default (could be switched to jasmine for instance)
  this.hookFor('test-framework', { as: 'app' });

  this.indexFile = this.readFileAsString(path.join(this.sourceRoot(), 'index.html'));
  this.mainJsFile = '';

  this.on('end', function () {
    console.log('\nI\'m all done. Just run ' + 'npm install && bower install'.bold.yellow + ' to install the required dependencies.');
  });
}

util.inherits(AppGenerator, yeoman.generators.NamedBase);

AppGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
  '\n     _-----_' +
  '\n    |       |' +
  '\n    |'+'--(o)--'.red+'|   .--------------------------.' +
  '\n   `---------´  |    '+'Welcome to Yeoman,'.yellow.bold+'    |' +
  '\n    '+'( '.yellow+'_'+'´U`'.yellow+'_'+' )'.yellow+'   |   '+'ladies and gentlemen!'.yellow.bold+'  |' +
  '\n    /___A___\\   \'__________________________\'' +
  '\n     |  ~  |'.yellow +
  '\n   __'+'\'.___.\''.yellow+'__' +
  '\n ´   '+'`  |'.red+'° '+'´ Y'.red+' `\n';

  console.log(welcome);
  console.log('Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.');

  var prompts = [{
    name: 'compassBootstrap',
    message: 'Would you like to include Twitter Bootstrap for Sass?',
    default: 'Y/n',
    warning: 'Yes: All Twitter Bootstrap files will be placed into the styles directory.'
  },
  {
    name: 'includeRequireJS',
    message: 'Would you like to include RequireJS (for AMD support)?',
    default: 'Y/n',
    warning: 'Yes: RequireJS will be placed into the JavaScript vendor directory.'
  }];

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    // manually deal with the response, get back and store the results.
    // we change a bit this way of doing to automatically do this in the self.prompt() method.
    this.compassBootstrap = (/y/i).test(props.compassBootstrap);
    this.includeRequireJS = (/y/i).test(props.includeRequireJS);

    cb();
  }.bind(this));
};

AppGenerator.prototype.gruntfile = function gruntfile() {
  this.template('Gruntfile.js');
};

AppGenerator.prototype.packageJSON = function packageJSON() {
  this.template('_package.json', 'package.json');
};

AppGenerator.prototype.git = function git() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
};

AppGenerator.prototype.bower = function bower() {
  this.copy('bowerrc', '.bowerrc');
  this.copy('_component.json', 'component.json');
};

AppGenerator.prototype.jshint = function jshint() {
  this.copy('jshintrc', '.jshintrc');
};

AppGenerator.prototype.editorConfig = function editorConfig() {
  this.copy('editorconfig', '.editorconfig');
};

AppGenerator.prototype.h5bp = function h5bp() {
  this.copy('favicon.ico', 'app/favicon.ico');
  this.copy('404.html', 'app/404.html');
  this.copy('robots.txt', 'app/robots.txt');
  this.copy('htaccess', 'app/.htaccess');
};

AppGenerator.prototype.bootstrapJs = function bootstrapJs() {
  // TODO: create a Bower component for this
  if (this.includeRequireJS) {
    this.copy('bootstrap.js', 'app/scripts/vendor/bootstrap.js');
  }
};

AppGenerator.prototype.mainStylesheet = function mainStylesheet() {
  if (this.compassBootstrap) {
    this.write('app/styles/main.scss', '@import \'sass-bootstrap/lib/bootstrap\';\n\n.hero-unit {\n    margin: 50px auto 0 auto;\n    width: 300px;\n}');
  } else {
    this.write('app/styles/main.css', 'body {\n    background: #fafafa;\n}\n\n.hero-unit {\n    margin: 50px auto 0 auto;\n    width: 300px;\n}');
  }
};

AppGenerator.prototype.writeIndex = function writeIndex() {
  // prepare default content text
  var defaults = ['HTML5 Boilerplate', 'Twitter Bootstrap'];
  var contentText = [
    '
',
    '
',
    '
\'Allo, \'Allo!
',
    '
You now have
',
    '
'
  ];

  if (!this.includeRequireJS) {
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/jquery.js', [
      'components/jquery/jquery.js'
    ]);
  }

  if (this.compassBootstrap && !this.includeRequireJS) {
    // wire Twitter Bootstrap plugins
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/plugins.js', [
      'components/sass-bootstrap/js/bootstrap-affix.js',
      'components/sass-bootstrap/js/bootstrap-alert.js',
      'components/sass-bootstrap/js/bootstrap-dropdown.js',
      'components/sass-bootstrap/js/bootstrap-tooltip.js',
      'components/sass-bootstrap/js/bootstrap-modal.js',
      'components/sass-bootstrap/js/bootstrap-transition.js',
      'components/sass-bootstrap/js/bootstrap-button.js',
      'components/sass-bootstrap/js/bootstrap-popover.js',
      'components/sass-bootstrap/js/bootstrap-typeahead.js',
      'components/sass-bootstrap/js/bootstrap-carousel.js',
      'components/sass-bootstrap/js/bootstrap-scrollspy.js',
      'components/sass-bootstrap/js/bootstrap-collapse.js',
      'components/sass-bootstrap/js/bootstrap-tab.js'
    ]);
  }

  if (this.includeRequireJS) {
    defaults.push('RequireJS');
  } else {
    this.mainJsFile = 'console.log(\'\\\'Allo \\\'Allo!\');';
  }

  // iterate over defaults and create content string
  defaults.forEach(function (el) {
    contentText.push('
' + el  +'
');
  });

  contentText = contentText.concat([
    '
',
    '
installed.
',
    '
Enjoy coding! - Yeoman
',
    '
',
    '
',
    ''
  ]);

  // append the default content
  this.indexFile = this.indexFile.replace('', '\n' + contentText.join('\n'));
};

// TODO(mklabs): to be put in a subgenerator like rjs:app
AppGenerator.prototype.requirejs = function requirejs() {
  if (this.includeRequireJS) {
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/main.js', ['components/requirejs/require.js'], {
      'data-main': 'scripts/main'
    });

    // add a basic amd module
    this.write('app/scripts/app.js', [
      '/*global define */',
      'define([], function () {',
      '    \'use strict\';\n',
      '    return \'\\\'Allo \\\'Allo!\';',
      '});'
    ].join('\n'));

    this.mainJsFile = [
      'require.config({',
      '    paths: {',
      '        jquery: \'../components/jquery/jquery\',',
      '        bootstrap: \'vendor/bootstrap\'',
      '    },',
      '    shim: {',
      '        bootstrap: {',
      '            deps: [\'jquery\'],',
      '            exports: \'jquery\'',
      '        }',
      '    }',
      '});',
      '',
      'require([\'app\', \'jquery\', \'bootstrap\'], function (app, $) {',
      '    \'use strict\';',
      '    // use app here',
      '    console.log(app);',
      '    console.log(\'Running jQuery %s\', $().jquery);',
      '});'
    ].join('\n');
  }
};

AppGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
  this.mkdir('app/styles');
  this.mkdir('app/images');
  this.write('app/index.html', this.indexFile);
  this.write('app/scripts/main.js', this.mainJsFile);
};
<|endoftext|>


<commit_before>var events = require("sdk/system/events");
var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var timer = require('./timer/timer');
var notifier = require('./notifier');

var activeTab;

var button = buttons.ActionButton({
  id: "timing",
  label: "Start reload timer",
  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png",
    "64": "./icon-64.png"
  },
  onClick: handleClick
});

function handleClick(state) {
	activeTab = tabs.activeTab;
	pageUrl = activeTab.url;

	timer.init(activeTab, 5);
	timer.startAttempt();
    events.on('timerComplete', function(){
		notifier.renderTimerResult(pageUrl, timer.getResults());
	});
}<commit_msg>Refactoring<commit_after>var events = require("sdk/system/events");
var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var timer = require('./timer/timer');
var notifier = require('./notifier');

buttons.ActionButton({
  id: "timing",
  label: "Start reload timer",
  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png",
    "64": "./icon-64.png"
  },
  onClick: handleButtonClick
});

function handleButtonClick(state) {
	activeTab = tabs.activeTab;
	pageUrl = activeTab.url;

	timer.init(activeTab, 5);
	timer.startAttempt();
    events.on('timerComplete', function(){
		notifier.renderTimerResult(pageUrl, timer.getResults());
	});
}<|endoftext|>


<commit_before>const express = require('express')
const { json, urlencoded } = require('body-parser')

const PORT = 3000

const app = express()
app.use(json())
app.use(urlencoded({ extended: true }))
app.set('port', PORT)

app.all('/status', (req, res) => {
  res.status(200).send({
    status: 'ok',
    date: new Date()
  })
})

app.get('*', (req, res) => {
  res.sendStatus(404)
})

module.exports = app

<commit_msg>Show environment on /status<commit_after>const express = require('express')
const { json, urlencoded } = require('body-parser')

const PORT = 3000
const environment = process.env.API_ENV

const app = express()
app.use(json())
app.use(urlencoded({ extended: true }))
app.set('port', PORT)

app.all('/status', (req, res) => {
  res.status(200).send({
    environment,
    status: 'ok',
    date: new Date()
  })
})

app.get('*', (req, res) => {
  res.sendStatus(404)
})

module.exports = app

<|endoftext|>


<commit_before>'use strict'
const fs = process.versions.electron ? require('original-fs') : require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const pickle = require('chromium-pickle-js')

const Filesystem = require('./filesystem')
let filesystemCache = {}

const copyFileToSync = function (dest, src, filename) {
  const srcFile = path.join(src, filename)
  const targetFile = path.join(dest, filename)

  const content = fs.readFileSync(srcFile)
  const stats = fs.statSync(srcFile)
  mkdirp.sync(path.dirname(targetFile))
  return fs.writeFileSync(targetFile, content, {mode: stats.mode})
}

const writeFileListToStream = function (dest, filesystem, out, list, metadata, callback) {
  for (let i = 0; i < list.length; i++) {
    const file = list[i]
    if (file.unpack) {
      // the file should not be packed into archive.
      const filename = path.relative(filesystem.src, file.filename)
      try {
        copyFileToSync(`${dest}.unpacked`, filesystem.src, filename)
      } catch (error) {
        return callback(error)
      }
    } else {
      const tr = metadata[file.filename].transformed
      const stream = fs.createReadStream((tr ? tr.path : file.filename))
      stream.pipe(out, {end: false})
      stream.on('error', callback)
      return stream.on('end', function () {
        return writeFileListToStream(dest, filesystem, out, list.slice(i + 1), metadata, callback)
      })
    }
  }
  out.end()
  return callback(null)
}

module.exports.writeFilesystem = function (dest, filesystem, files, metadata, callback) {
  let sizeBuf
  let headerBuf
  try {
    const headerPickle = pickle.createEmpty()
    headerPickle.writeString(JSON.stringify(filesystem.header))
    headerBuf = headerPickle.toBuffer()

    const sizePickle = pickle.createEmpty()
    sizePickle.writeUInt32(headerBuf.length)
    sizeBuf = sizePickle.toBuffer()
  } catch (error) {
    return callback(error)
  }

  const out = fs.createWriteStream(dest)
  out.on('error', callback)
  out.write(sizeBuf)
  return out.write(headerBuf, function () {
    return writeFileListToStream(dest, filesystem, out, files, metadata, callback)
  })
}

module.exports.readArchiveHeaderSync = function (archive) {
  const fd = fs.openSync(archive, 'r')
  let size
  let headerBuf
  try {
    const sizeBuf = new Buffer(8)
    if (fs.readSync(fd, sizeBuf, 0, 8, null) !== 8) {
      throw new Error('Unable to read header size')
    }

    const sizePickle = pickle.createFromBuffer(sizeBuf)
    size = sizePickle.createIterator().readUInt32()
    headerBuf = new Buffer(size)
    if (fs.readSync(fd, headerBuf, 0, size, null) !== size) {
      throw new Error('Unable to read header')
    }
  } finally {
    fs.closeSync(fd)
  }

  const headerPickle = pickle.createFromBuffer(headerBuf)
  const header = headerPickle.createIterator().readString()
  return {header: JSON.parse(header), headerSize: size}
}

module.exports.readFilesystemSync = function (archive) {
  if (!filesystemCache[archive]) {
    const header = this.readArchiveHeaderSync(archive)
    const filesystem = new Filesystem(archive)
    filesystem.header = header.header
    filesystem.headerSize = header.headerSize
    filesystemCache[archive] = filesystem
  }
  return filesystemCache[archive]
}

module.exports.uncacheFilesystem = function (archive) {
  if (filesystemCache[archive]) {
    filesystemCache[archive] = undefined
    return true
  }
  return false
}

module.exports.uncacheAll = function () {
  filesystemCache = {}
}

module.exports.readFileSync = function (filesystem, filename, info) {
  let buffer = new Buffer(info.size)
  if (info.size <= 0) { return buffer }
  if (info.unpacked) {
    // it's an unpacked file, copy it.
    buffer = fs.readFileSync(path.join(`${filesystem.src}.unpacked`, filename))
  } else {
    // Node throws an exception when reading 0 bytes into a 0-size buffer,
    // so we short-circuit the read in this case.
    const fd = fs.openSync(filesystem.src, 'r')
    try {
      const offset = 8 + filesystem.headerSize + parseInt(info.offset)
      fs.readSync(fd, buffer, 0, info.size, offset)
    } finally {
      fs.closeSync(fd)
    }
  }
  return buffer
}
<commit_msg>fix: Use buffer.alloc<commit_after>'use strict'
const fs = process.versions.electron ? require('original-fs') : require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const pickle = require('chromium-pickle-js')

const Filesystem = require('./filesystem')
let filesystemCache = {}

const copyFileToSync = function (dest, src, filename) {
  const srcFile = path.join(src, filename)
  const targetFile = path.join(dest, filename)

  const content = fs.readFileSync(srcFile)
  const stats = fs.statSync(srcFile)
  mkdirp.sync(path.dirname(targetFile))
  return fs.writeFileSync(targetFile, content, { mode: stats.mode })
}

const writeFileListToStream = function (dest, filesystem, out, list, metadata, callback) {
  for (let i = 0; i < list.length; i++) {
    const file = list[i]
    if (file.unpack) {
      // the file should not be packed into archive.
      const filename = path.relative(filesystem.src, file.filename)
      try {
        copyFileToSync(`${dest}.unpacked`, filesystem.src, filename)
      } catch (error) {
        return callback(error)
      }
    } else {
      const tr = metadata[file.filename].transformed
      const stream = fs.createReadStream((tr ? tr.path : file.filename))
      stream.pipe(out, { end: false })
      stream.on('error', callback)
      return stream.on('end', function () {
        return writeFileListToStream(dest, filesystem, out, list.slice(i + 1), metadata, callback)
      })
    }
  }
  out.end()
  return callback(null)
}

module.exports.writeFilesystem = function (dest, filesystem, files, metadata, callback) {
  let sizeBuf
  let headerBuf
  try {
    const headerPickle = pickle.createEmpty()
    headerPickle.writeString(JSON.stringify(filesystem.header))
    headerBuf = headerPickle.toBuffer()

    const sizePickle = pickle.createEmpty()
    sizePickle.writeUInt32(headerBuf.length)
    sizeBuf = sizePickle.toBuffer()
  } catch (error) {
    return callback(error)
  }

  const out = fs.createWriteStream(dest)
  out.on('error', callback)
  out.write(sizeBuf)
  return out.write(headerBuf, function () {
    return writeFileListToStream(dest, filesystem, out, files, metadata, callback)
  })
}

module.exports.readArchiveHeaderSync = function (archive) {
  const fd = fs.openSync(archive, 'r')
  let size
  let headerBuf
  try {
    const sizeBuf = Buffer.alloc(8)
    if (fs.readSync(fd, sizeBuf, 0, 8, null) !== 8) {
      throw new Error('Unable to read header size')
    }

    const sizePickle = pickle.createFromBuffer(sizeBuf)
    size = sizePickle.createIterator().readUInt32()
    headerBuf = Buffer.alloc(size)
    if (fs.readSync(fd, headerBuf, 0, size, null) !== size) {
      throw new Error('Unable to read header')
    }
  } finally {
    fs.closeSync(fd)
  }

  const headerPickle = pickle.createFromBuffer(headerBuf)
  const header = headerPickle.createIterator().readString()
  return { header: JSON.parse(header), headerSize: size }
}

module.exports.readFilesystemSync = function (archive) {
  if (!filesystemCache[archive]) {
    const header = this.readArchiveHeaderSync(archive)
    const filesystem = new Filesystem(archive)
    filesystem.header = header.header
    filesystem.headerSize = header.headerSize
    filesystemCache[archive] = filesystem
  }
  return filesystemCache[archive]
}

module.exports.uncacheFilesystem = function (archive) {
  if (filesystemCache[archive]) {
    filesystemCache[archive] = undefined
    return true
  }
  return false
}

module.exports.uncacheAll = function () {
  filesystemCache = {}
}

module.exports.readFileSync = function (filesystem, filename, info) {
  let buffer = Buffer.alloc(info.size)
  if (info.size <= 0) { return buffer }
  if (info.unpacked) {
    // it's an unpacked file, copy it.
    buffer = fs.readFileSync(path.join(`${filesystem.src}.unpacked`, filename))
  } else {
    // Node throws an exception when reading 0 bytes into a 0-size buffer,
    // so we short-circuit the read in this case.
    const fd = fs.openSync(filesystem.src, 'r')
    try {
      const offset = 8 + filesystem.headerSize + parseInt(info.offset)
      fs.readSync(fd, buffer, 0, info.size, offset)
    } finally {
      fs.closeSync(fd)
    }
  }
  return buffer
}
<|endoftext|>


<commit_before>/* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
"use strict";

let windows = require("sdk/windows");
let {viewFor} = require("sdk/view/core");
let self = require("sdk/self");
const {Cc, Ci} = require("chrome");

let gSSService = Cc["@mozilla.org/ssservice;1"].getService(Ci.nsISiteSecurityService);

function ProgressListener(win) {
  this._win = win;
  this._doneOne = false;
  this._lastState = 0;
  this._lastLocation = "";
}

ProgressListener.prototype.onSecurityChange = function(webProgress, request, state) {
  let uri = this._win.gBrowser.currentURI;
  if (this._doneOne && state === this._lastState && uri.spec === this._lastLocation)
    return;
  this._doneOne = true;
  this._lastState = state;
  this._lastLocation = uri.spec;
  let label = this._win.document.getElementById("httpsinfo-label");
  if (!(state & (Ci.nsIWebProgressListener.STATE_IS_SECURE | Ci.nsIWebProgressListener.STATE_IS_BROKEN))) {
    label.collapsed = true;
    return;
  }

  const nsISSLStatus = Ci.nsISSLStatus;
  let sslStatus = this._win.gBrowser.securityUI.SSLStatus;
  let protocolVersion;
  switch (sslStatus.protocolVersion) {
  case nsISSLStatus.TLS_VERSION_1:
    protocolVersion = "1.0";
    break;
  case nsISSLStatus.TLS_VERSION_1_1:
    protocolVersion = "1.1";
    break;
  case nsISSLStatus.TLS_VERSION_1_2:
    protocolVersion = "1.2";
    break;
  default:
    protocolVersion = "?";
    break;
  }
  let suite = sslStatus.cipherName;
  let pfs = suite.contains("DHE_");
  let cipher = suite.contains("_AES_") ? "AES" :
      (suite.contains("_RC4_") ? "RC4" :
       (suite.contains("_3DES_") ? "DES" : "?"));
  let mode = suite.contains("_GCM_") ? "/GCM" :
      (suite.contains("_CBC_") ? "/CBC" :
       (cipher === "RC4" ? "" : "/?"));
  let h2 = false;
  let httpInternal = request.QueryInterface(Ci.nsIHttpChannelInternal);
  if (httpInternal !== null) {
    let major = {} , minor = {};
    httpInternal.getResponseVersion(major, minor);
    if (major.value === 2)
      h2 = true;
  }
  let sts = gSSService.isSecureURI(Ci.nsISiteSecurityService.HEADER_HSTS, uri, 0);
  label.value = `${protocolVersion},${cipher}/${sslStatus.secretKeyLength}${mode},${pfs ? "FS" : "!FS"},${sts ? "STS" : "!STS"}${h2 ? ",H2" : ""}`;
  label.tooltipText = sslStatus.cipherName;

  label.collapsed = false;
};

function applyToWindow(modelWin) {
  let win = viewFor(modelWin);

  {
    // Add stylesheet.
    let style = win.document.createProcessingInstruction("xml-stylesheet", 'class="httpsinfo-node" href="' + self.data.url("httpsinfo.css") + '" type="text/css"')
    win.document.insertBefore(style, win.document.firstChild);
  }

  {
    // Add label to the URLBar.
    let label = win.document.createElement("label");
    label.setAttribute("id", "httpsinfo-label");
    label.setAttribute("class", "plain");
    label.collapsed = true;
    let identityBox = win.document.getElementById("identity-box");
    let identityLabels = win.document.getElementById("identity-icon-labels");
    identityBox.insertBefore(label, identityLabels);
  }

  win.gHTTPSInfoListener = new ProgressListener(win);
  win.gBrowser.addProgressListener(win.gHTTPSInfoListener);
}

function removeFromWindow(modelWin) {
  let win = viewFor(modelWin);
  if ("gHTTPSInfoListener" in win) {
    win.gBrowser.removeProgressListener(win.gHTTPSInfoListener);
    delete win["gHTTPSInfoListener"];
  }

  {
    let label = win.document.getElementById("httpsinfo-label");
    if (label !== null) {
      label.parentNode.removeChild(label);
    }
  }

  for (let child = win.document.firstChild; child !== null; child = child.nextSibling) {
    if (child.nodeType == child.PROCESSING_INSTRUCTION_NODE &&
        child.data.contains("httpsinfo-node")) {
      child.parentNode.removeChild(child);
    }
  }
}

exports.main = (function (options, callbacks) {
  for (let win of windows.browserWindows) {
    applyToWindow(win);
  }
  windows.browserWindows.on("open", function(win) {
    applyToWindow(win);
  });
  windows.browserWindows.on("close", function(win) {
    removeFromWindow(win);
  });
});

exports.onUnload = (function (reason) {
  for (let win of windows.browserWindows) {
    removeFromWindow(win);
  }
});
<commit_msg>triple equals<commit_after>/* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
"use strict";

let windows = require("sdk/windows");
let {viewFor} = require("sdk/view/core");
let self = require("sdk/self");
const {Cc, Ci} = require("chrome");

let gSSService = Cc["@mozilla.org/ssservice;1"].getService(Ci.nsISiteSecurityService);

function ProgressListener(win) {
  this._win = win;
  this._doneOne = false;
  this._lastState = 0;
  this._lastLocation = "";
}

ProgressListener.prototype.onSecurityChange = function(webProgress, request, state) {
  let uri = this._win.gBrowser.currentURI;
  if (this._doneOne && state === this._lastState && uri.spec === this._lastLocation)
    return;
  this._doneOne = true;
  this._lastState = state;
  this._lastLocation = uri.spec;
  let label = this._win.document.getElementById("httpsinfo-label");
  if (!(state & (Ci.nsIWebProgressListener.STATE_IS_SECURE | Ci.nsIWebProgressListener.STATE_IS_BROKEN))) {
    label.collapsed = true;
    return;
  }

  const nsISSLStatus = Ci.nsISSLStatus;
  let sslStatus = this._win.gBrowser.securityUI.SSLStatus;
  let protocolVersion;
  switch (sslStatus.protocolVersion) {
  case nsISSLStatus.TLS_VERSION_1:
    protocolVersion = "1.0";
    break;
  case nsISSLStatus.TLS_VERSION_1_1:
    protocolVersion = "1.1";
    break;
  case nsISSLStatus.TLS_VERSION_1_2:
    protocolVersion = "1.2";
    break;
  default:
    protocolVersion = "?";
    break;
  }
  let suite = sslStatus.cipherName;
  let pfs = suite.contains("DHE_");
  let cipher = suite.contains("_AES_") ? "AES" :
      (suite.contains("_RC4_") ? "RC4" :
       (suite.contains("_3DES_") ? "DES" : "?"));
  let mode = suite.contains("_GCM_") ? "/GCM" :
      (suite.contains("_CBC_") ? "/CBC" :
       (cipher === "RC4" ? "" : "/?"));
  let h2 = false;
  let httpInternal = request.QueryInterface(Ci.nsIHttpChannelInternal);
  if (httpInternal !== null) {
    let major = {} , minor = {};
    httpInternal.getResponseVersion(major, minor);
    if (major.value === 2)
      h2 = true;
  }
  let sts = gSSService.isSecureURI(Ci.nsISiteSecurityService.HEADER_HSTS, uri, 0);
  label.value = `${protocolVersion},${cipher}/${sslStatus.secretKeyLength}${mode},${pfs ? "FS" : "!FS"},${sts ? "STS" : "!STS"}${h2 ? ",H2" : ""}`;
  label.tooltipText = sslStatus.cipherName;

  label.collapsed = false;
};

function applyToWindow(modelWin) {
  let win = viewFor(modelWin);

  {
    // Add stylesheet.
    let style = win.document.createProcessingInstruction("xml-stylesheet", 'class="httpsinfo-node" href="' + self.data.url("httpsinfo.css") + '" type="text/css"')
    win.document.insertBefore(style, win.document.firstChild);
  }

  {
    // Add label to the URLBar.
    let label = win.document.createElement("label");
    label.setAttribute("id", "httpsinfo-label");
    label.setAttribute("class", "plain");
    label.collapsed = true;
    let identityBox = win.document.getElementById("identity-box");
    let identityLabels = win.document.getElementById("identity-icon-labels");
    identityBox.insertBefore(label, identityLabels);
  }

  win.gHTTPSInfoListener = new ProgressListener(win);
  win.gBrowser.addProgressListener(win.gHTTPSInfoListener);
}

function removeFromWindow(modelWin) {
  let win = viewFor(modelWin);
  if ("gHTTPSInfoListener" in win) {
    win.gBrowser.removeProgressListener(win.gHTTPSInfoListener);
    delete win["gHTTPSInfoListener"];
  }

  {
    let label = win.document.getElementById("httpsinfo-label");
    if (label !== null) {
      label.parentNode.removeChild(label);
    }
  }

  for (let child = win.document.firstChild; child !== null; child = child.nextSibling) {
    if (child.nodeType === child.PROCESSING_INSTRUCTION_NODE &&
        child.data.contains("httpsinfo-node")) {
      child.parentNode.removeChild(child);
    }
  }
}

exports.main = (function (options, callbacks) {
  for (let win of windows.browserWindows) {
    applyToWindow(win);
  }
  windows.browserWindows.on("open", function(win) {
    applyToWindow(win);
  });
  windows.browserWindows.on("close", function(win) {
    removeFromWindow(win);
  });
});

exports.onUnload = (function (reason) {
  for (let win of windows.browserWindows) {
    removeFromWindow(win);
  }
});
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var path = require('path');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var options = {};

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the fantabulous ' + chalk.red('Phase2') + ' generator!'
    ));
    options = _.assign({
      skipWelcome: true
    }, this.options);
  },

  prompting: function () {
    var done = this.async();
    var prompts = [];

    var gadgetPrompts = require('generator-gadget/lib/prompts.js');
    gadgetPrompts.forEach(function (item) {
      if (_.isUndefined(options[item])) {
        prompts.push(item);
      }
    });

    prompts.push({
      name: 'usePLS',
      type: 'confirm',
      message: 'Use Pattern Lab Starter?'
    });
    var plPrompts = require('generator-pattern-lab-starter/app/prompts.js');
    plPrompts.forEach(function (item) {
      if (_.isUndefined(options[item])) {
        var validate = item.when;
        item.when = function(answers) {
          return answers['usePLS'] && (!_.isFunction(validate) || validate());
        }
        prompts.push(item);
      }
    });

    // Minimally necessary prompt as a fallback if the other generators drop it.
    if (_.isUndefined(options.projectName)) {
      prompts.push({
        name: 'projectName',
        message: 'Machine name of project?',
        default: _.last(this.env.cwd.split('/')), // parent folder
        validate: function (input) {
          return (input.search(' ') === -1) ? true : 'No spaces allowed.';
        }
      });
    }

    // ensuring we only ask questions with the same `name` value once; earlier questions take priority
    prompts = _.uniq(prompts, 'name');

    this.prompt(prompts, function (props) {
      options = _.assign(options, props);
      options.themePath = 'src/themes/' + options.themeName;
      done();
    }.bind(this));

  },

  writing: function () {
    this.composeWith('gadget', {
      options: _.assign(options, {
        "use-master": true,
        themeScripts: {
          "compile-theme": "npm run compile",
          "validate": "npm run test"
        }
      })
    },
    {
      local: require.resolve('generator-gadget')
    });

    if (options.usePLS) {
      this.composeWith('pattern-lab-starter', { options: options }, {
        local: require.resolve('generator-pattern-lab-starter')
      });
    }
  },

  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }
});
<commit_msg>Pass required when callback argument to wrapped validation.<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var path = require('path');
var chalk = require('chalk');
var yosay = require('yosay');
var _ = require('lodash');
var options = {};

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the fantabulous ' + chalk.red('Phase2') + ' generator!'
    ));
    options = _.assign({
      skipWelcome: true
    }, this.options);
  },

  prompting: function () {
    var done = this.async();
    var prompts = [];

    var gadgetPrompts = require('generator-gadget/lib/prompts.js');
    gadgetPrompts.forEach(function (item) {
      if (_.isUndefined(options[item])) {
        prompts.push(item);
      }
    });

    prompts.push({
      name: 'usePLS',
      type: 'confirm',
      message: 'Use Pattern Lab Starter?'
    });
    var plPrompts = require('generator-pattern-lab-starter/app/prompts.js');
    plPrompts.forEach(function (item) {
      if (_.isUndefined(options[item])) {
        var validate = item.when;
        item.when = function(answers) {
          return answers['usePLS'] && (!_.isFunction(validate) || validate(answers));
        }
        prompts.push(item);
      }
    });

    // Minimally necessary prompt as a fallback if the other generators drop it.
    if (_.isUndefined(options.projectName)) {
      prompts.push({
        name: 'projectName',
        message: 'Machine name of project?',
        default: _.last(this.env.cwd.split('/')), // parent folder
        validate: function (input) {
          return (input.search(' ') === -1) ? true : 'No spaces allowed.';
        }
      });
    }

    // ensuring we only ask questions with the same `name` value once; earlier questions take priority
    prompts = _.uniq(prompts, 'name');

    this.prompt(prompts, function (props) {
      options = _.assign(options, props);
      options.themePath = 'src/themes/' + options.themeName;
      done();
    }.bind(this));

  },

  writing: function () {
    this.composeWith('gadget', {
      options: _.assign(options, {
        "use-master": true,
        themeScripts: {
          "compile-theme": "npm run compile",
          "validate": "npm run test"
        }
      })
    },
    {
      local: require.resolve('generator-gadget')
    });

    if (options['usePLS']) {
      this.composeWith('pattern-lab-starter', { options: options }, {
        local: require.resolve('generator-pattern-lab-starter')
      });
    }
  },

  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }
});
<|endoftext|>


<commit_before>// domo.js 0.5.3

// (c) 2012 Jed Schmidt
// domo.js is distributed under the MIT license.
// For more details, see http://domo-js.com

!function() {
  // Determine the global object.
  var global = Function("return this")()

  // Valid HTML5 tag names used to generate DOM functions.
  var tags = [
    "A", "ABBR", "ACRONYM", "ADDRESS", "AREA", "ARTICLE", "ASIDE", "AUDIO",
    "B", "BDI", "BDO", "BIG", "BLOCKQUOTE", "BODY", "BR", "BUTTON",
    "CANVAS", "CAPTION", "CITE", "CODE", "COL", "COLGROUP", "COMMAND",
    "DATALIST", "DD", "DEL", "DETAILS", "DFN", "DIV", "DL", "DT", "EM",
    "EMBED", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "FORM", "FRAME",
    "FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6", "HEAD", "HEADER",
    "HGROUP", "HR", "HTML", "I", "IFRAME", "IMG", "INPUT", "INS", "KBD",
    "KEYGEN", "LABEL", "LEGEND", "LI", "LINK", "MAP", "MARK", "META",
    "METER", "NAV", "NOSCRIPT", "OBJECT", "OL", "OPTGROUP", "OPTION",
    "OUTPUT", "P", "PARAM", "PRE", "PROGRESS", "Q", "RP", "RT", "RUBY",
    "SAMP", "SCRIPT", "SECTION", "SELECT", "SMALL", "SOURCE", "SPAN",
    "SPLIT", "STRONG", "STYLE", "SUB", "SUMMARY", "SUP", "TABLE", "TBODY",
    "TD", "TEXTAREA", "TFOOT", "TH", "THEAD", "TIME", "TITLE", "TR",
    "TRACK", "TT", "UL", "VAR", "VIDEO", "WBR"
  ]

  // Turn a camelCase string into a hyphenated one.
  // Used for CSS property names and DOM element attributes.
  function hyphenify(text) {
    return text.replace(/[A-Z]/g, "-$&").toLowerCase()
  }

  // Cache select Array/Object methods
  var unshift = Array.prototype.unshift
  var concat = Array.prototype.concat
  var has = Object.prototype.hasOwnProperty

  // Export the Domo constructor for a CommonJS environment,
  // or create a new Domo namespace otherwise.
  typeof module == "object"
    ? module.exports = Domo
    : new Domo(global.document).global(true)

  // Create a new domo namespace, scoped to the given document.
  function Domo(document) {
    if (!document) throw new Error("No document provided.")

    this.domo = this

    // Create a DOM comment
    this.COMMENT = function(nodeValue) {
      return document.createComment(nodeValue)
    }

    // Create a DOM text node
    this.TEXT = function(nodeValue) {
      return document.createTextNode(nodeValue)
    }

    // Create a DOM fragment
    this.FRAGMENT = function() {
      var fragment = document.createDocumentFragment()
      var childNodes = concat.apply([], arguments)
      var length = childNodes.length
      var i = 0
      var child

      while (i < length) {
        child = childNodes[i++]

        while (typeof child == "function") child = child()

        if (!child) child = this.COMMENT(child)

        else if (!child.nodeType) child = this.TEXT(child)

        fragment.appendChild(child)
      }

      return fragment
    }

    // Create a DOM element
    this.ELEMENT = function() {
      var childNodes = concat.apply([], arguments)
      var nodeName = childNodes.shift()
      var element = document.createElement(nodeName)
      var attributes = childNodes[0]

      if (attributes) {
        if (typeof attributes == "object" && !attributes.nodeType) {
          for (var name in attributes) if (has.call(attributes, name)) {
            element.setAttribute(hyphenify(name), attributes[name])
          }

          childNodes.shift()
        }
      }

      element.appendChild(
        this.FRAGMENT.apply(this, childNodes)
      )

      switch (nodeName) {
        case "HTML":
        case "HEAD":
        case "BODY":
          var replaced = document.getElementsByTagName(nodeName)[0]

          if (replaced) replaced.parentNode.replaceChild(element, replaced)
      }

      return element
    }

    // Convenience functions to create each HTML5 element
    var i = tags.length
    while (i--) !function(domo, nodeName) {
      domo[nodeName] =
      domo[nodeName.toLowerCase()] =

      function() {
        unshift.call(arguments, nodeName)
        return domo.ELEMENT.apply(domo, arguments)
      }
    }(this, tags[i])

    // Create a CSS style rule
    this.STYLE.on = function() {
      var rules = concat.apply([], arguments)
      var selector = rules[0]
      var css = selector + "{"
      var i = 1
      var l = rules.length
      var key
      var block

      while (i < l) {
        block = rules[i++]

        switch (typeof block) {
          case "object":
            for (key in block) {
              css += hyphenify(key) + ":" + block[key]

              if (typeof block[key] == "number") css += "px"

              css += ";"
            }
            break

          case "string":
            css = selector + " " + block + css
            break
        }
      }

      css += "}\n"

      return css
    }

    // Pollute the global scope for convenience.
    this.global = function(on) {
      var values = this.global.values
      var key
      var code

      if (on !== false) {
        global.domo = this

        for (key in this) {
          code = key.charCodeAt(0)

          if (code < 65 || code > 90) continue

          if (this[key] == global[key]) continue

          if (key in global) values[key] = global[key]

          global[key] = this[key]
        }
      }

      else {
        delete global.domo

        for (key in this) {
          if (key in values) {
            if (global[key] == this[key]) global[key] = values[key]
          }

          else delete global[key]
        }
      }

      return this
    }

    // A place to store previous global properties
    this.global.values = {}
  }
}()
<commit_msg>bump version<commit_after>// domo.js 0.5.4

// (c) 2012 Jed Schmidt
// domo.js is distributed under the MIT license.
// For more details, see http://domo-js.com

!function() {
  // Determine the global object.
  var global = Function("return this")()

  // Valid HTML5 tag names used to generate DOM functions.
  var tags = [
    "A", "ABBR", "ACRONYM", "ADDRESS", "AREA", "ARTICLE", "ASIDE", "AUDIO",
    "B", "BDI", "BDO", "BIG", "BLOCKQUOTE", "BODY", "BR", "BUTTON",
    "CANVAS", "CAPTION", "CITE", "CODE", "COL", "COLGROUP", "COMMAND",
    "DATALIST", "DD", "DEL", "DETAILS", "DFN", "DIV", "DL", "DT", "EM",
    "EMBED", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "FORM", "FRAME",
    "FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6", "HEAD", "HEADER",
    "HGROUP", "HR", "HTML", "I", "IFRAME", "IMG", "INPUT", "INS", "KBD",
    "KEYGEN", "LABEL", "LEGEND", "LI", "LINK", "MAP", "MARK", "META",
    "METER", "NAV", "NOSCRIPT", "OBJECT", "OL", "OPTGROUP", "OPTION",
    "OUTPUT", "P", "PARAM", "PRE", "PROGRESS", "Q", "RP", "RT", "RUBY",
    "SAMP", "SCRIPT", "SECTION", "SELECT", "SMALL", "SOURCE", "SPAN",
    "SPLIT", "STRONG", "STYLE", "SUB", "SUMMARY", "SUP", "TABLE", "TBODY",
    "TD", "TEXTAREA", "TFOOT", "TH", "THEAD", "TIME", "TITLE", "TR",
    "TRACK", "TT", "UL", "VAR", "VIDEO", "WBR"
  ]

  // Turn a camelCase string into a hyphenated one.
  // Used for CSS property names and DOM element attributes.
  function hyphenify(text) {
    return text.replace(/[A-Z]/g, "-$&").toLowerCase()
  }

  // Cache select Array/Object methods
  var unshift = Array.prototype.unshift
  var concat = Array.prototype.concat
  var has = Object.prototype.hasOwnProperty

  // Export the Domo constructor for a CommonJS environment,
  // or create a new Domo namespace otherwise.
  typeof module == "object"
    ? module.exports = Domo
    : new Domo(global.document).global(true)

  // Create a new domo namespace, scoped to the given document.
  function Domo(document) {
    if (!document) throw new Error("No document provided.")

    this.domo = this

    // Create a DOM comment
    this.COMMENT = function(nodeValue) {
      return document.createComment(nodeValue)
    }

    // Create a DOM text node
    this.TEXT = function(nodeValue) {
      return document.createTextNode(nodeValue)
    }

    // Create a DOM fragment
    this.FRAGMENT = function() {
      var fragment = document.createDocumentFragment()
      var childNodes = concat.apply([], arguments)
      var length = childNodes.length
      var i = 0
      var child

      while (i < length) {
        child = childNodes[i++]

        while (typeof child == "function") child = child()

        if (!child) child = this.COMMENT(child)

        else if (!child.nodeType) child = this.TEXT(child)

        fragment.appendChild(child)
      }

      return fragment
    }

    // Create a DOM element
    this.ELEMENT = function() {
      var childNodes = concat.apply([], arguments)
      var nodeName = childNodes.shift()
      var element = document.createElement(nodeName)
      var attributes = childNodes[0]

      if (attributes) {
        if (typeof attributes == "object" && !attributes.nodeType) {
          for (var name in attributes) if (has.call(attributes, name)) {
            element.setAttribute(hyphenify(name), attributes[name])
          }

          childNodes.shift()
        }
      }

      element.appendChild(
        this.FRAGMENT.apply(this, childNodes)
      )

      switch (nodeName) {
        case "HTML":
        case "HEAD":
        case "BODY":
          var replaced = document.getElementsByTagName(nodeName)[0]

          if (replaced) replaced.parentNode.replaceChild(element, replaced)
      }

      return element
    }

    // Convenience functions to create each HTML5 element
    var i = tags.length
    while (i--) !function(domo, nodeName) {
      domo[nodeName] =
      domo[nodeName.toLowerCase()] =

      function() {
        unshift.call(arguments, nodeName)
        return domo.ELEMENT.apply(domo, arguments)
      }
    }(this, tags[i])

    // Create a CSS style rule
    this.STYLE.on = function() {
      var rules = concat.apply([], arguments)
      var selector = rules[0]
      var css = selector + "{"
      var i = 1
      var l = rules.length
      var key
      var block

      while (i < l) {
        block = rules[i++]

        switch (typeof block) {
          case "object":
            for (key in block) {
              css += hyphenify(key) + ":" + block[key]

              if (typeof block[key] == "number") css += "px"

              css += ";"
            }
            break

          case "string":
            css = selector + " " + block + css
            break
        }
      }

      css += "}\n"

      return css
    }

    // Pollute the global scope for convenience.
    this.global = function(on) {
      var values = this.global.values
      var key
      var code

      if (on !== false) {
        global.domo = this

        for (key in this) {
          code = key.charCodeAt(0)

          if (code < 65 || code > 90) continue

          if (this[key] == global[key]) continue

          if (key in global) values[key] = global[key]

          global[key] = this[key]
        }
      }

      else {
        delete global.domo

        for (key in this) {
          if (key in values) {
            if (global[key] == this[key]) global[key] = values[key]
          }

          else delete global[key]
        }
      }

      return this
    }

    // A place to store previous global properties
    this.global.values = {}
  }
}()
<|endoftext|>