<commit_before>// including plugins
var gulp = require('gulp'),
    htmlmin = require("gulp-htmlmin"),
    minifyCss = require("gulp-minify-css"),
    uglify = require("gulp-uglify"),
    replace = require("gulp-replace"),
    clean = require("gulp-clean"),
    debug = require("gulp-debug"),
    pjson = require('./package.json');

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

gulp.task('minify-html', ['clean'], function () {
    return gulp.src('./public/*.html') // path to your files
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('copy-html-templates', ['clean'], function () {
    return gulp.src('./public/scripts/app/templates/*')
        .pipe(gulp.dest('dist/scripts/app/templates'));
})

gulp.task('minify-css', ['clean'], function () {
    return gulp.src('./public/**/*.css') // path to your files
        .pipe(minifyCss())
        .pipe(gulp.dest('dist'));
});

gulp.task('minify-js', ['clean'], function () {
    return gulp.src(['./public/**/*.js', '!./public/scripts/app/siteconfig.js', '!./public/**/*.min.js']) // path to your files
        .pipe(debug({title: 'minifying:'}))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('images', ['clean'], function () {
    return gulp.src(['./public/**/*.{png,jpg,gif,svg}'])
        .pipe(gulp.dest('dist'));
});

gulp.task('siteconfig-pubstorm', ['minify-js'], function () {
    return gulp.src('./public/scripts/app/siteconfig.js')
        .pipe(replace('return ConfigGnuLorienDev;', 'return ConfigPubstorm;'))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist/scripts/app'));
});

gulp.task('siteconfig-patron', ['minify-js'], function () {
    return gulp.src('./public/scripts/app/siteconfig.js')
        .pipe(replace('return ConfigGnuLorienDev;', 'return ConfigPatron;'))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist/scripts/app'));
});

gulp.task('appbust', ['minify-js'], function () {
    return gulp.src('./public/scripts/app.js')
        .pipe(replace('bust=010101', 'bust=' + pjson.version))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist/scripts'));
});

gulp.task('indexbust', ['minify-html'], function () {
    return gulp.src('./public/index.html')
        .pipe(replace('require.js?bust=010101', 'require.js?bust=' + pjson.version))
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest('dist'));
})

gulp.task('pubstorm', ['minify-html', 'copy-html-templates', 'minify-css', 'images', 'siteconfig-pubstorm', 'appbust', 'indexbust']);

gulp.task('patron', ['minify-html', 'copy-html-templates', 'minify-css', 'images', 'siteconfig-patron', 'appbust', 'indexbust']);
<commit_msg>Copy new print templates to dist<commit_after>// including plugins
var gulp = require('gulp'),
    htmlmin = require("gulp-htmlmin"),
    minifyCss = require("gulp-minify-css"),
    uglify = require("gulp-uglify"),
    replace = require("gulp-replace"),
    clean = require("gulp-clean"),
    debug = require("gulp-debug"),
    pjson = require('./package.json');

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

gulp.task('minify-html', ['clean'], function () {
    return gulp.src('./public/*.html') // path to your files
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('copy-html-templates', ['clean'], function () {
    return gulp.src('./public/scripts/app/templates/*')
        .pipe(gulp.dest('dist/scripts/app/templates'));
})

gulp.task('copy-print-templates', ['clean'], function () {
    return gulp.src('./public/scripts/app/templates/print/*')
        .pipe(gulp.dest('dist/scripts/app/templates/print'));
})

gulp.task('minify-css', ['clean'], function () {
    return gulp.src('./public/**/*.css') // path to your files
        .pipe(minifyCss())
        .pipe(gulp.dest('dist'));
});

gulp.task('minify-js', ['clean'], function () {
    return gulp.src(['./public/**/*.js', '!./public/scripts/app/siteconfig.js', '!./public/**/*.min.js']) // path to your files
        .pipe(debug({title: 'minifying:'}))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('images', ['clean'], function () {
    return gulp.src(['./public/**/*.{png,jpg,gif,svg}'])
        .pipe(gulp.dest('dist'));
});

gulp.task('siteconfig-pubstorm', ['minify-js'], function () {
    return gulp.src('./public/scripts/app/siteconfig.js')
        .pipe(replace('return ConfigGnuLorienDev;', 'return ConfigPubstorm;'))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist/scripts/app'));
});

gulp.task('siteconfig-patron', ['minify-js'], function () {
    return gulp.src('./public/scripts/app/siteconfig.js')
        .pipe(replace('return ConfigGnuLorienDev;', 'return ConfigPatron;'))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist/scripts/app'));
});

gulp.task('appbust', ['minify-js'], function () {
    return gulp.src('./public/scripts/app.js')
        .pipe(replace('bust=010101', 'bust=' + pjson.version))
        .pipe(uglify({outSourceMap: true}))
        .pipe(gulp.dest('dist/scripts'));
});

gulp.task('indexbust', ['minify-html'], function () {
    return gulp.src('./public/index.html')
        .pipe(replace('require.js?bust=010101', 'require.js?bust=' + pjson.version))
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest('dist'));
})

gulp.task('pubstorm', ['minify-html', 'copy-print-templates', 'copy-html-templates', 'minify-css', 'images', 'siteconfig-pubstorm', 'appbust', 'indexbust']);

gulp.task('patron', ['minify-html', 'copy-print-templates', 'copy-html-templates', 'minify-css', 'images', 'siteconfig-patron', 'appbust', 'indexbust']);
<|endoftext|>


<commit_before>// enable debug for gulp
process.env.DEBUG = process.env.DEBUG || 'freecc:*';

require('babel-core/register');
var Rx = require('rx'),
  gulp = require('gulp'),
  path = require('path'),

  // utils
  plumber = require('gulp-plumber'),
  notify = require('gulp-notify'),
  gutil = require('gulp-util'),
  reduce = require('gulp-reduce-file'),
  sortKeys = require('sort-keys'),
  debug = require('debug')('freecc:gulp'),
  yargs = require('yargs'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify'),
  merge = require('merge-stream'),
  babel = require('gulp-babel'),
  sourcemaps = require('gulp-sourcemaps'),

  // react app
  webpack = require('webpack-stream'),
  webpackConfig = require('./webpack.config.js'),
  webpackConfigNode = require('./webpack.config.node.js'),

  // server process
  nodemon = require('gulp-nodemon'),
  sync = require('browser-sync'),

  // css
  less = require('gulp-less'),

  // rev
  rev = require('gulp-rev'),
  revReplace = require('gulp-rev-replace'),
  revDel = require('rev-del'),

  // lint
  jsonlint = require('gulp-jsonlint'),
  eslint = require('gulp-eslint'),

  // unit-tests
  tape = require('gulp-tape'),
  tapSpec = require('tap-spec');

Rx.config.longStackSupport = true;

var __DEV__ = !yargs.argv.p;
var reloadDelay = 1000;
var reload = sync.reload;
var paths = {
  server: './server/server.js',
  serverIgnore: [
    'gulpfile.js',
    'public/',
    '!public/js/bundle*',
    'node_modules/',
    'client/',
    'seed',
    'server/manifests/*.json',
    'server/rev-manifest.json'
  ],

  publicJs: './public/js',
  css: 'public/css',

  loopback: {
    client: './client/loopbackClient',
    root: path.join(__dirname, 'client/'),
    clientName: 'lbApp'
  },

  client: {
    src: './client',
    dest: 'public/js'
  },

  vendorChallenges: [
    'public/bower_components/jshint/dist/jshint.js',
    'public/bower_components/chai/chai.js',
    'public/bower_components/CodeMirror/lib/codemirror.js',
    'public/bower_components/CodeMirror/addon/edit/closebrackets.js',
    'public/bower_components/CodeMirror/addon/edit/matchbrackets.js',
    'public/bower_components/CodeMirror/addon/lint/lint.js',
    'public/bower_components/CodeMirror/addon/lint/javascript-lint.js',
    'public/bower_components/CodeMirror/mode/javascript/javascript.js',
    'public/bower_components/CodeMirror/mode/xml/xml.js',
    'public/bower_components/CodeMirror/mode/css/css.js',
    'public/bower_components/CodeMirror/mode/htmlmixed/htmlmixed.js',
    'node_modules/emmet-codemirror/dist/emmet.js',
    'public/js/lib/loop-protect/loop-protect.js'
  ],

  vendorMain: [
    'public/bower_components/jquery/dist/jquery.min.js',
    'public/bower_components/bootstrap/dist/js/bootstrap.min.js',
    'public/bower_components/d3/d3.min.js',
    'public/bower_components/moment/min/moment.min.js',
    'public/bower_components/lightbox2/dist/js/lightbox.min.js',
    'public/bower_components/rxjs/dist/rx.all.min.js'
  ],

  js: [
    'client/main.js',
    'client/iFrameScripts.js',
    'client/plugin.js'
  ],

  commonFramework: [
    'init',
    'bindings',
    'add-test-to-string',
    'code-storage',
    'code-uri',
    'add-loop-protect',
    'get-iframe',
    'update-preview',
    'create-editor',
    'detect-unsafe-code-stream',
    'display-test-results',
    'execute-challenge-stream',
    'output-display',
    'phone-scroll-lock',
    'report-issue',
    'run-tests-stream',
    'show-completion',
    'step-challenge',
    'end'
  ],

  less: './client/less/main.less',
  lessFiles: './client/less/*.less',

  manifest: 'server/manifests/',

  node: {
    src: './client',
    dest: 'common/app'
  },

  syncWatch: [
    'public/**/*.*'
  ],

  challenges: [
    'seed/challenges/*/*.json'
  ]
};

var webpackOptions = {
  devtool: 'inline-source-map'
};

function formatCommonFrameworkPaths() {
  return this.map(function(script) {
    return 'client/commonFramework/' + script + '.js';
  });
}

function errorHandler() {
  var args = Array.prototype.slice.call(arguments);

  // Send error to notification center with gulp-notify
  notify.onError({
    title: 'Compile Error',
    message: '<%= error %>'
  }).apply(this, args);

  // Keep gulp from hanging on this task
  this.emit('end');
}

function delRev(dest, manifestName) {
  // in production do not delete old revisions
  if (!__DEV__) {
    return gutil.noop();
  }
  return revDel({
    oldManifest: path.join(paths.manifest, manifestName),
    dest: dest
  });
}

gulp.task('serve', ['build-manifest'], function(cb) {
  var called = false;
  nodemon({
    script: paths.server,
    ext: '.jsx .js .json',
    ignore: paths.serverIgnore,
    exec: path.join(__dirname, 'node_modules/.bin/babel-node'),
    env: {
      'NODE_ENV': 'development',
      'DEBUG': process.env.DEBUG || 'freecc:*'
    }
  })
    .on('start', function() {
      if (!called) {
        called = true;
        setTimeout(function() {
          cb();
        }, reloadDelay);
      }
    })
    .on('restart', function(files) {
      if (files) {
        debug('Files that changes: ', files);
      }
      setTimeout(function() {
        debug('Restarting browsers');
        reload();
      }, reloadDelay);
    });
});

var syncDepenedents = [
  'serve',
  'js',
  'less',
  'dependents',
  'pack-watch',
  'build-manifest'
];

gulp.task('sync', syncDepenedents, function() {
  sync.init(null, {
    proxy: 'http://localhost:3000',
    logLeval: 'debug',
    files: paths.syncWatch,
    port: 3001,
    open: false,
    reloadDelay: reloadDelay
  });
});

gulp.task('lint-js', function() {
  return gulp.src([
    'common/**/*.js',
    'common/**/*.jsx',
    'client/**/*.js',
    'client/**/*.jsx',
    'server/**/*.js',
    'config/**/*.js'
  ])
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('lint-json', function() {
  return gulp.src(paths.challenges)
    .pipe(jsonlint())
    .pipe(jsonlint.reporter());
});

gulp.task('test-challenges', ['lint-json']);

gulp.task('pack-client', function() {
  if (!__DEV__) { console.log('\n\nbundling production\n\n'); }

  var manifestName = 'react-manifest.json';
  var dest = webpackConfig.output.path;

  return gulp.src(webpackConfig.entry)
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(webpack(Object.assign(
      {},
      webpackConfig,
      webpackOptions
    )))
    .pipe(__DEV__ ? gutil.noop() : uglify())
    .pipe(gulp.dest(dest))
    .pipe(rev())
    // copy files to public
    .pipe(gulp.dest(dest))
    // create manifest
    .pipe(rev.manifest(manifestName))
    // delete old rev
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

var defaultStatsOptions = {
  colors: gutil.colors.supportsColor,
  hash: false,
  timings: false,
  chunks: false,
  chunkModules: false,
  modules: false,
  children: true,
  version: true,
  cached: false,
  cachedAssets: false,
  reasons: false,
  source: false,
  errorDetails: false
};

var webpackCalled = false;
gulp.task('pack-watch', function(cb) {
  if (webpackCalled) {
    console.log('webpack watching already runnning');
    return cb();
  }
  gulp.src(webpackConfig.entry)
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(webpack(Object.assign(
      {},
      webpackConfig,
      webpackOptions,
      { watch: true }
    ), null, function(notUsed, stats) {
      if (stats) {
        gutil.log(stats.toString(defaultStatsOptions));
      }

      if (!webpackCalled) {
        debug('webpack init completed');
        webpackCalled = true;
        cb();
      }

    }))
    .pipe(gulp.dest(webpackConfig.output.path));
});

gulp.task('pack-watch-manifest', ['pack-watch'], function() {
  var manifestName = 'react-manifest.json';
  var dest = webpackConfig.output.path;
  return gulp.src(dest + '/bundle.js')
    .pipe(rev())
    // copy files to public
    .pipe(gulp.dest(dest))
    // create manifest
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

gulp.task('pack-node', function() {
  return gulp.src(webpackConfigNode.entry)
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(webpack(webpackConfigNode))
    .pipe(gulp.dest(webpackConfigNode.output.path));
});

gulp.task('pack', ['pack-client', 'pack-node']);

gulp.task('less', function() {
  var manifestName = 'css-manifest.json';
  var dest = paths.css;
  return gulp.src(paths.less)
    .pipe(plumber({ errorHandler: errorHandler }))
    // compile
    .pipe(less({
      paths: [ path.join(__dirname, 'less', 'includes') ]
    }))
    .pipe(gulp.dest(dest))
    // add revision
    .pipe(rev())
    // copy files to public
    .pipe(gulp.dest(dest))
    // create and merge manifest
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

function getFilesGlob(files) {
  if (!__DEV__) {
    return files;
  }
  return files.map(function(file) {
    return file
      .replace('.min.', '.')
      // moment breaks the pattern
      .replace('/min/', '/');
  });
}

gulp.task('js', function() {
  var manifestName = 'js-manifest.json';
  var dest = paths.publicJs;

  var jsFiles = merge(

    gulp.src(getFilesGlob(paths.vendorMain))
      .pipe(__DEV__ ? sourcemaps.init() : gutil.noop())
      .pipe(concat('vendor-main.js'))
      .pipe(
        __DEV__ ?
          sourcemaps.write({ sourceRoot: '/vendor' }) :
          gutil.noop()
      ),

    gulp.src(paths.vendorChallenges)
      .pipe(__DEV__ ? sourcemaps.init() : gutil.noop())
      .pipe(__DEV__ ? gutil.noop() : uglify())
      .pipe(concat('vendor-challenges.js'))
      .pipe(
        __DEV__ ?
          sourcemaps.write({ sourceRoot: '/vendor' }) :
          gutil.noop()
      ),

    gulp.src(paths.js)
      .pipe(plumber({ errorHandler: errorHandler }))
      .pipe(babel())
      .pipe(__DEV__ ? gutil.noop() : uglify())
  );

  return jsFiles
    .pipe(gulp.dest(dest))
    // create registry file
    .pipe(rev())
    // copy revisioned assets to dest
    .pipe(gulp.dest(dest))
    // create manifest file
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    // copy manifest file to dest
    .pipe(gulp.dest(paths.manifest));
});

// commonFramework depend on iFrameScripts
// and faux.js
gulp.task('dependents', ['js'], function() {
  var manifestName = 'dependents-manifest.json';
  var dest = paths.publicJs;

  var manifest = gulp.src(
    path.join(__dirname, paths.manifest, 'js-manifest.json')
  );

  return gulp.src(formatCommonFrameworkPaths.call(paths.commonFramework))
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(babel())
    .pipe(__DEV__ ? sourcemaps.init() : gutil.noop())
    .pipe(concat('commonFramework.js'))
    .pipe(
      __DEV__ ?
        sourcemaps.write({ sourceRoot: '/commonFramework' }) :
        gutil.noop()
    )
    .pipe(__DEV__ ? gutil.noop() : uglify())
    .pipe(revReplace({ manifest: manifest }))
    .pipe(gulp.dest(dest))
    .pipe(rev())
    .pipe(gulp.dest(dest))
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

function collector(file, memo) {
  return Object.assign({}, JSON.parse(file.contents), memo);
}

function done(manifest) {
  return sortKeys(manifest);
}

function buildManifest() {
  return gulp.src(paths.manifest + '*.json')
    .pipe(reduce('rev-manifest.json', collector, done, {}))
    .pipe(gulp.dest('server/'));
}

var buildDependents = ['less', 'js', 'dependents'];

if (__DEV__) {
  buildDependents.push('pack-watch-manifest');
}

gulp.task('build-manifest', buildDependents, function() {
  return buildManifest();
});

gulp.task('build-manifest-watch', function() {
  return buildManifest();
});

gulp.task('build', [
  'less',
  'js',
  'dependents',
  'pack-client',
  'build-manifest'
]);

var watchDependents = [
  'less',
  'js',
  'dependents',
  'serve',
  'sync',
  'pack-watch',
  'pack-watch-manifest',
  'build-manifest'
];

gulp.task('reload', function() {
  notify({ message: 'test changed' });
  reload();
});

gulp.task('watch', watchDependents, function() {
  gulp.watch(paths.lessFiles, ['less']);
  gulp.watch(paths.js.concat(paths.vendorChallenges), ['js']);
  gulp.watch(paths.challenges, ['test-challenges', 'reload']);
  gulp.watch(paths.js, ['js', 'dependents']);
  gulp.watch(
    formatCommonFrameworkPaths.call(paths.commonFramework),
    ['dependents']
  );
  gulp.watch(paths.manifest + '/*.json', ['build-manifest-watch']);
  gulp.watch(webpackConfig.output.path + '/bundle.js', ['pack-watch-manifest']);
});

gulp.task('default', [
  'less',
  'serve',
  'pack-watch',
  'pack-watch-manifest',
  'build-manifest-watch',
  'watch',
  'sync'
]);

gulp.task('test', function() {
  return gulp.src('test/**/*.js')
    .pipe(tape({
      reporter: tapSpec()
    }));
});
<commit_msg>Add less source maps Watch bootstrap less files<commit_after>// enable debug for gulp
process.env.DEBUG = process.env.DEBUG || 'freecc:*';

require('babel-core/register');
var Rx = require('rx'),
  gulp = require('gulp'),
  path = require('path'),

  // utils
  plumber = require('gulp-plumber'),
  notify = require('gulp-notify'),
  gutil = require('gulp-util'),
  reduce = require('gulp-reduce-file'),
  sortKeys = require('sort-keys'),
  debug = require('debug')('freecc:gulp'),
  yargs = require('yargs'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify'),
  merge = require('merge-stream'),
  babel = require('gulp-babel'),
  sourcemaps = require('gulp-sourcemaps'),

  // react app
  webpack = require('webpack-stream'),
  webpackConfig = require('./webpack.config.js'),
  webpackConfigNode = require('./webpack.config.node.js'),

  // server process
  nodemon = require('gulp-nodemon'),
  sync = require('browser-sync'),

  // css
  less = require('gulp-less'),

  // rev
  rev = require('gulp-rev'),
  revReplace = require('gulp-rev-replace'),
  revDel = require('rev-del'),

  // lint
  jsonlint = require('gulp-jsonlint'),
  eslint = require('gulp-eslint'),

  // unit-tests
  tape = require('gulp-tape'),
  tapSpec = require('tap-spec');

Rx.config.longStackSupport = true;

var __DEV__ = !yargs.argv.p;
var reloadDelay = 1000;
var reload = sync.reload;
var paths = {
  server: './server/server.js',
  serverIgnore: [
    'gulpfile.js',
    'public/',
    '!public/js/bundle*',
    'node_modules/',
    'client/',
    'seed',
    'server/manifests/*.json',
    'server/rev-manifest.json'
  ],

  publicJs: './public/js',
  css: 'public/css',

  loopback: {
    client: './client/loopbackClient',
    root: path.join(__dirname, 'client/'),
    clientName: 'lbApp'
  },

  client: {
    src: './client',
    dest: 'public/js'
  },

  vendorChallenges: [
    'public/bower_components/jshint/dist/jshint.js',
    'public/bower_components/chai/chai.js',
    'public/bower_components/CodeMirror/lib/codemirror.js',
    'public/bower_components/CodeMirror/addon/edit/closebrackets.js',
    'public/bower_components/CodeMirror/addon/edit/matchbrackets.js',
    'public/bower_components/CodeMirror/addon/lint/lint.js',
    'public/bower_components/CodeMirror/addon/lint/javascript-lint.js',
    'public/bower_components/CodeMirror/mode/javascript/javascript.js',
    'public/bower_components/CodeMirror/mode/xml/xml.js',
    'public/bower_components/CodeMirror/mode/css/css.js',
    'public/bower_components/CodeMirror/mode/htmlmixed/htmlmixed.js',
    'node_modules/emmet-codemirror/dist/emmet.js',
    'public/js/lib/loop-protect/loop-protect.js'
  ],

  vendorMain: [
    'public/bower_components/jquery/dist/jquery.min.js',
    'public/bower_components/bootstrap/dist/js/bootstrap.min.js',
    'public/bower_components/d3/d3.min.js',
    'public/bower_components/moment/min/moment.min.js',
    'public/bower_components/lightbox2/dist/js/lightbox.min.js',
    'public/bower_components/rxjs/dist/rx.all.min.js'
  ],

  js: [
    'client/main.js',
    'client/iFrameScripts.js',
    'client/plugin.js'
  ],

  commonFramework: [
    'init',
    'bindings',
    'add-test-to-string',
    'code-storage',
    'code-uri',
    'add-loop-protect',
    'get-iframe',
    'update-preview',
    'create-editor',
    'detect-unsafe-code-stream',
    'display-test-results',
    'execute-challenge-stream',
    'output-display',
    'phone-scroll-lock',
    'report-issue',
    'run-tests-stream',
    'show-completion',
    'step-challenge',
    'end'
  ],

  less: './client/less/main.less',
  lessFiles: './client/less/**/*.less',

  manifest: 'server/manifests/',

  node: {
    src: './client',
    dest: 'common/app'
  },

  syncWatch: [
    'public/**/*.*'
  ],

  challenges: [
    'seed/challenges/*/*.json'
  ]
};

var webpackOptions = {
  devtool: 'inline-source-map'
};

function formatCommonFrameworkPaths() {
  return this.map(function(script) {
    return 'client/commonFramework/' + script + '.js';
  });
}

function errorHandler() {
  var args = Array.prototype.slice.call(arguments);

  // Send error to notification center with gulp-notify
  notify.onError({
    title: 'Compile Error',
    message: '<%= error %>'
  }).apply(this, args);

  // Keep gulp from hanging on this task
  this.emit('end');
}

function delRev(dest, manifestName) {
  // in production do not delete old revisions
  if (!__DEV__) {
    return gutil.noop();
  }
  return revDel({
    oldManifest: path.join(paths.manifest, manifestName),
    dest: dest
  });
}

gulp.task('serve', ['build-manifest'], function(cb) {
  var called = false;
  nodemon({
    script: paths.server,
    ext: '.jsx .js .json',
    ignore: paths.serverIgnore,
    exec: path.join(__dirname, 'node_modules/.bin/babel-node'),
    env: {
      'NODE_ENV': 'development',
      'DEBUG': process.env.DEBUG || 'freecc:*'
    }
  })
    .on('start', function() {
      if (!called) {
        called = true;
        setTimeout(function() {
          cb();
        }, reloadDelay);
      }
    })
    .on('restart', function(files) {
      if (files) {
        debug('Files that changes: ', files);
      }
      setTimeout(function() {
        debug('Restarting browsers');
        reload();
      }, reloadDelay);
    });
});

var syncDepenedents = [
  'serve',
  'js',
  'less',
  'dependents',
  'pack-watch',
  'build-manifest'
];

gulp.task('sync', syncDepenedents, function() {
  sync.init(null, {
    proxy: 'http://localhost:3000',
    logLeval: 'debug',
    files: paths.syncWatch,
    port: 3001,
    open: false,
    reloadDelay: reloadDelay
  });
});

gulp.task('lint-js', function() {
  return gulp.src([
    'common/**/*.js',
    'common/**/*.jsx',
    'client/**/*.js',
    'client/**/*.jsx',
    'server/**/*.js',
    'config/**/*.js'
  ])
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('lint-json', function() {
  return gulp.src(paths.challenges)
    .pipe(jsonlint())
    .pipe(jsonlint.reporter());
});

gulp.task('test-challenges', ['lint-json']);

gulp.task('pack-client', function() {
  if (!__DEV__) { console.log('\n\nbundling production\n\n'); }

  var manifestName = 'react-manifest.json';
  var dest = webpackConfig.output.path;

  return gulp.src(webpackConfig.entry)
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(webpack(Object.assign(
      {},
      webpackConfig,
      webpackOptions
    )))
    .pipe(__DEV__ ? gutil.noop() : uglify())
    .pipe(gulp.dest(dest))
    .pipe(rev())
    // copy files to public
    .pipe(gulp.dest(dest))
    // create manifest
    .pipe(rev.manifest(manifestName))
    // delete old rev
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

var defaultStatsOptions = {
  colors: gutil.colors.supportsColor,
  hash: false,
  timings: false,
  chunks: false,
  chunkModules: false,
  modules: false,
  children: true,
  version: true,
  cached: false,
  cachedAssets: false,
  reasons: false,
  source: false,
  errorDetails: false
};

var webpackCalled = false;
gulp.task('pack-watch', function(cb) {
  if (webpackCalled) {
    console.log('webpack watching already runnning');
    return cb();
  }
  gulp.src(webpackConfig.entry)
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(webpack(Object.assign(
      {},
      webpackConfig,
      webpackOptions,
      { watch: true }
    ), null, function(notUsed, stats) {
      if (stats) {
        gutil.log(stats.toString(defaultStatsOptions));
      }

      if (!webpackCalled) {
        debug('webpack init completed');
        webpackCalled = true;
        cb();
      }

    }))
    .pipe(gulp.dest(webpackConfig.output.path));
});

gulp.task('pack-watch-manifest', ['pack-watch'], function() {
  var manifestName = 'react-manifest.json';
  var dest = webpackConfig.output.path;
  return gulp.src(dest + '/bundle.js')
    .pipe(rev())
    // copy files to public
    .pipe(gulp.dest(dest))
    // create manifest
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

gulp.task('pack-node', function() {
  return gulp.src(webpackConfigNode.entry)
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(webpack(webpackConfigNode))
    .pipe(gulp.dest(webpackConfigNode.output.path));
});

gulp.task('pack', ['pack-client', 'pack-node']);

gulp.task('less', function() {
  var manifestName = 'css-manifest.json';
  var dest = paths.css;
  return gulp.src(paths.less)
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(__DEV__ ? sourcemaps.init() : gutil.noop())
    // compile
    .pipe(less({
      paths: [ path.join(__dirname, 'less', 'includes') ]
    }))
    .pipe(__DEV__ ?
      sourcemaps.write({ sourceRoot: '/less' }) :
      gutil.noop()
    )
    .pipe(gulp.dest(dest))
    // add revision
    .pipe(rev())
    // copy files to public
    .pipe(gulp.dest(dest))
    // create and merge manifest
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

function getFilesGlob(files) {
  if (!__DEV__) {
    return files;
  }
  return files.map(function(file) {
    return file
      .replace('.min.', '.')
      // moment breaks the pattern
      .replace('/min/', '/');
  });
}

gulp.task('js', function() {
  var manifestName = 'js-manifest.json';
  var dest = paths.publicJs;

  var jsFiles = merge(

    gulp.src(getFilesGlob(paths.vendorMain))
      .pipe(__DEV__ ? sourcemaps.init() : gutil.noop())
      .pipe(concat('vendor-main.js'))
      .pipe(
        __DEV__ ?
          sourcemaps.write({ sourceRoot: '/vendor' }) :
          gutil.noop()
      ),

    gulp.src(paths.vendorChallenges)
      .pipe(__DEV__ ? sourcemaps.init() : gutil.noop())
      .pipe(__DEV__ ? gutil.noop() : uglify())
      .pipe(concat('vendor-challenges.js'))
      .pipe(
        __DEV__ ?
          sourcemaps.write({ sourceRoot: '/vendor' }) :
          gutil.noop()
      ),

    gulp.src(paths.js)
      .pipe(plumber({ errorHandler: errorHandler }))
      .pipe(babel())
      .pipe(__DEV__ ? gutil.noop() : uglify())
  );

  return jsFiles
    .pipe(gulp.dest(dest))
    // create registry file
    .pipe(rev())
    // copy revisioned assets to dest
    .pipe(gulp.dest(dest))
    // create manifest file
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    // copy manifest file to dest
    .pipe(gulp.dest(paths.manifest));
});

// commonFramework depend on iFrameScripts
// and faux.js
gulp.task('dependents', ['js'], function() {
  var manifestName = 'dependents-manifest.json';
  var dest = paths.publicJs;

  var manifest = gulp.src(
    path.join(__dirname, paths.manifest, 'js-manifest.json')
  );

  return gulp.src(formatCommonFrameworkPaths.call(paths.commonFramework))
    .pipe(plumber({ errorHandler: errorHandler }))
    .pipe(babel())
    .pipe(__DEV__ ? sourcemaps.init() : gutil.noop())
    .pipe(concat('commonFramework.js'))
    .pipe(
      __DEV__ ?
        sourcemaps.write({ sourceRoot: '/commonFramework' }) :
        gutil.noop()
    )
    .pipe(__DEV__ ? gutil.noop() : uglify())
    .pipe(revReplace({ manifest: manifest }))
    .pipe(gulp.dest(dest))
    .pipe(rev())
    .pipe(gulp.dest(dest))
    .pipe(rev.manifest(manifestName))
    .pipe(delRev(
      dest,
      manifestName
    ))
    .pipe(gulp.dest(paths.manifest));
});

function collector(file, memo) {
  return Object.assign({}, JSON.parse(file.contents), memo);
}

function done(manifest) {
  return sortKeys(manifest);
}

function buildManifest() {
  return gulp.src(paths.manifest + '*.json')
    .pipe(reduce('rev-manifest.json', collector, done, {}))
    .pipe(gulp.dest('server/'));
}

var buildDependents = ['less', 'js', 'dependents'];

if (__DEV__) {
  buildDependents.push('pack-watch-manifest');
}

gulp.task('build-manifest', buildDependents, function() {
  return buildManifest();
});

gulp.task('build-manifest-watch', function() {
  return buildManifest();
});

gulp.task('build', [
  'less',
  'js',
  'dependents',
  'pack-client',
  'build-manifest'
]);

var watchDependents = [
  'less',
  'js',
  'dependents',
  'serve',
  'sync',
  'pack-watch',
  'pack-watch-manifest',
  'build-manifest'
];

gulp.task('reload', function() {
  notify({ message: 'test changed' });
  reload();
});

gulp.task('watch', watchDependents, function() {
  gulp.watch(paths.lessFiles, ['less']);
  gulp.watch(paths.js.concat(paths.vendorChallenges), ['js']);
  gulp.watch(paths.challenges, ['test-challenges', 'reload']);
  gulp.watch(paths.js, ['js', 'dependents']);
  gulp.watch(
    formatCommonFrameworkPaths.call(paths.commonFramework),
    ['dependents']
  );
  gulp.watch(paths.manifest + '/*.json', ['build-manifest-watch']);
  gulp.watch(webpackConfig.output.path + '/bundle.js', ['pack-watch-manifest']);
});

gulp.task('default', [
  'less',
  'serve',
  'pack-watch',
  'pack-watch-manifest',
  'build-manifest-watch',
  'watch',
  'sync'
]);

gulp.task('test', function() {
  return gulp.src('test/**/*.js')
    .pipe(tape({
      reporter: tapSpec()
    }));
});
<|endoftext|>


<commit_before>/**
 * Created by hunte on 06/06/2016.
 */

var prntSvcs = angular.module("prntSvcs",['$rootScope', '$compile','$http','$timeout']);

prntSvcs.factory('printer',['printer', function($rootScope, $compile, $http, $timeout ){
    var printHtml = function (html) {
        var deferred = $q.defer();
        var hiddenFrame = $('').appendTo('body')[0];
        hiddenFrame.contentWindow.printAndRemove = function() {
            hiddenFrame.contentWindow.print();
            $(hiddenFrame).remove();
        };

    };

    var print = function (templateUrl, data) {
        $http.get(templateUrl).success(function(template){
            var printScope = $rootScope.$new()
            angular.extend(printScope, data);
            var element = $compile($('
' + template + '
'))(printScope);
            var waitForRenderAndPrint = function() {
                if(printScope.$$phase || $http.pendingRequests.length) {
                    $timeout(waitForRenderAndPrint);
                } else {
                    // Replace printHtml with openNewWindow for debugging
                    printHtml(element.html());
                    printScope.$destroy();
                }
            };
            waitForRenderAndPrint();
        });
    };
}]);

<commit_msg>Updated printService.js<commit_after>/**
 * Created by hunte on 06/06/2016.
 */

var prntSvcs = angular.module("prntSvcs",['$rootScope', '$compile','$http','$timeout']);

prntSvcs.factory('printer',['printer', function($rootScope, $compile, $http, $timeout ){
    var printHtml = function (html) {
        var deferred = $q.defer();
        var hiddenFrame = $('').appendTo('body')[0];
        hiddenFrame.contentWindow.printAndRemove = function() {
            hiddenFrame.contentWindow.print();
            $(hiddenFrame).remove();
        };

    };

    var print = function (templateUrl, data) {
        $http.get(templateUrl).success(function(template){
            var printScope = $rootScope.$new()
            angular.extend(printScope, data);
            var element = $compile($('
' + template + '
'))(printScope);
            var waitForRenderAndPrint = function() {
                if(printScope.$$phase || $http.pendingRequests.length) {
                    $timeout(waitForRenderAndPrint);
                } else {
                    // Replace printHtml with openNewWindow for debugging
                    printHtml(element.html());
                    printScope.$destroy();
                }
            };
            waitForRenderAndPrint();
        });
    };
}]);

<|endoftext|>


<commit_before>var gulp        = require( 'gulp' );
var requireDir  = require( 'require-dir' )
var runSequence = require( 'run-sequence' );;

requireDir( './gulp/tasks', { recurse: true } );

gulp.task( 'default', function(  )
{
	runSequence(
		'clean',
		[
			'sass',
			'scripts',
			'jade',
			'images'
		],
		'bower-files',
		'inject',
		'connect',
		'watch'
	);
} );

gulp.task( 'build', function(  )
{
	runSequence(
		'clean',
		[
			'build-images',
			'build-scripts',
			'build-css'
		],
		'jade',
		'build-inject',
		'build-html',
		'connect'
	);
} );<commit_msg>add use strict to gulpfile<commit_after>'use strict';

var gulp        = require( 'gulp' );
var requireDir  = require( 'require-dir' )
var runSequence = require( 'run-sequence' );;

requireDir( './gulp/tasks', { recurse: true } );

gulp.task( 'default', function(  )
{
	runSequence(
		'clean',
		[
			'sass',
			'scripts',
			'jade',
			'images'
		],
		'bower-files',
		'inject',
		'connect',
		'watch'
	);
} );

gulp.task( 'build', function(  )
{
	runSequence(
		'clean',
		[
			'build-images',
			'build-scripts',
			'build-css'
		],
		'jade',
		'build-inject',
		'build-html',
		'connect'
	);
} );<|endoftext|>


<commit_before>var servPort = process.env.DS_PORT || 8080; // default TCP port 8080

// for each URL route, import environment variable or set default for
// maximum added response latency (milliseconds) and error 503 probability (percentage)
//
// parameters for / [main]
var latencyMax_main = process.env.DS_LAT_MAIN || 1000;
var errorProb_main  = process.env.DS_ERR_MAIN || 10;
// parameters for /alt
var latencyMax_alt  = process.env.DS_LAT_ALT  || 2000;
var errorProb_alt   = process.env.DS_ERR_ALT  || 20;

// for error 503 case, import environment variable or set default for
// extra maximum added response latency (milliseconds)
var latencyMax_err  = process.env.DS_LAT_ERR  || 3000;

// example custom header
var metaVersion = process.env.DS_META_VER || "1.20(3)";

var sleep = require('sleep'); //npm install sleep
var express = require('express'); //npm install express
var app = express();

app.get('/', function (request, response) {
        console.log("Route / (main)")
        var basicSnooze = Math.round(Math.random()*latencyMax_main);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_main) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("HTTP Error 503 Service Unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Main</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Surprise!
Something completely different
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

app.get('/alt', function (request, response) {
        console.log("Route /alt")
        var basicSnooze = Math.round(Math.random()*latencyMax_alt);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_alt) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("HTTP Error 503 Service Unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Alt</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Cheers!
Everyone loves instant gratification
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

var server = app.listen(servPort, function () {
                        var host = server.address().address;
                        var port = server.address().port;
                        console.log('Demo server listening at http://%s:%s', host, port);
                        });
<commit_msg>Retweaked error message<commit_after>var servPort = process.env.DS_PORT || 8080; // default TCP port 8080

// for each URL route, import environment variable or set default for
// maximum added response latency (milliseconds) and error 503 probability (percentage)
//
// parameters for / [main]
var latencyMax_main = process.env.DS_LAT_MAIN || 1000;
var errorProb_main  = process.env.DS_ERR_MAIN || 10;
// parameters for /alt
var latencyMax_alt  = process.env.DS_LAT_ALT  || 2000;
var errorProb_alt   = process.env.DS_ERR_ALT  || 20;

// for error 503 case, import environment variable or set default for
// extra maximum added response latency (milliseconds)
var latencyMax_err  = process.env.DS_LAT_ERR  || 3000;

// example custom header
var metaVersion = process.env.DS_META_VER || "1.20(3)";

var sleep = require('sleep'); //npm install sleep
var express = require('express'); //npm install express
var app = express();

app.get('/', function (request, response) {
        console.log("Route / (main)")
        var basicSnooze = Math.round(Math.random()*latencyMax_main);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_main) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("HTTP Error 503\nService unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Main</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Surprise!
Something completely different
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

app.get('/alt', function (request, response) {
        console.log("Route /alt")
        var basicSnooze = Math.round(Math.random()*latencyMax_alt);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_alt) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("HTTP Error 503\nService unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Alt</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Cheers!
Everyone loves instant gratification
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

var server = app.listen(servPort, function () {
                        var host = server.address().address;
                        var port = server.address().port;
                        console.log('Demo server listening at http://%s:%s', host, port);
                        });
<|endoftext|>


<commit_before>var gulp = require('gulp');
var inlinesource = require('gulp-inline-source');
var htmlmin = require('gulp-htmlmin');
var ghPages = require('gulp-gh-pages');

gulp.task('build', function() {
  var options = {};
  options.inlinesource = {
    compress: true
  };

  var stream = gulp.src('./index.html')
    .pipe(inlinesource({compress: true}))
    .pipe(htmlmin({
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeRedundantAttributes: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true,
      removeOptionalTags: true
    }))
    .pipe(gulp.dest('./dist'));

  return stream;
});

gulp.task('deploy', ['build'], function() {
  gulp.src('./dist/index.html')
  .pipe(ghPages())
});

gulp.task('clean')<commit_msg>Remove the clean task<commit_after>var gulp = require('gulp');
var inlinesource = require('gulp-inline-source');
var htmlmin = require('gulp-htmlmin');
var ghPages = require('gulp-gh-pages');
var del = require('del');

gulp.task('build', function() {
  var options = {};
  options.inlinesource = {
    compress: true
  };

  var stream = gulp.src('./index.html')
    .pipe(inlinesource({compress: true}))
    .pipe(htmlmin({
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeRedundantAttributes: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true,
      removeOptionalTags: true
    }))
    .pipe(gulp.dest('./dist'));

  return stream;
});

gulp.task('deploy', ['build'], function() {
  gulp.src('./dist/index.html')
  .pipe(ghPages())
});<|endoftext|>


<commit_before>var gulp   = require('gulp'),
    uglify = require('gulp-uglify'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-concat'),
    cssmin = require('gulp-cssmin'),
    //jscs = require('gulp-jscs'),
    htmlreplace = require('gulp-html-replace'),
    templateCache = require('gulp-angular-templatecache'),
    del = require('del');

gulp.task('minify', ['templates'], function () {
    var scripts = [
        "src/app.js",
        "src/services/utils.js",
        "src/directives/widgetContent.js",
        "src/services/error.js",
        "src/services/filters.js",
        "src/controllers/filter.js",
        "src/directives/focus.js",
        "src/directives/pivot.js",
        "src/controllers/login.js",
        "src/services/interseptor.js",
        "src/services/connector.js",
        "src/controllers/menu.js",
        "src/controllers/dashboard.js",
        "src/controllers/dashboardList.js",
        "src/factories/baseWidget.js",
        "src/factories/emptyWidget.js",
        "src/factories/baseChart.js",
        "src/factories/lineChart.js",
        "src/factories/areaChart.js",
        "src/factories/barChart.js",
        "src/factories/columnChart.js",
        "src/factories/pieChart.js",
        "src/factories/xyChart.js",
        "src/factories/timeChart.js",
        "src/factories/timeChart.js",
        "src/factories/hiLowChart.js",
        "src/factories/treeMapChart.js",
        "src/factories/bubbleChart.js",
        "src/factories/bullseyeChart.js",
        "src/factories/speedometerChart.js",
        "src/factories/fuelGaugeChart.js",
        "src/factories/pivotWidget.js",
        "src/directives/textWidget.js",
        "src/factories/textWidget.js",
        "src/services/typeMap.js",
        "src/controllers/widget.js",
        "src/services/lang.js",
        "build/src/templates.js"
    ];

    return gulp.src(scripts)
        //.pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        //.pipe(uglify())
        .pipe(uglify({mangle: false}))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cssminify', function () {
    gulp.src(['css/**/*.css', '!css/**/*.min.css'])
        .pipe(cssmin())
        .pipe(concat('main.css'))
        .pipe(gulp.dest('build/css'));
});

gulp.task('copyfiles', function () {
    gulp.src(['src/lib/*.js'])
        .pipe(gulp.dest('build/src/lib'));
    gulp.src(['css/*.min.css'])
        .pipe(gulp.dest('build/css'));
    gulp.src(['fonts/*'])
        .pipe(gulp.dest('build/fonts'));
    gulp.src(['img/*'])
        .pipe(gulp.dest('build/img'));
});

gulp.task('copyindex', function () {
    var scripts = [
        "src/lib/pdfmake.min.js",
        "src/lib/vfs_fonts.js",
        "src/lib/numeral.min.js",
        "src/lib/angular.min.js",
        "src/lib/angular-route.min.js",
        "src/lib/angular-cookies.min.js",
        "src/lib/angular-notify.min.js",
        "src/lib/ng-context-menu.min.js",
        "src/lib/ngDialog.js",
        "src/lib/jquery-2.1.3.min.js",
        "src/lib/bootstrap.min.js",
        "src/lib/angular-gridster.min.js",
        "src/lib/highstock.js",
        "src/lib/exporting.js",
        "src/lib/no-data-to-display.src.js",
        "src/lib/highcharts-more.js",
        "src/lib/highcharts-3d.src.js",
        "src/lib/highcharts-legendExtension.js",
        "src/lib/heatmap.src.js",
        "src/lib/treemap.src.js",
        "src/lib/highcharts-ng.min.js",
        "src/lib/lightPivotTable.js",
        "src/app.js"
    ];
    gulp.src(['index.html'])
        .pipe(htmlreplace({ 'js': scripts }))
        .pipe(gulp.dest('build'));
});

gulp.task('templates', function() {
    return gulp.src(['src/views/*.html'])
        .pipe(templateCache({root:"src/views/"}))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cleanup', ['minify'], function() {
    del(["build/src/templates.js"]);
});

gulp.task('default', ['minify', 'cssminify', 'copyfiles', 'copyindex', 'cleanup'], function () {});

<commit_msg>modules added<commit_after>var gulp   = require('gulp'),
    uglify = require('gulp-uglify'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-concat'),
    cssmin = require('gulp-cssmin'),
    //jscs = require('gulp-jscs'),
    htmlreplace = require('gulp-html-replace'),
    templateCache = require('gulp-angular-templatecache'),
    del = require('del');

gulp.task('minify', ['templates'], function () {
    var scripts = [
        "src/app.js",
        "src/services/utils.js",
        "src/directives/widgetContent.js",
        "src/services/error.js",
        "src/services/filters.js",
        "src/controllers/filter.js",
        "src/directives/focus.js",
        "src/directives/pivot.js",
        "src/controllers/login.js",
        "src/services/interseptor.js",
        "src/services/connector.js",
        "src/controllers/menu.js",
        "src/controllers/dashboard.js",
        "src/controllers/dashboardList.js",
        "src/controllers/home.js",
        "src/factories/baseWidget.js",
        "src/factories/emptyWidget.js",
        "src/factories/baseChart.js",
        "src/factories/lineChart.js",
        "src/factories/areaChart.js",
        "src/factories/barChart.js",
        "src/factories/columnChart.js",
        "src/factories/pieChart.js",
        "src/factories/xyChart.js",
        "src/factories/timeChart.js",
        "src/factories/timeChart.js",
        "src/factories/hiLowChart.js",
        "src/factories/treeMapChart.js",
        "src/factories/bubbleChart.js",
        "src/factories/bullseyeChart.js",
        "src/factories/speedometerChart.js",
        "src/factories/fuelGaugeChart.js",
        "src/factories/pivotWidget.js",
        "src/directives/textWidget.js",
        "src/factories/textWidget.js",
        "src/services/typeMap.js",
        "src/controllers/widget.js",
        "src/services/lang.js",
        "build/src/templates.js"
    ];

    return gulp.src(scripts)
        //.pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        //.pipe(uglify())
        .pipe(uglify({mangle: false}))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cssminify', function () {
    gulp.src(['css/**/*.css', '!css/**/*.min.css'])
        .pipe(cssmin())
        .pipe(concat('main.css'))
        .pipe(gulp.dest('build/css'));
});

gulp.task('copyfiles', function () {
    gulp.src(['src/lib/*.js'])
        .pipe(gulp.dest('build/src/lib'));
    gulp.src(['css/*.min.css'])
        .pipe(gulp.dest('build/css'));
    gulp.src(['fonts/*'])
        .pipe(gulp.dest('build/fonts'));
    gulp.src(['img/*'])
        .pipe(gulp.dest('build/img'));
});

gulp.task('copyindex', function () {
    var scripts = [
        "src/lib/pdfmake.min.js",
        "src/lib/vfs_fonts.js",
        "src/lib/numeral.min.js",
        "src/lib/angular.min.js",
        "src/lib/angular-route.min.js",
        "src/lib/angular-cookies.min.js",
        "src/lib/angular-notify.min.js",
        "src/lib/ng-context-menu.min.js",
        "src/lib/ngDialog.js",
        "src/lib/jquery-2.1.3.min.js",
        "src/lib/bootstrap.min.js",
        "src/lib/angular-gridster.min.js",
        "src/lib/highstock.js",
        "src/lib/exporting.js",
        "src/lib/no-data-to-display.src.js",
        "src/lib/highcharts-more.js",
        "src/lib/highcharts-3d.src.js",
        "src/lib/highcharts-legendExtension.js",
        "src/lib/heatmap.src.js",
        "src/lib/treemap.src.js",
        "src/lib/highcharts-ng.min.js",
        "src/lib/lightPivotTable.js",
        "src/app.js"
    ];
    gulp.src(['index.html'])
        .pipe(htmlreplace({ 'js': scripts }))
        .pipe(gulp.dest('build'));
});

gulp.task('templates', function() {
    return gulp.src(['src/views/*.html'])
        .pipe(templateCache({root:"src/views/"}))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cleanup', ['minify'], function() {
    del(["build/src/templates.js"]);
});

gulp.task('default', ['minify', 'cssminify', 'copyfiles', 'copyindex', 'cleanup'], function () {});

<|endoftext|>


<commit_before>var gulp = require('gulp');

var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var prefix = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var reload = browserSync.reload;
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var transform = require('vinyl-transform');
var uglify = require('gulp-uglify');

// Start server
gulp.task('serve', function () {
  browserSync({
    server: './Build'
  });
});

// HTML task
gulp.task('html', function() {
  return gulp.src('./src/*.html')
    .pipe(gulp.dest('./Build'))
    .pipe(reload({stream: true}))
});

// Sass task
gulp.task('sass', function(event) {
  return gulp.src(['./src/scss/*.scss', './src/scss/**/*.scss'])
    .pipe(plumber())
    .pipe(sass())
    .pipe(prefix({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(minifyCSS())
    .pipe(gulp.dest('./Build/css'))
    .pipe(reload({stream: true}))
});

// JS task
gulp.task('js', function () {
  return browserify({entries: ['./src/js/app.js']})
    .bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
      .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./Build/js'))
    .pipe(reload({stream: true}));
});

// Default task
gulp.task('default', ['serve', 'html', 'sass', 'js'], function() {
  gulp.watch('./src/*.html', ['html']);
  gulp.watch(['./src/scss/*.scss', './src/scss/**/*.scss'], ['sass']);
  gulp.watch('./src/js/*.js', ['js']);
});
<commit_msg>Add standalone watch task and remove watch task from default task<commit_after>var gulp = require('gulp');

var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var prefix = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var reload = browserSync.reload;
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var transform = require('vinyl-transform');
var uglify = require('gulp-uglify');

// Start server
gulp.task('serve', function () {
  browserSync({
    server: './Build'
  });
});

// HTML task
gulp.task('html', function() {
  return gulp.src('./src/*.html')
    .pipe(gulp.dest('./Build'))
    .pipe(reload({stream: true}))
});

// Sass task
gulp.task('sass', function(event) {
  return gulp.src(['./src/scss/*.scss', './src/scss/**/*.scss'])
    .pipe(plumber())
    .pipe(sass())
    .pipe(prefix({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(minifyCSS())
    .pipe(gulp.dest('./Build/css'))
    .pipe(reload({stream: true}))
});

// JS task
gulp.task('js', function () {
  return browserify({entries: ['./src/js/app.js']})
    .bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
      .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./Build/js'))
    .pipe(reload({stream: true}));
});

// Watch task
gulp.task('watch', function() {
  gulp.watch('./src/*.html', ['html']);
  gulp.watch(['./src/scss/*.scss', './src/scss/**/*.scss'], ['sass']);
  gulp.watch('./src/js/*.js', ['js']);
});

// Default task
gulp.task('default', ['serve', 'html', 'sass', 'js', 'watch']);
<|endoftext|>


<commit_before>var express  = require('express'),
    handlers = require('./handlers'),
    models   = require('./models'),
    helpers  = require('./helpers'),
    errors   = require('./errors'),
    spike    = require('./spike'),
    features = require('./features'),
    scripts  = require('../scripts.json');

function tag(label) {
  return function (req, res, next) {
    req[label] = true;
    next();
  };
}

module.exports = function (app) {
  // A sandbox object to contain some specific objects that are commonly used by
  // handlers. In future it would be ideal that each handler only receives the
  // objects that it requires.
  var sandbox = {
    store:   app.store,
    models:  models,
    mailer:  app.mailer,
    helpers: helpers.createHelpers(app)
  }, binHandler, sessionHandler, errorHandler;

  // Create handlers for accepting incoming requests.
  binHandler = new handlers.BinHandler(sandbox);
  sessionHandler = new handlers.SessionHandler(sandbox);
  errorHandler = new handlers.ErrorHandler(sandbox);

  // Special redirects (to external sources)
  app.get(['/video', '/videos', '/tutorials'], function (req, res) {
    res.redirect('http://www.youtube.com/playlist?list=PLXmT1r4krsTooRDWOrIu23P3SEZ3luIUq');
  });

  app.get('/about', function (req, res) {
    res.redirect('https://github.com/remy/jsbin/blob/master/README.markdown');
  });

  app.get(['/issues', '/bugs'], function (req, res) {
    res.redirect('https://github.com/remy/jsbin/issues/');
  });

  // Handler Events

  binHandler.on('updated', spike.ping.bind(spike));
  binHandler.on('reload', spike.reload.bind(spike));
  binHandler.on('latest-for-user', spike.updateUserSpikes.bind(spike));
  binHandler.on('new-revision', spike.bumpRevision.bind(spike));

  binHandler.on('render-scripts', spike.appendScripts.bind(spike, app.settings.version));

  // Load the bin from the store when encountered in the url. Also handles the
  // "latest" url action.
  app.param('bin', binHandler.loadBin);
  app.param('rev', binHandler.loadBinRevision);
  app.param('name', sessionHandler.loadUser);

  // Set up the routes.
  app.get('/', binHandler.getDefault);
  app.get('/gist/*', binHandler.getDefault);
  app.post('/', binHandler.getFromPost);

  // Runner
  app.get('/runner', function (req, res) {
    res.render('runner', {
      scripts: app.get('is_production') ? false : scripts.runner,
      static: sandbox.helpers.urlForStatic()
    });
  });

  app.get('/api/:bin/:rev?', binHandler.apiGetBin);
  app.post('/api/save', binHandler.apiCreateBin);
  app.post('/api/:bin/save', binHandler.apiCreateRevision);

  // Login/Create account.
  app.post('/sethome', sessionHandler.routeSetHome);
  app.post('/logout', sessionHandler.logoutUser);
  app.post('/forgot', sessionHandler.forgotPassword);
  app.get('/forgot', sessionHandler.requestToken);
  app.get('/reset', sessionHandler.resetPassword);

  // GitHub auth
  app.get('/auth/github', sessionHandler.github);
  app.get('/auth/github/callback', sessionHandler.githubPassportCallback, sessionHandler.githubCallback);

  // List
  app.get('/list/:user', binHandler.getUserBins);
  app.get('/list',       binHandler.getUserBins);
  app.get('/show/:user', binHandler.getUserBins);
  app.get('/user/:user', binHandler.getUserBins);

  // Latest
  app.get('/:bin/latest((.|\/):format)?', binHandler.redirectToLatest);
  app.get('/:bin/latest/edit', binHandler.redirectToLatest);

  // Quick and easy urls for test - allows me to do /rem/last on my mobile devices
  app.get('/:name/last(\-:n)?/:quiet(quiet)?', tag('keepLatest'), binHandler.getLatestForUser, spike.getStream, binHandler.getBinPreview);
  app.get('/:name/last(\-:n)?/edit', binHandler.getLatestForUser, binHandler.getBin);
  app.get('/:name/last(\-:n)?/watch', binHandler.getLatestForUser, binHandler.live, binHandler.getBin);

  // Edit
  app.get('/:bin/:rev?/edit', binHandler.getBin);
  app.get('/:bin/:rev?/watch', tag('live'), binHandler.getBin);
  app.get('/:bin/:rev?/embed', tag('embed'), binHandler.getBin);

  app.post('/:bin/:rev?/report', binHandler.report);

  // Save
  app.post('/save', binHandler.createBin);

  // Use this handler to check for a user creating/claiming their own bin url.
  // We use :url here to prevent loadBin() being called and returning a not
  // found error.
  app.post('/:url/save', binHandler.claimBin);

  // If the above route fails then it's either a clone or a revision. Which
  // the handler can check in the post body.
  app.post('/:bin/:rev?/save', binHandler.createRevisionOrClone);
  app.post('/:bin/:rev?/reload', binHandler.reload);

  // delete a bin
  app.post('/:bin/:rev?/delete', features.route('delete'), binHandler.delete);

  // Private
  app.post('/:bin/:rev?/private', binHandler.setBinAsPrivate);
  app.post('/:bin/:rev?/public', binHandler.setBinAsPublic);

  // Archive
  app.post('/:bin/:rev/archive', binHandler.archiveBin.bind(null, true));
  // Unarchive
  app.post('/:bin/:rev/unarchive', binHandler.archiveBin.bind(null, false));

  // Download
  app.get('/:bin/:rev?/download', binHandler.downloadBin);

  // Source
  app.get('/:bin/:rev?/source', binHandler.getBinSource);
  app.get('/:bin/:rev?.:format(js|json|css|html|md|markdown|stylus|less|coffee|jade)', binHandler.getBinSourceFile);
  app.get('/:bin/:rev?/:format(js)', function (req, res) {
    // Redirect legacy /js suffix to the new .js extension.
    res.redirect(301, req.path.replace(/\/js$/, '.js'));
  });

  // Log
  app.get('/:bin/:rev/log', spike.getLog);
  app.post('/:bin/:rev/log', spike.postLog);

  // Preview
  app.get('/:bin/:quiet(quiet)?', spike.getStream, binHandler.getBinPreview);
  app.get('/:bin/:rev?/:quiet(quiet)?', spike.getStream, binHandler.getBinPreview);

  app.get('/test/error/:num', function (req, res, next) {
    next(req.params.num * 1);
  });

  // Handle failed auth requests.
  app.use(sessionHandler.githubCallbackWithError);

  // Catch all
  app.use(errorHandler.notFound);

  // Error handler.
  app.use(errorHandler.httpError);

  // Final connect error handler when in development.
  app.configure('development', function () {
    app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
  });

  // Final connect error handler when in development.
  app.configure('production', function () {
    app.use(errorHandler.uncaughtError);
  });
};
<commit_msg>Updating redirects to github<commit_after>var express  = require('express'),
    handlers = require('./handlers'),
    models   = require('./models'),
    helpers  = require('./helpers'),
    errors   = require('./errors'),
    spike    = require('./spike'),
    features = require('./features'),
    scripts  = require('../scripts.json');

function tag(label) {
  return function (req, res, next) {
    req[label] = true;
    next();
  };
}

module.exports = function (app) {
  // A sandbox object to contain some specific objects that are commonly used by
  // handlers. In future it would be ideal that each handler only receives the
  // objects that it requires.
  var sandbox = {
    store:   app.store,
    models:  models,
    mailer:  app.mailer,
    helpers: helpers.createHelpers(app)
  }, binHandler, sessionHandler, errorHandler;

  // Create handlers for accepting incoming requests.
  binHandler = new handlers.BinHandler(sandbox);
  sessionHandler = new handlers.SessionHandler(sandbox);
  errorHandler = new handlers.ErrorHandler(sandbox);

  // Special redirects (to external sources)
  app.get(['/video', '/videos', '/tutorials'], function (req, res) {
    res.redirect('http://www.youtube.com/playlist?list=PLXmT1r4krsTooRDWOrIu23P3SEZ3luIUq');
  });

  app.get('/about', function (req, res) {
    res.redirect('https://github.com/jsbin/jsbin/blob/master/README.markdown');
  });

  app.get(['/issues', '/bugs'], function (req, res) {
    res.redirect('https://github.com/jsbin/jsbin/issues/');
  });

  // Handler Events

  binHandler.on('updated', spike.ping.bind(spike));
  binHandler.on('reload', spike.reload.bind(spike));
  binHandler.on('latest-for-user', spike.updateUserSpikes.bind(spike));
  binHandler.on('new-revision', spike.bumpRevision.bind(spike));

  binHandler.on('render-scripts', spike.appendScripts.bind(spike, app.settings.version));

  // Load the bin from the store when encountered in the url. Also handles the
  // "latest" url action.
  app.param('bin', binHandler.loadBin);
  app.param('rev', binHandler.loadBinRevision);
  app.param('name', sessionHandler.loadUser);

  // Set up the routes.
  app.get('/', binHandler.getDefault);
  app.get('/gist/*', binHandler.getDefault);
  app.post('/', binHandler.getFromPost);

  // Runner
  app.get('/runner', function (req, res) {
    res.render('runner', {
      scripts: app.get('is_production') ? false : scripts.runner,
      static: sandbox.helpers.urlForStatic()
    });
  });

  app.get('/api/:bin/:rev?', binHandler.apiGetBin);
  app.post('/api/save', binHandler.apiCreateBin);
  app.post('/api/:bin/save', binHandler.apiCreateRevision);

  // Login/Create account.
  app.post('/sethome', sessionHandler.routeSetHome);
  app.post('/logout', sessionHandler.logoutUser);
  app.post('/forgot', sessionHandler.forgotPassword);
  app.get('/forgot', sessionHandler.requestToken);
  app.get('/reset', sessionHandler.resetPassword);

  // GitHub auth
  app.get('/auth/github', sessionHandler.github);
  app.get('/auth/github/callback', sessionHandler.githubPassportCallback, sessionHandler.githubCallback);

  // List
  app.get('/list/:user', binHandler.getUserBins);
  app.get('/list',       binHandler.getUserBins);
  app.get('/show/:user', binHandler.getUserBins);
  app.get('/user/:user', binHandler.getUserBins);

  // Latest
  app.get('/:bin/latest((.|\/):format)?', binHandler.redirectToLatest);
  app.get('/:bin/latest/edit', binHandler.redirectToLatest);

  // Quick and easy urls for test - allows me to do /rem/last on my mobile devices
  app.get('/:name/last(\-:n)?/:quiet(quiet)?', tag('keepLatest'), binHandler.getLatestForUser, spike.getStream, binHandler.getBinPreview);
  app.get('/:name/last(\-:n)?/edit', binHandler.getLatestForUser, binHandler.getBin);
  app.get('/:name/last(\-:n)?/watch', binHandler.getLatestForUser, binHandler.live, binHandler.getBin);

  // Edit
  app.get('/:bin/:rev?/edit', binHandler.getBin);
  app.get('/:bin/:rev?/watch', tag('live'), binHandler.getBin);
  app.get('/:bin/:rev?/embed', tag('embed'), binHandler.getBin);

  app.post('/:bin/:rev?/report', binHandler.report);

  // Save
  app.post('/save', binHandler.createBin);

  // Use this handler to check for a user creating/claiming their own bin url.
  // We use :url here to prevent loadBin() being called and returning a not
  // found error.
  app.post('/:url/save', binHandler.claimBin);

  // If the above route fails then it's either a clone or a revision. Which
  // the handler can check in the post body.
  app.post('/:bin/:rev?/save', binHandler.createRevisionOrClone);
  app.post('/:bin/:rev?/reload', binHandler.reload);

  // delete a bin
  app.post('/:bin/:rev?/delete', features.route('delete'), binHandler.delete);

  // Private
  app.post('/:bin/:rev?/private', binHandler.setBinAsPrivate);
  app.post('/:bin/:rev?/public', binHandler.setBinAsPublic);

  // Archive
  app.post('/:bin/:rev/archive', binHandler.archiveBin.bind(null, true));
  // Unarchive
  app.post('/:bin/:rev/unarchive', binHandler.archiveBin.bind(null, false));

  // Download
  app.get('/:bin/:rev?/download', binHandler.downloadBin);

  // Source
  app.get('/:bin/:rev?/source', binHandler.getBinSource);
  app.get('/:bin/:rev?.:format(js|json|css|html|md|markdown|stylus|less|coffee|jade)', binHandler.getBinSourceFile);
  app.get('/:bin/:rev?/:format(js)', function (req, res) {
    // Redirect legacy /js suffix to the new .js extension.
    res.redirect(301, req.path.replace(/\/js$/, '.js'));
  });

  // Log
  app.get('/:bin/:rev/log', spike.getLog);
  app.post('/:bin/:rev/log', spike.postLog);

  // Preview
  app.get('/:bin/:quiet(quiet)?', spike.getStream, binHandler.getBinPreview);
  app.get('/:bin/:rev?/:quiet(quiet)?', spike.getStream, binHandler.getBinPreview);

  app.get('/test/error/:num', function (req, res, next) {
    next(req.params.num * 1);
  });

  // Handle failed auth requests.
  app.use(sessionHandler.githubCallbackWithError);

  // Catch all
  app.use(errorHandler.notFound);

  // Error handler.
  app.use(errorHandler.httpError);

  // Final connect error handler when in development.
  app.configure('development', function () {
    app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
  });

  // Final connect error handler when in development.
  app.configure('production', function () {
    app.use(errorHandler.uncaughtError);
  });
};
<|endoftext|>


<commit_before>/* global require */
var jshint = require('gulp-jshint'),
  stylish = require('jshint-stylish'),
  jsonlint = require('gulp-jsonlint'),
  uglify = require('gulp-uglify'),
  rename = require('gulp-rename'),
  header = require('gulp-header'),
  connect = require('gulp-connect'),
  replace = require('gulp-replace'),
  rename = require('gulp-rename'),
  sass = require('gulp-sass'),
  fs = require('fs');
  qunit = require('node-qunit-phantomjs'),
  gulp = require('gulp');

gulp.task('lintJSON', function(){
  gulp.src(['*.json', '.jshintrc'])
    .pipe(jsonlint())
    .pipe(jsonlint.reporter());
});

gulp.task('lintJS', function(){
  gulp.src(['*/**.js', '!**/*.min.js', '!bower_components', '!node_modules'])
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

gulp.task('prepTestFiles', function(){
  gulp.src('src/oForm.js')
    .pipe(replace('/* expose default functions */', 'jQuery.oFormDefaultFunctions = defaultOptions;'))
    .pipe(replace('/* expose combined function */', 'jQuery.oFormFunctions = settings;'))
    .pipe(rename('oFormTest.js'))
    .pipe(gulp.dest('tests/assets'));
  gulp.src([
    'bower_components/qunit/qunit/qunit.js',
    'bower_components/qunit/qunit/qunit.css',
    'bower_components/jquery/jquery.js',
    'src/assets/scss/javascripts/bootstrap.js'
    ])
      .pipe(gulp.dest('tests/assets/'));
});

gulp.task('css', function(){
  gulp.src('src/assets/scss/stylesheets/styles.scss')
    .pipe(sass())
    .pipe(gulp.dest('tests/assets/css/'));
});

gulp.task('connect', function(){
  connect.server({
    root: 'tests',
    livereload: true,
    middleware: function(connect, options, middlewares){
      return[
        function(req, res, next){
          if(req.method === 'POST'){
            if(req.url === '/success'){
              res.writeHead(200, {'Content-Type': 'application/json'});
              fs.readFile('tests/json/success.json',
              {
                encoding: 'utf-8'
              },
              function(err, data){
                res.end(data);
              });
            }
          } else {
            next();
          }
        }
      ];
    }
  });
});

gulp.task('connectBuild', function(){
  connect.server({
    root: 'tests',
    livereload: false,
    middleware: function(connect, options, middlewares){
      return[
        function(req, res, next){
          if(req.method === 'POST'){
            if(req.url === '/success'){
              res.writeHead(200, {'Content-Type': 'application/json'});
              fs.readFile('tests/json/success.json',
              {
                encoding: 'utf-8'
              },
              function(err, data){
                res.end(data);
              });
            }
          } else {
            next();
          }
        }
      ];
    }
  });
});

gulp.task('html', function(){
  gulp.src('tests/*.html')
    .pipe(connect.reload());
});

gulp.task('watch', function(){
  gulp.watch(['*/**.js', '!bower_component', '!node_modules', '!tests/assets'], ['lintJS', 'prepTestFiles', 'html']);
  gulp.watch(['src/**/*.scss'], ['css']);
  gulp.watch(['tests/*.html'], ['prepTestFiles', 'html']);
});

gulp.task('compress', function(){
  gulp.src('oForm.js')
    .pipe(uglify({mangle: false}))
    .pipe(header('/* oForm - Author: Kyle Rush - MIT license - https://github.com/kylerush/oform */ \n'))
    .pipe(rename('oForm.min.js'))
    .pipe(gulp.dest('dist'));
});

var error;

gulp.task('qunit', function(done){
  qunit('./tests/index.html');
  done();
});

//gulp.task('test', ['prepTestFiles', 'css', 'qunit']);

gulp.task('dev', ['prepTestFiles', 'css', 'connect', 'watch']);

gulp.task('build', ['lintJSON', 'lintJS', 'compress', 'prepTestFiles', 'css', 'qunit']);
<commit_msg>move callback.<commit_after>/* global require */
var jshint = require('gulp-jshint'),
  stylish = require('jshint-stylish'),
  jsonlint = require('gulp-jsonlint'),
  uglify = require('gulp-uglify'),
  rename = require('gulp-rename'),
  header = require('gulp-header'),
  connect = require('gulp-connect'),
  replace = require('gulp-replace'),
  rename = require('gulp-rename'),
  sass = require('gulp-sass'),
  fs = require('fs');
  qunit = require('node-qunit-phantomjs'),
  gulp = require('gulp');

gulp.task('lintJSON', function(){
  gulp.src(['*.json', '.jshintrc'])
    .pipe(jsonlint())
    .pipe(jsonlint.reporter());
});

gulp.task('lintJS', function(){
  gulp.src(['*/**.js', '!**/*.min.js', '!bower_components', '!node_modules'])
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

gulp.task('prepTestFiles', function(){
  gulp.src('src/oForm.js')
    .pipe(replace('/* expose default functions */', 'jQuery.oFormDefaultFunctions = defaultOptions;'))
    .pipe(replace('/* expose combined function */', 'jQuery.oFormFunctions = settings;'))
    .pipe(rename('oFormTest.js'))
    .pipe(gulp.dest('tests/assets'));
  gulp.src([
    'bower_components/qunit/qunit/qunit.js',
    'bower_components/qunit/qunit/qunit.css',
    'bower_components/jquery/jquery.js',
    'src/assets/scss/javascripts/bootstrap.js'
    ])
      .pipe(gulp.dest('tests/assets/'));
});

gulp.task('css', function(){
  gulp.src('src/assets/scss/stylesheets/styles.scss')
    .pipe(sass())
    .pipe(gulp.dest('tests/assets/css/'));
});

gulp.task('connect', function(){
  connect.server({
    root: 'tests',
    livereload: true,
    middleware: function(connect, options, middlewares){
      return[
        function(req, res, next){
          if(req.method === 'POST'){
            if(req.url === '/success'){
              res.writeHead(200, {'Content-Type': 'application/json'});
              fs.readFile('tests/json/success.json',
              {
                encoding: 'utf-8'
              },
              function(err, data){
                res.end(data);
              });
            }
          } else {
            next();
          }
        }
      ];
    }
  });
});

gulp.task('connectBuild', function(){
  connect.server({
    root: 'tests',
    livereload: false,
    middleware: function(connect, options, middlewares){
      return[
        function(req, res, next){
          if(req.method === 'POST'){
            if(req.url === '/success'){
              res.writeHead(200, {'Content-Type': 'application/json'});
              fs.readFile('tests/json/success.json',
              {
                encoding: 'utf-8'
              },
              function(err, data){
                res.end(data);
              });
            }
          } else {
            next();
          }
        }
      ];
    }
  });
});

gulp.task('html', function(){
  gulp.src('tests/*.html')
    .pipe(connect.reload());
});

gulp.task('watch', function(){
  gulp.watch(['*/**.js', '!bower_component', '!node_modules', '!tests/assets'], ['lintJS', 'prepTestFiles', 'html']);
  gulp.watch(['src/**/*.scss'], ['css']);
  gulp.watch(['tests/*.html'], ['prepTestFiles', 'html']);
});

gulp.task('compress', function(){
  gulp.src('oForm.js')
    .pipe(uglify({mangle: false}))
    .pipe(header('/* oForm - Author: Kyle Rush - MIT license - https://github.com/kylerush/oform */ \n'))
    .pipe(rename('oForm.min.js'))
    .pipe(gulp.dest('dist'));
});

var error;

gulp.task('qunit', function(done){
  qunit('./tests/index.html', {}, function(){
    done();
  });
});

//gulp.task('test', ['prepTestFiles', 'css', 'qunit']);

gulp.task('dev', ['prepTestFiles', 'css', 'connect', 'watch']);

gulp.task('build', ['lintJSON', 'lintJS', 'compress', 'prepTestFiles', 'css', 'qunit']);
<|endoftext|>


<commit_before>'use strict'

var gulp   = require('gulp'),
    uglify = require('gulp-uglify');

gulp.task('default', function () {
  gulp.src('./src/predicate.js')
      .pipe(uglify())
      .pipe(gulp.dest('./dist/'));
});
<commit_msg>Missing semicolon in gulpfile<commit_after>'use strict';

var gulp   = require('gulp'),
    uglify = require('gulp-uglify');

gulp.task('default', function () {
  gulp.src('./src/predicate.js')
      .pipe(uglify())
      .pipe(gulp.dest('./dist/'));
});
<|endoftext|>


<commit_before>/**
 * Handling all routing.
 *
 * This and responses.js are the only files that should be saying things like res.send, or res.json.
 *
 * @module
 */

'use strict';
var _ = require('lodash'),
  express = require('express'),
  vhost = require('vhost'),
  config = require('config'),
  siteService = require('./sites'),
  sitesFolder = siteService.sitesFolder,
  composer = require('./composer'),
  path = require('path'),
  responses = require('./responses'),
  files = require('./files');

/**
 * add site.slug to locals for each site
 * @param {object} options
 *   options.slug  (Optional) site name
 */
function addSiteLocals(options) {
  return function (req, res, next) {
    res.locals.url = req.protocol + '://' + req.get('host') + req.originalUrl;

    if (options && options.slug) {
      res.locals.site = options.slug;
    }

    next();
  };
}

/**
 * add edit mode for each site
 */
function addEditMode() {
  return function (req, res, next) {
    // add isEdit to the locals. it'll be ignored by the db lookup
    res.locals.isEditMode = !!(req.query.edit);
    next();
  };
}

/**
 * syntactical sugar to quickly add routes that point directly to a layout
 * @param {string} route  e.g. '/users/:id'
 * @param {string} layout e.g. 'user-page'
 * note: all params will automatically be added to res.locals
 */
function setLayout(route, layout) {
  this.get(route, function (req, res, next) { // jshint ignore:line
    res.locals = req.params; // add all params
    res.locals.layout = layout; // add layout
    next();
  });
}

/**
 * Add component routes to this router.
 * @param router
 */
function addControllerRoutes(router) {
  var routesPath = '/routes';

  //assume json for anything in request bodies
  router.use(require('body-parser').json({strict: true, type: 'application/json'}));
  router.use(require('body-parser').text({type: 'text/*'}));

  //load all controller routers
  _.each(files.getFiles(__dirname + routesPath), function (filename) {
    var pathContainer,
      name = responses.removeExtension(filename),
      controller = require('.' + routesPath + '/' + name);

    pathContainer = express.Router();
    controller(pathContainer);

    router.use('/' + name, pathContainer);
  });
}

/**
 *
 * @param {express.Router} router
 * @param {object} options
 */
function addSite(router, options) {
  options = _.defaults(options || {}, {
    path: '/'
  });
  var path = options.path,
    siteRouter = express.Router();

  // add res.locals.site (slug) to every request
  router.use(path, addSiteLocals(options));

  // parse querystring for ?edit=true (this should probably be at the host level?)
  router.use(path, addEditMode());

  //components, pages and schema have priority over user-defined routes (this should probably be at the host level?)
  addControllerRoutes(router);

  // optional module to load routes and configuration defined from outside of byline
  if (options.siteResolver) {
    router.use(path, options.siteResolver(siteRouter, options));
  }
}

/**
 * @param a
 * @param b
 * @returns {number}
 */
function sortByDepthOfPath(a, b) {
  // sort by the depth of the path, so we can have domain.com/ and domain.com/foo/ as two separate sites
  return a.path.split('/').length - b.path.split('/').length;
}

/**
 * @param hostname
 * @returns {{slug: string, name: string, host: string, path: string}}
 * @example
 *
 *  www.example.com becomes:
 *
 *  {
 *    slug: example
 *    name: Example
 *    host: www.example.com
 *    path: '/'
 *  }
 */
function getDefaultSiteSettings(hostname) {
  var name = _.takeRight(hostname.split('.'), 2)[0]; //penultimate or last

  return {
    slug: name.toLowerCase(),
    name: _.startCase(name),
    host: hostname,
    path: '/'
  };
}

/**
 * Default way to load site controllers.
 *
 * @param {express.Router} router
 * @param {object} data  Extra information to help load controllers
 * @returns {function}
 */
function resolveSiteController(router, data) {
  var controllerPath = path.join(sitesFolder, data.slug);
  return require(controllerPath)(router, composer);
}

/**
 * @param {express.Router} router
 * @param {string} hostname
 * @param {object} [options]
 * @param {array} [options.sites]
 * @param {object} [options.siteResolver] Site router
 *
 * @example addHost('www.example.com');
 */
function addHost(router, hostname, options) {
  options = options || {};
  var hostRouter = express.Router(),
    sites = options.sites || [getDefaultSiteSettings(hostname)];

  _.each(sites, function (site) {
    //pass whatever options were given for the host, plus any extra information for the site.
    addSite(hostRouter, _.defaults(site, options));
  });

  // once all sites are added, wrap them in a vhost
  router.use(vhost(hostname, hostRouter));
}

/**
 * @param router  Often an express app.
 * @returns {*}
 * @example
 *   var app = express();
 *   require('./routes)(app);
 */
function loadFromConfig(router) {
  var siteHosts = siteService.hosts(),
    sitesMap = siteService.sites(),
    hostMap = config.get('hosts'); //includes local.yaml

  // iterate through the hosts
  _.each(siteHosts, function (hostname) {
    var sites = _.filter(sitesMap, {host: hostname}).sort(sortByDepthOfPath),
      localHostname = hostMap[hostname] || hostname;

    addHost(router, localHostname, {
      sites: sites,
      siteResolver: resolveSiteController
    });
  });
  return router;
}

module.exports = loadFromConfig;
module.exports.addSite = addSite;
module.exports.addHost = addHost;
module.exports.getDefaultSiteSettings = getDefaultSiteSettings;
module.exports.sortByDepthOfPath = sortByDepthOfPath;<commit_msg>remove setLayout function<commit_after>/**
 * Handling all routing.
 *
 * This and responses.js are the only files that should be saying things like res.send, or res.json.
 *
 * @module
 */

'use strict';
var _ = require('lodash'),
  express = require('express'),
  vhost = require('vhost'),
  config = require('config'),
  siteService = require('./sites'),
  sitesFolder = siteService.sitesFolder,
  composer = require('./composer'),
  path = require('path'),
  responses = require('./responses'),
  files = require('./files');

/**
 * add site.slug to locals for each site
 * @param {object} options
 *   options.slug  (Optional) site name
 */
function addSiteLocals(options) {
  return function (req, res, next) {
    res.locals.url = req.protocol + '://' + req.get('host') + req.originalUrl;

    if (options && options.slug) {
      res.locals.site = options.slug;
    }

    next();
  };
}

/**
 * add edit mode for each site
 */
function addEditMode() {
  return function (req, res, next) {
    // add isEdit to the locals. it'll be ignored by the db lookup
    res.locals.isEditMode = !!(req.query.edit);
    next();
  };
}

/**
 * Add component routes to this router.
 * @param router
 */
function addControllerRoutes(router) {
  var routesPath = '/routes';

  //assume json for anything in request bodies
  router.use(require('body-parser').json({strict: true, type: 'application/json'}));
  router.use(require('body-parser').text({type: 'text/*'}));

  //load all controller routers
  _.each(files.getFiles(__dirname + routesPath), function (filename) {
    var pathContainer,
      name = responses.removeExtension(filename),
      controller = require('.' + routesPath + '/' + name);

    pathContainer = express.Router();
    controller(pathContainer);

    router.use('/' + name, pathContainer);
  });
}

/**
 *
 * @param {express.Router} router
 * @param {object} options
 */
function addSite(router, options) {
  options = _.defaults(options || {}, {
    path: '/'
  });
  var path = options.path,
    siteRouter = express.Router();

  // add res.locals.site (slug) to every request
  router.use(path, addSiteLocals(options));

  // parse querystring for ?edit=true (this should probably be at the host level?)
  router.use(path, addEditMode());

  //components, pages and schema have priority over user-defined routes (this should probably be at the host level?)
  addControllerRoutes(router);

  // optional module to load routes and configuration defined from outside of byline
  if (options.siteResolver) {
    router.use(path, options.siteResolver(siteRouter, options));
  }
}

/**
 * @param a
 * @param b
 * @returns {number}
 */
function sortByDepthOfPath(a, b) {
  // sort by the depth of the path, so we can have domain.com/ and domain.com/foo/ as two separate sites
  return a.path.split('/').length - b.path.split('/').length;
}

/**
 * @param hostname
 * @returns {{slug: string, name: string, host: string, path: string}}
 * @example
 *
 *  www.example.com becomes:
 *
 *  {
 *    slug: example
 *    name: Example
 *    host: www.example.com
 *    path: '/'
 *  }
 */
function getDefaultSiteSettings(hostname) {
  var name = _.takeRight(hostname.split('.'), 2)[0]; //penultimate or last

  return {
    slug: name.toLowerCase(),
    name: _.startCase(name),
    host: hostname,
    path: '/'
  };
}

/**
 * Default way to load site controllers.
 *
 * @param {express.Router} router
 * @param {object} data  Extra information to help load controllers
 * @returns {function}
 */
function resolveSiteController(router, data) {
  var controllerPath = path.join(sitesFolder, data.slug);
  return require(controllerPath)(router, composer);
}

/**
 * @param {express.Router} router
 * @param {string} hostname
 * @param {object} [options]
 * @param {array} [options.sites]
 * @param {object} [options.siteResolver] Site router
 *
 * @example addHost('www.example.com');
 */
function addHost(router, hostname, options) {
  options = options || {};
  var hostRouter = express.Router(),
    sites = options.sites || [getDefaultSiteSettings(hostname)];

  _.each(sites, function (site) {
    //pass whatever options were given for the host, plus any extra information for the site.
    addSite(hostRouter, _.defaults(site, options));
  });

  // once all sites are added, wrap them in a vhost
  router.use(vhost(hostname, hostRouter));
}

/**
 * @param router  Often an express app.
 * @returns {*}
 * @example
 *   var app = express();
 *   require('./routes)(app);
 */
function loadFromConfig(router) {
  var siteHosts = siteService.hosts(),
    sitesMap = siteService.sites(),
    hostMap = config.get('hosts'); //includes local.yaml

  // iterate through the hosts
  _.each(siteHosts, function (hostname) {
    var sites = _.filter(sitesMap, {host: hostname}).sort(sortByDepthOfPath),
      localHostname = hostMap[hostname] || hostname;

    addHost(router, localHostname, {
      sites: sites,
      siteResolver: resolveSiteController
    });
  });
  return router;
}

module.exports = loadFromConfig;
module.exports.addSite = addSite;
module.exports.addHost = addHost;
module.exports.getDefaultSiteSettings = getDefaultSiteSettings;
module.exports.sortByDepthOfPath = sortByDepthOfPath;<|endoftext|>