<commit_before>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var bump = require('gulp-bump');
var header = require('gulp-header');
var modRewrite = require('connect-modrewrite');
var qunit = require('node-qunit-phantomjs');
var runSequence = require('run-sequence');
var argv = require('yargs').argv;

var config = {
	paths: {
		scripts: ['./js/jquery.responsiveTabs.js'],
		images: 'client/img/**/*'
	}
};

gulp.task('release', function(cb) {
    runSequence('bump', 'build', cb);
});

// Build
gulp.task('build', function() {
    var pkg = require('./package.json');
    var banner = ['/**',
        ' * <%= pkg.name %>',
        ' * ',
        ' * <%= pkg.description %>',
        ' * ',
        ' * @author <%= pkg.author %>',
        ' * @version v<%= pkg.version %>',
        ' * @license <%= pkg.license %>',
        ' */',
        ''].join('\n');

	return gulp.src(config.paths.scripts)
		.pipe(uglify({
			preserveComments: 'some'
		}))
        .pipe(header(banner, { pkg : pkg } ))
		.pipe(rename({
			extname: '.min.js'
		}))
		.pipe(gulp.dest('js/'));
});

// Bump
gulp.task('bump', function() {
    var bumpOpts = {};

    if ('v' in argv) {
        bumpOpts.type = argv.v;
    }

    return gulp.src(['./package.json'])
        .pipe(bump(bumpOpts))
        .pipe(gulp.dest('./'));
});

// Lint
gulp.task('lint', function() {
	return gulp.src(config.paths.scripts)
		.pipe(jshint())
		.pipe(jshint.reporter('default'));
});

// Test
gulp.task('test', function() {
	qunit('./test/fixture.html');
});

// Watch
gulp.task('watch', function() {
	gulp.watch(config.paths.scripts, ['lint']);
});

// Serve
gulp.task('serve', ['watch'], function() {
    browserSync.init({
        server: {
            baseDir: './',
            middleware: [
				modRewrite([
					'^/$ /demo.html'
				])
			]
        }
    });

    gulp.watch('*.html').on('change', browserSync.reload);
});

gulp.task('default', ['serve']);<commit_msg>Tests should be run before build and release<commit_after>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var bump = require('gulp-bump');
var header = require('gulp-header');
var modRewrite = require('connect-modrewrite');
var qunit = require('node-qunit-phantomjs');
var runSequence = require('run-sequence');
var argv = require('yargs').argv;

var config = {
	paths: {
		scripts: ['./js/jquery.responsiveTabs.js'],
		images: 'client/img/**/*'
	}
};

gulp.task('release', function(cb) {
    runSequence('test', 'bump', 'build', cb);
});

// Build
gulp.task('build', ['test'], function() {
    var pkg = require('./package.json');
    var banner = ['/**',
        ' * <%= pkg.name %>',
        ' * ',
        ' * <%= pkg.description %>',
        ' * ',
        ' * @author <%= pkg.author %>',
        ' * @version v<%= pkg.version %>',
        ' * @license <%= pkg.license %>',
        ' */',
        ''].join('\n');

	return gulp.src(config.paths.scripts)
		.pipe(uglify({
			preserveComments: 'some'
		}))
        .pipe(header(banner, { pkg : pkg } ))
		.pipe(rename({
			extname: '.min.js'
		}))
		.pipe(gulp.dest('js/'));
});

// Bump
gulp.task('bump', function() {
    var bumpOpts = {};

    if ('v' in argv) {
        bumpOpts.type = argv.v;
    }

    return gulp.src(['./package.json'])
        .pipe(bump(bumpOpts))
        .pipe(gulp.dest('./'));
});

// Lint
gulp.task('lint', function() {
	return gulp.src(config.paths.scripts)
		.pipe(jshint())
		.pipe(jshint.reporter('default'));
});

// Test
gulp.task('test', function() {
	qunit('./test/fixture.html');
});

// Watch
gulp.task('watch', function() {
	gulp.watch(config.paths.scripts, ['lint']);
});

// Serve
gulp.task('serve', ['watch'], function() {
    browserSync.init({
        server: {
            baseDir: './',
            middleware: [
				modRewrite([
					'^/$ /demo.html'
				])
			]
        }
    });

    gulp.watch('*.html').on('change', browserSync.reload);
});

gulp.task('default', ['serve']);
<|endoftext|>


<commit_before>
var fs = require('fs');
var gulp = require('gulp');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');
var CleanCSS = require('clean-css');

var cssfile = './lib/console.css';
var cssholder = '/* CONSOLE CSS */';

gulp.task('build', function(){
  gulp.src('lib/console.js')
  .pipe(replace(cssholder, new CleanCSS().minify(fs.readFileSync(cssfile)).styles))
  .pipe(uglify())
  .pipe(rename('console.min.js'))
  .pipe(gulp.dest('./lib/'));
});
<commit_msg>(chore) add `gulp watch`<commit_after>
var fs = require('fs');
var gulp = require('gulp');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');
var CleanCSS = require('clean-css');

var cssfile = './lib/console.css';
var cssholder = '/* CONSOLE CSS */';

gulp.task('build', function(){
  gulp.src('lib/console.js')
  .pipe(replace(
    cssholder,
    new CleanCSS().minify(fs.readFileSync(cssfile)).styles)
  )
  .pipe(uglify())
  .pipe(rename('console.min.js'))
  .pipe(gulp.dest('./lib/'));
});

gulp.task('watch', function(){
  gulp.watch([
    'lib/console.css',
    'lib/console.js'
  ], ['build'])
})
<|endoftext|>


<commit_before>/* eslint-disable security/detect-non-literal-fs-filename */
const chai = require('chai')
const chaiHttp = require('chai-http')
const config = require('config')

chai.use(chaiHttp)

// it is indirectly used at here res.should.have.status
// eslint-disable-next-line no-unused-vars
const should = chai.Should()

/**
 * Integration test using localhost (not mocked)
 */
describe('/passport/metrics - metrics endpoint (integration)', () => {
  const gluuBasePath = 'http://127.0.0.1:8090'

  // server should be up and running, integration test
  // health check used to inspect req.session.cookie
  it('Health check - GET /passport/health-check', (done) => {
    const sameSiteConfig = config.get('sameSite')
    const secureConfig = config.get('secure')
    chai.request(gluuBasePath)
      .get('/passport/health-check')
      .set('Cookie', 'SameSite=None')
      .end((_err, res) => {
        console.log(res.body)
        res.body.sessionCookie.should.include(
          {
            sameSite: sameSiteConfig,
            secure: secureConfig
          }
        )
        done()
      })
  })
})
<commit_msg>test(session): remove unneeded print<commit_after>/* eslint-disable security/detect-non-literal-fs-filename */
const chai = require('chai')
const chaiHttp = require('chai-http')
const config = require('config')

chai.use(chaiHttp)

// it is indirectly used at here res.should.have.status
// eslint-disable-next-line no-unused-vars
const should = chai.Should()

/**
 * Integration test using localhost (not mocked)
 */
describe('/passport/metrics - metrics endpoint (integration)', () => {
  const gluuBasePath = 'http://127.0.0.1:8090'

  // server should be up and running, integration test
  // health check used to inspect req.session.cookie
  it('Health check - GET /passport/health-check', (done) => {
    const sameSiteConfig = config.get('sameSite')
    const secureConfig = config.get('secure')
    chai.request(gluuBasePath)
      .get('/passport/health-check')
      .set('Cookie', 'SameSite=None')
      .end((_err, res) => {
        res.body.sessionCookie.should.include(
          {
            sameSite: sameSiteConfig,
            secure: secureConfig
          }
        )
        done()
      })
  })
})
<|endoftext|>


<commit_before>// Gulp tasks for Tachyons

// Load plugins
var gulp = require('gulp'),
    watch = require('gulp-watch'),
    prefix = require('gulp-autoprefixer'),
    minifyCSS = require('gulp-minify-css'),
    sass = require('gulp-sass'),
    size = require('gulp-size'),
    rename = require('gulp-rename');

// Task that compiles scss files down to good old css
gulp.task('pre-process', function(){
  gulp.src('./forms.scss')
      .pipe(watch('./forms.scss', function(files) {
        return files.pipe(sass())
          .pipe(size({gzip: false, showFiles: true, title:'un-prefixed css'}))
          .pipe(size({gzip: true, showFiles: true, title:'un-prefixed gzipped css'}))
          .pipe(prefix())
          .pipe(size({gzip: false, showFiles: true, title:'prefixed css'}))
          .pipe(size({gzip: true, showFiles: true, title:'prefixed css'}))
          .pipe(gulp.dest('./'))
          .pipe(minifyCSS())
          .pipe(rename('forms.min.css'))
          .pipe(gulp.dest('./'))
          .pipe(size({gzip: false, showFiles: true, title:'minified css'}))
          .pipe(size({gzip: true, showFiles: true, title:'minified css'}))
      }));
});

/*
   DEFAULT TASK
*/

gulp.task('default', ['pre-process'], function(){
  gulp.start('pre-process');
  gulp.watch('*.scss', ['pre-process']);
});

<commit_msg>Update reference path to css source in gulpfile<commit_after>var gulp = require('gulp'),
    rename = require('gulp-rename'),
    basswork = require('gulp-basswork'),
    minifyCss = require('gulp-minify-css'),
    transform = require('vinyl-transform'),
    size = require('gulp-size'),
    webserver = require('gulp-webserver');

gulp.task('css', function() {
  gulp.src('./src/tachyons-forms.css')
    .pipe(basswork())
    .pipe(size({gzip: true, showFiles: true, title:'prefixed'}))
    .pipe(gulp.dest('./'))
    .pipe(minifyCss())
    .pipe(size({gzip: true, showFiles: true, title:'minified'}))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./'));
});

gulp.task('serve', function() {
  gulp.src('.')
    .pipe(webserver({}));
});

gulp.task('default', ['css', 'serve'], function() {
  gulp.watch(['./src/**/*'], ['css']);
});

<|endoftext|>


<commit_before>const gulp = require('gulp')

const moduleName = 'Vuet'
const destName = 'vuet'

const eslint = require('gulp-eslint')
const clear = require('clear')
gulp.task('lint', () => {
  clear()
  return gulp.src(['**/*.js', '!node_modules/**', '!dist/**'])
    .pipe(eslint())
    .pipe(eslint.format())
})

const { rollup } = require('rollup')
const babel = require('rollup-plugin-babel')({
  babelrc: false,
  presets: [
    ['es2015-rollup'],
    'stage-0'
  ]
})
const uglify = require('rollup-plugin-uglify')
const { minify } = require('uglify-js')
const replace = require('rollup-plugin-replace')
gulp.task('build', ['lint'], () => {
  // Development environment version
  return rollup({
    entry: 'src/index.js',
    plugins: [babel]
  }).then((bundle) => {
    return bundle.write({
      moduleName,
      format: 'umd',
      dest: `dist/${destName}.js`,
      sourceMap: true,
      exports: 'named'
    })
  }).then(() => {
    // Production environment version
    return rollup({
      entry: 'src/index.js',
      plugins: [
        babel,
        replace({
          'process.env.NODE_ENV': JSON.stringify('production')
        }),
        uglify({
          compress: {
            drop_debugger: true,
            drop_console: true
          }
        }, minify)
      ]
    })
  }).then((bundle) => {
    return bundle.write({
      moduleName,
      format: 'umd',
      dest: `dist/${destName}.min.js`,
      sourceMap: true,
      exports: 'named'
    })
  })
})

const ava = require('gulp-ava')
gulp.task('unit', ['build'], () => {
  return gulp.src('test/unit/**.test.js')
  .pipe(ava({
    verbose: true // Enable verbose output
  }))
})

const testcafe = require('gulp-testcafe')
gulp.task('e2e', ['unit'], () => {
  return gulp.src('test/e2e/**.test.js')
    .pipe(testcafe({ browsers: ['chrome', 'firefox'] }))
})

gulp.task('test', ['lint', 'build', 'unit', 'e2e'])
gulp.task('default', ['lint', 'build', 'unit', 'e2e'])

if (process.env.NODE_ENV === 'development') {
  gulp.watch(['**/*.js', '**/*.vue', '!node_modules/**', '!dist/**'], ['default'])
}
<commit_msg>test:fix<commit_after>const gulp = require('gulp')

const moduleName = 'Vuet'
const destName = 'vuet'

const eslint = require('gulp-eslint')
const clear = require('clear')
gulp.task('lint', () => {
  clear()
  return gulp.src(['**/*.js', '!node_modules/**', '!dist/**'])
    .pipe(eslint())
    .pipe(eslint.format())
})

const { rollup } = require('rollup')
const babel = require('rollup-plugin-babel')({
  babelrc: false,
  presets: [
    ['es2015-rollup'],
    'stage-0'
  ]
})
const uglify = require('rollup-plugin-uglify')
const { minify } = require('uglify-js')
const replace = require('rollup-plugin-replace')
gulp.task('build', ['lint'], () => {
  // Development environment version
  return rollup({
    entry: 'src/index.js',
    plugins: [babel]
  }).then((bundle) => {
    return bundle.write({
      moduleName,
      format: 'umd',
      dest: `dist/${destName}.js`,
      sourceMap: true,
      exports: 'named'
    })
  }).then(() => {
    // Production environment version
    return rollup({
      entry: 'src/index.js',
      plugins: [
        babel,
        replace({
          'process.env.NODE_ENV': JSON.stringify('production')
        }),
        uglify({
          compress: {
            drop_debugger: true,
            drop_console: true
          }
        }, minify)
      ]
    })
  }).then((bundle) => {
    return bundle.write({
      moduleName,
      format: 'umd',
      dest: `dist/${destName}.min.js`,
      sourceMap: true,
      exports: 'named'
    })
  })
})

const ava = require('gulp-ava')
gulp.task('unit', ['build'], () => {
  return gulp.src('test/unit/**.test.js')
  .pipe(ava({
    verbose: true // Enable verbose output
  }))
})
const testcafe = require('gulp-testcafe')
gulp.task('e2e', ['unit'], () => {
  if (process.env.NODE_ENV === 'testing') {
    require('examples/server')
  }
  return gulp.src('test/e2e/**.test.js')
    .pipe(testcafe({ browsers: ['chrome', 'firefox'] }))
})

gulp.task('test', ['lint', 'build', 'unit', 'e2e'])
gulp.task('default', ['lint', 'build', 'unit', 'e2e'])

if (process.env.NODE_ENV === 'development') {
  gulp.watch(['**/*.js', '**/*.vue', '!node_modules/**', '!dist/**'], ['default'])
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat-util');
var indent = require('gulp-indent');
var wrap = require('gulp-wrap');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');

var del = require('del');
var map = require('vinyl-map');

var target = 'glpt.js';

gulp.task('jshint:src', function() {

  return gulp.src('src/*.js')

    .pipe(jshint())
    .pipe(jshint.reporter('default'))
});

gulp.task('test');

gulp.task('clean:dist', function () {

  return del('dist/*');
});

gulp.task('transpile:shaders', function() {

  return gulp.src('src/shaders/*.glsl')

    .pipe(map(function(code, filename) {

      var shader_type = filename.slice(

        filename.lastIndexOf('\\') + 1,
        filename.indexOf('.')
      );

      code = code.toString();

      return 'var ' + shader_type + '_shader = "" +\n  ' +

        code.split('\n')
            .map(function(x) { return '"' + x.trim() + '"'; })
            .join(' +\n  ') +
        ';';
    }))

    .pipe(rename(function (path) { path.extname = ".js"; }))
    .pipe(gulp.dest('src/shaders/'));
});

gulp.task('concat:dist', ['clean:dist', 'transpile:shaders'], function() {

  return gulp.src([

    'src/shaders/vertex.js',
    'src/shaders/fragment.js',

    'src/js/Primitive.js',
    'src/js/Material.js',
    'src/js/Light.js',
    'src/js/Stratifier.js',
    'src/js/Renderer.js',
    'src/js/index.js'
  ])

    .pipe(concat(target, {

      process: function (src) {

        var i = src.indexOf('*/');

        if (i !== -1) {

          return src.slice(i + 2).trim() + '\n';
        }

        else { return src + '\n'; }
      }
    }))

    .pipe(gulp.dest('dist'));
});

gulp.task('wrap:dist', ['concat:dist'], function() {

  return gulp.src('dist/' + target)

    .pipe(indent({

      tabs: false,
      amount: 2
    }))

    .pipe(wrap(

      '/**\n' +
      ' * @author Raoul Harel\n' +
      ' * @license The MIT license (LICENSE.txt)\n' +
      ' * @copyright 2015 Raoul Harel\n' +
      ' * @url https://github.com/rharel/webgl-pathtracer\n' +
      ' */\n' +
      '\n\n' +
      '(function () {\n\n' +
      '<%= contents %>\n' +
      '})();\n'
    ))

    .pipe(gulp.dest('dist'));
});

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

gulp.task('default', ['build']);<commit_msg>fixed jshint src issue and added newlines to transpile:shaders<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat-util');
var indent = require('gulp-indent');
var wrap = require('gulp-wrap');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');

var del = require('del');
var map = require('vinyl-map');

var target = 'glpt.js';

gulp.task('jshint:src', function() {

  return gulp.src('src/**/*.js')

    .pipe(jshint())
    .pipe(jshint.reporter('default'))
});

gulp.task('jshint:dist', ['jshint:src', 'build'], function() {

  return gulp.src('dist/' + target)

    .pipe(jshint())
    .pipe(jshint.reporter('default'))
});

gulp.task('test');

gulp.task('clean:dist', function () {

  return del('dist/*');
});

gulp.task('transpile:shaders', function() {

  return gulp.src('src/shaders/*.glsl')

    .pipe(map(function(code, filename) {

      var shader_type = filename.slice(

        filename.lastIndexOf('\\') + 1,
        filename.indexOf('.')
      );

      code = code.toString();

      return 'var ' + shader_type.toUpperCase() + '_SHADER_SOURCE = "" +\n  ' +

        code.split('\n')
            .map(function(x) { return '"' + x.replace(/\s+$/, '') + '\\n"'; })
            .join(' +\n  ') +
        ';';
    }))

    .pipe(rename(function (path) { path.extname = ".js"; }))
    .pipe(gulp.dest('src/shaders/'));
});

gulp.task('concat:dist', ['clean:dist', 'transpile:shaders'], function() {

  return gulp.src([

    'src/shaders/vertex.js',
    'src/shaders/fragment.js',

    'src/js/Primitive.js',
    'src/js/Material.js',
    'src/js/Light.js',
    'src/js/Stratifier.js',
    'src/js/Renderer.js',
    'src/js/index.js'
  ])

    .pipe(concat(target, {

      process: function (src) {

        var i = src.indexOf('*/');

        if (i !== -1) {

          return src.slice(i + 2).trim() + '\n';
        }

        else { return src + '\n'; }
      }
    }))

    .pipe(gulp.dest('dist'));
});

gulp.task('wrap:dist', ['concat:dist'], function() {

  return gulp.src('dist/' + target)

    .pipe(indent({

      tabs: false,
      amount: 2
    }))

    .pipe(wrap(

      '/**\n' +
      ' * @author Raoul Harel\n' +
      ' * @license The MIT license (LICENSE.txt)\n' +
      ' * @copyright 2015 Raoul Harel\n' +
      ' * @url https://github.com/rharel/webgl-pathtracer\n' +
      ' */\n' +
      '\n\n' +
      '(function () {\n\n' +
      '<%= contents %>\n' +
      '})();\n'
    ))

    .pipe(gulp.dest('dist'));
});

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

gulp.task('default', ['build']);<|endoftext|>


<commit_before>/**
 * gulpfile.js
 * @task - loads all tasks from `./internals/gulp/tasks/*`
 */
const argv = require('yargs').boolean('p').argv;
const glob = require('glob');
const gutil = require('gulp-util');
const path = require('path');

const isProduction = argv.p;

gutil.log(gutil.colors.bold('ℹ  Blaupause v2.5.0'));

if (isProduction) {
  gutil.log(gutil.colors.bold.green('🚚  Production Mode'));
} else {
  gutil.log(gutil.colors.bold.green('🔧  Development Mode'));
}

glob.sync('./internals/gulp/tasks/*.js').forEach((file) => {
  require(path.resolve(file)); // eslint-disable-line
});
<commit_msg>Dynamically bump cli info<commit_after>/**
 * gulpfile.js
 * @task - loads all tasks from `./internals/gulp/tasks/*`
 */
const argv = require('yargs').boolean('p').argv;
const glob = require('glob');
const gutil = require('gulp-util');
const path = require('path');

const pkg = require('./package.json');

const isProduction = argv.p;

gutil.log(gutil.colors.bold(`ℹ  ${pkg.name} v${pkg.version}`));

if (isProduction) {
  gutil.log(gutil.colors.bold.green('🚚  Production Mode'));
} else {
  gutil.log(gutil.colors.bold.green('🔧  Development Mode'));
}

glob.sync('./internals/gulp/tasks/*.js').forEach((file) => {
  require(path.resolve(file)); // eslint-disable-line
});
<|endoftext|>


<commit_before>var {series} = require('gulp');
var execFile = require('child_process').execFile;
var glob = require('glob');
var fs = require('fs');

function exec(command, cb) {
  execFile('sh', ['-c', command], cb);
}

var plugin =   '--plugin=protoc-gen-js=bazel-bin/generator/protoc-gen-js';
var protoc = [(process.env.PROTOC || 'protoc'), plugin].join(' ');
var protocInc = process.env.PROTOC_INC || '../src';

var wellKnownTypes = [
  'google/protobuf/any.proto',
  'google/protobuf/api.proto',
  'google/protobuf/compiler/plugin.proto',
  'google/protobuf/descriptor.proto',
  'google/protobuf/duration.proto',
  'google/protobuf/empty.proto',
  'google/protobuf/field_mask.proto',
  'google/protobuf/source_context.proto',
  'google/protobuf/struct.proto',
  'google/protobuf/timestamp.proto',
  'google/protobuf/type.proto',
  'google/protobuf/wrappers.proto',
];

wellKnownTypes.forEach((path, i) => protocInc + '/' + path);

var group1Protos = [
  'data.proto',
  'test3.proto',
  'test5.proto',
  'commonjs/test6/test6.proto',
  'test8.proto',
  'test11.proto',
  'test12.proto',
  'test13.proto',
  'test14.proto',
  'test15.proto',
  'testbinary.proto',
  'testempty.proto',
  'test.proto',
  'testlargenumbers.proto',
];

var group2Protos = [
  'proto3_test.proto',
  'test2.proto',
  'test4.proto',
  'commonjs/test7/test7.proto',
];

var group3Protos = [
  'test9.proto',
  'test10.proto'
];

function make_exec_logging_callback(cb) {
  return (err, stdout, stderr) => {
    console.log(stdout);
    console.error(stderr);
    cb(err);
  }
}

function genproto_well_known_types_closure(cb) {
  exec(protoc + ' --js_out=one_output_file_per_input_file,binary:. -I ' + protocInc + ' -I . ' + wellKnownTypes.join(' '),
       make_exec_logging_callback(cb));
}

function genproto_group1_closure(cb) {
  exec(protoc + ' --js_out=library=testproto_libs1,binary:.  -I ' + protocInc + ' -I . ' + group1Protos.join(' '),
       make_exec_logging_callback(cb));
}

function genproto_group2_closure(cb) {
  exec(
      protoc +
        ' --experimental_allow_proto3_optional' +
        ' --js_out=library=testproto_libs2,binary:.  -I ' + protocInc + ' -I . -I commonjs ' +
        group2Protos.join(' '),
      make_exec_logging_callback(cb));
}

function genproto_well_known_types_commonjs(cb) {
            exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ' + protocInc + ' ' + wellKnownTypes.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_group1_commonjs(cb) {
            exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ' + protocInc + ' -I commonjs -I . ' + group1Protos.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_group2_commonjs(cb) {
  exec(
      'mkdir -p commonjs_out && ' + protoc +
        ' --experimental_allow_proto3_optional --js_out=import_style=commonjs,binary:commonjs_out -I ' + protocInc + ' -I commonjs -I . ' +
        group2Protos.join(' '),
      make_exec_logging_callback(cb));
}

function genproto_commonjs_wellknowntypes(cb) {
            exec('mkdir -p commonjs_out/node_modules/google-protobuf && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out/node_modules/google-protobuf -I ' + protocInc + ' ' + wellKnownTypes.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_wellknowntypes(cb) {
            exec(protoc + ' --js_out=import_style=commonjs,binary:. -I ' + protocInc + ' ' + wellKnownTypes.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_group3_commonjs_strict(cb) {
            exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs_strict,binary:commonjs_out -I ' + protocInc + ' -I commonjs -I . ' + group3Protos.join(' '),
                 make_exec_logging_callback(cb));
}

function getClosureCompilerCommand(exportsFile, outputFile) {
  const closureLib = 'node_modules/google-closure-library';
  return [
    'node_modules/.bin/google-closure-compiler',
    `--js=${closureLib}/closure/goog/**.js`,
    `--js=${closureLib}/third_party/closure/goog/**.js`, '--js=map.js',
    '--js=message.js', '--js=binary/arith.js', '--js=binary/constants.js',
    '--js=binary/decoder.js', '--js=binary/encoder.js', '--js=binary/reader.js',
    '--js=binary/utils.js', '--js=binary/writer.js', `--js=${exportsFile}`,
    `--entry_point=${exportsFile}`, `> ${outputFile}`
  ].join(' ');
}

function gen_google_protobuf_js(cb) {
  // TODO(haberman): minify this more aggressively.
  // Will require proper externs/exports.
  var log_file = fs.createWriteStream('/usr/local/google/home/dibenede/gulp.log', {flags:'w'});
  exec(
      getClosureCompilerCommand('commonjs/export.js', 'google-protobuf.js'),
      make_exec_logging_callback(cb));
}

function commonjs_asserts(cb) {
            exec(
                'mkdir -p commonjs_out/test_node_modules && ' +
                  getClosureCompilerCommand(
                      'commonjs/export_asserts.js',
                      'commonjs_out/test_node_modules/closure_asserts_commonjs.js'),
                make_exec_logging_callback(cb));
}

function commonjs_testdeps(cb) {
            exec(
                'mkdir -p commonjs_out/test_node_modules && ' +
                  getClosureCompilerCommand(
                      'commonjs/export_testdeps.js',
                      'commonjs_out/test_node_modules/testdeps_commonjs.js'),
                make_exec_logging_callback(cb));
}

function commonjs_out(cb) {
          // TODO(haberman): minify this more aggressively.
          // Will require proper externs/exports.
          var cmd =
              'mkdir -p commonjs_out/binary && mkdir -p commonjs_out/test_node_modules && ';
          function addTestFile(file) {
            cmd += 'node commonjs/rewrite_tests_for_commonjs.js < ' + file +
                ' > commonjs_out/' + file + '&& ';
          }

          glob.sync('*_test.js').forEach(addTestFile);
          glob.sync('binary/*_test.js').forEach(addTestFile);

          exec(
              cmd + 'cp commonjs/jasmine.json commonjs_out/jasmine.json && ' +
                'cp google-protobuf.js commonjs_out/test_node_modules && ' +
                'cp commonjs/strict_test.js commonjs_out/strict_test.js &&' +
                'cp commonjs/import_test.js commonjs_out/import_test.js',
              make_exec_logging_callback(cb));
}

function closure_make_deps(cb) {
  exec(
      './node_modules/.bin/closure-make-deps --closure-path=. --file=node_modules/google-closure-library/closure/goog/deps.js binary/arith.js binary/constants.js binary/decoder.js binary/encoder.js binary/reader.js binary/utils.js binary/writer.js debug.js map.js message.js node_loader.js test_bootstrap.js > deps.js',
      make_exec_logging_callback(cb));
}

function test_closure(cb) {
  exec(
      'JASMINE_CONFIG_PATH=jasmine.json ./node_modules/.bin/jasmine',
      make_exec_logging_callback(cb));
}

function test_commonjs(cb) {
  exec('cd commonjs_out && JASMINE_CONFIG_PATH=jasmine.json NODE_PATH=test_node_modules ../node_modules/.bin/jasmine',
       make_exec_logging_callback(cb));
}

exports.build_protoc_plugin = function (cb) {
  exec('bazel build generator:protoc-gen-js',
       make_exec_logging_callback(cb));
}

exports.dist = series(exports.build_protoc_plugin,
                      genproto_wellknowntypes,
                      gen_google_protobuf_js);

exports.make_commonjs_out = series(
    exports.dist,
    genproto_well_known_types_commonjs,
    genproto_group1_commonjs, genproto_group2_commonjs,
    genproto_commonjs_wellknowntypes, commonjs_asserts,
    commonjs_testdeps, genproto_group3_commonjs_strict,
    commonjs_out);

exports.deps = series(exports.build_protoc_plugin,
                      genproto_well_known_types_closure,
                      genproto_group1_closure,
                      genproto_group2_closure,
                      closure_make_deps);

exports.test_closure = series(exports.deps,
                              test_closure);

exports.test_commonjs = series(exports.make_commonjs_out,
                               test_commonjs);

exports.test = series(exports.test_closure,
                      exports.test_commonjs);
<commit_msg>Fixup build and docs after move to standalone repo<commit_after>var {series} = require('gulp');
var execFile = require('child_process').execFile;
var glob = require('glob');
var fs = require('fs');

function exec(command, cb) {
  execFile('sh', ['-c', command], cb);
}

var plugin =   '--plugin=protoc-gen-js=bazel-bin/generator/protoc-gen-js';
var protoc = [(process.env.PROTOC || 'protoc'), plugin].join(' ');
var protocInc = process.env.PROTOC_INC || '../src';

var wellKnownTypes = [
  'google/protobuf/any.proto',
  'google/protobuf/api.proto',
  'google/protobuf/compiler/plugin.proto',
  'google/protobuf/descriptor.proto',
  'google/protobuf/duration.proto',
  'google/protobuf/empty.proto',
  'google/protobuf/field_mask.proto',
  'google/protobuf/source_context.proto',
  'google/protobuf/struct.proto',
  'google/protobuf/timestamp.proto',
  'google/protobuf/type.proto',
  'google/protobuf/wrappers.proto',
];

wellKnownTypes.forEach((path, i) => protocInc + '/' + path);

var group1Protos = [
  'data.proto',
  'test3.proto',
  'test5.proto',
  'commonjs/test6/test6.proto',
  'test8.proto',
  'test11.proto',
  'test12.proto',
  'test13.proto',
  'test14.proto',
  'test15.proto',
  'testbinary.proto',
  'testempty.proto',
  'test.proto',
  'testlargenumbers.proto',
];

var group2Protos = [
  'proto3_test.proto',
  'test2.proto',
  'test4.proto',
  'commonjs/test7/test7.proto',
];

var group3Protos = [
  'test9.proto',
  'test10.proto'
];

function make_exec_logging_callback(cb) {
  return (err, stdout, stderr) => {
    console.log(stdout);
    console.error(stderr);
    cb(err);
  }
}

function genproto_well_known_types_closure(cb) {
  exec(protoc + ' --js_out=one_output_file_per_input_file,binary:. -I ' + protocInc + ' -I . ' + wellKnownTypes.join(' '),
       make_exec_logging_callback(cb));
}

function genproto_group1_closure(cb) {
  exec(protoc + ' --js_out=library=testproto_libs1,binary:.  -I ' + protocInc + ' -I . ' + group1Protos.join(' '),
       make_exec_logging_callback(cb));
}

function genproto_group2_closure(cb) {
  exec(
      protoc +
        ' --experimental_allow_proto3_optional' +
        ' --js_out=library=testproto_libs2,binary:.  -I ' + protocInc + ' -I . -I commonjs ' +
        group2Protos.join(' '),
      make_exec_logging_callback(cb));
}

function genproto_well_known_types_commonjs(cb) {
            exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ' + protocInc + ' ' + wellKnownTypes.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_group1_commonjs(cb) {
            exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ' + protocInc + ' -I commonjs -I . ' + group1Protos.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_group2_commonjs(cb) {
  exec(
      'mkdir -p commonjs_out && ' + protoc +
        ' --experimental_allow_proto3_optional --js_out=import_style=commonjs,binary:commonjs_out -I ' + protocInc + ' -I commonjs -I . ' +
        group2Protos.join(' '),
      make_exec_logging_callback(cb));
}

function genproto_commonjs_wellknowntypes(cb) {
            exec('mkdir -p commonjs_out/node_modules/google-protobuf && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out/node_modules/google-protobuf -I ' + protocInc + ' ' + wellKnownTypes.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_wellknowntypes(cb) {
            exec(protoc + ' --js_out=import_style=commonjs,binary:. -I ' + protocInc + ' ' + wellKnownTypes.join(' '),
                 make_exec_logging_callback(cb));
}

function genproto_group3_commonjs_strict(cb) {
            exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs_strict,binary:commonjs_out -I ' + protocInc + ' -I commonjs -I . ' + group3Protos.join(' '),
                 make_exec_logging_callback(cb));
}

function getClosureCompilerCommand(exportsFile, outputFile) {
  const closureLib = 'node_modules/google-closure-library';
  return [
    'node_modules/.bin/google-closure-compiler',
    `--js=${closureLib}/closure/goog/**.js`,
    `--js=${closureLib}/third_party/closure/goog/**.js`, '--js=map.js',
    '--js=message.js', '--js=binary/arith.js', '--js=binary/constants.js',
    '--js=binary/decoder.js', '--js=binary/encoder.js', '--js=binary/reader.js',
    '--js=binary/utils.js', '--js=binary/writer.js', `--js=${exportsFile}`,
    `--entry_point=${exportsFile}`, `> ${outputFile}`
  ].join(' ');
}

function gen_google_protobuf_js(cb) {
  // TODO(haberman): minify this more aggressively.
  // Will require proper externs/exports.
  exec(
      getClosureCompilerCommand('commonjs/export.js', 'google-protobuf.js'),
      make_exec_logging_callback(cb));
}

function commonjs_asserts(cb) {
            exec(
                'mkdir -p commonjs_out/test_node_modules && ' +
                  getClosureCompilerCommand(
                      'commonjs/export_asserts.js',
                      'commonjs_out/test_node_modules/closure_asserts_commonjs.js'),
                make_exec_logging_callback(cb));
}

function commonjs_testdeps(cb) {
            exec(
                'mkdir -p commonjs_out/test_node_modules && ' +
                  getClosureCompilerCommand(
                      'commonjs/export_testdeps.js',
                      'commonjs_out/test_node_modules/testdeps_commonjs.js'),
                make_exec_logging_callback(cb));
}

function commonjs_out(cb) {
          // TODO(haberman): minify this more aggressively.
          // Will require proper externs/exports.
          var cmd =
              'mkdir -p commonjs_out/binary && mkdir -p commonjs_out/test_node_modules && ';
          function addTestFile(file) {
            cmd += 'node commonjs/rewrite_tests_for_commonjs.js < ' + file +
                ' > commonjs_out/' + file + '&& ';
          }

          glob.sync('*_test.js').forEach(addTestFile);
          glob.sync('binary/*_test.js').forEach(addTestFile);

          exec(
              cmd + 'cp commonjs/jasmine.json commonjs_out/jasmine.json && ' +
                'cp google-protobuf.js commonjs_out/test_node_modules && ' +
                'cp commonjs/strict_test.js commonjs_out/strict_test.js &&' +
                'cp commonjs/import_test.js commonjs_out/import_test.js',
              make_exec_logging_callback(cb));
}

function closure_make_deps(cb) {
  exec(
      './node_modules/.bin/closure-make-deps --closure-path=. --file=node_modules/google-closure-library/closure/goog/deps.js binary/arith.js binary/constants.js binary/decoder.js binary/encoder.js binary/reader.js binary/utils.js binary/writer.js debug.js map.js message.js node_loader.js test_bootstrap.js > deps.js',
      make_exec_logging_callback(cb));
}

function test_closure(cb) {
  exec(
      'JASMINE_CONFIG_PATH=jasmine.json ./node_modules/.bin/jasmine',
      make_exec_logging_callback(cb));
}

function test_commonjs(cb) {
  exec('cd commonjs_out && JASMINE_CONFIG_PATH=jasmine.json NODE_PATH=test_node_modules ../node_modules/.bin/jasmine',
       make_exec_logging_callback(cb));
}

exports.build_protoc_plugin = function (cb) {
  exec('bazel build generator:protoc-gen-js',
       make_exec_logging_callback(cb));
}

exports.dist = series(exports.build_protoc_plugin,
                      genproto_wellknowntypes,
                      gen_google_protobuf_js);

exports.make_commonjs_out = series(
    exports.dist,
    genproto_well_known_types_commonjs,
    genproto_group1_commonjs, genproto_group2_commonjs,
    genproto_commonjs_wellknowntypes, commonjs_asserts,
    commonjs_testdeps, genproto_group3_commonjs_strict,
    commonjs_out);

exports.deps = series(exports.build_protoc_plugin,
                      genproto_well_known_types_closure,
                      genproto_group1_closure,
                      genproto_group2_closure,
                      closure_make_deps);

exports.test_closure = series(exports.deps,
                              test_closure);

exports.test_commonjs = series(exports.make_commonjs_out,
                               test_commonjs);

exports.test = series(exports.test_closure,
                      exports.test_commonjs);
<|endoftext|>


<commit_before>const gulp = require('gulp');
const template = require('gulp-template');
const data = require('gulp-data');
const debug = require('gulp-debug');
const fs = require('fs');

var preProcessPath = 'html.src/pre';
var today = new Date();
var month = today.getMonth() + 1;

const configJSON = fs.readFileSync('html.src/gulp_config.json');
const configDict = JSON.parse(configJSON);

const videoPath = configDict.videoPath;
const docsPath = configDict.docsPath;
const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();

//const contentBlocks = fs.readFileSync('html.src/gulp_contentBlocks.js');

htmlBlocks = {
	"header": "header.html",
	"footer": "footer.html",
	"footer_monitor": "footer.monitor.html",
	"header_2022": "header_2022.html"
};

html2process = {
	"static_version": staticVersion,
	"video_path": videoPath,
	"docs_path": docsPath,
	"company_name": configDict.companyName,
	"company": configDict.companyCode
};

for (const key in htmlBlocks) {
	if (fs.existsSync(preProcessPath+'/'+htmlBlocks[key])) {
		console.log(key + ' found');
		html2process[key] = fs.readFileSync(preProcessPath+'/'+htmlBlocks[key], 'utf8');
	}
	else {
		console.log(key + ' NOT found');
	}
}

gulp.task('hello', function() {
	console.log('Hello, Tony');
});

gulp.task('process', ['pre','js','css','jpegs','pngs','svg','gif','ico', 'dashboards'], () =>
	gulp.src('html.src/**/*.html')
		.pipe(data(() => (html2process)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pre', () =>
    gulp.src(preProcessPath+'/*.html')
        .pipe(data(() => (
            {
                "static_version": staticVersion,
				"video_path": videoPath,
				"docs_path": docsPath,
                "header": fs.readFileSync(preProcessPath+'/header.html', 'utf8'),
                "footer": fs.readFileSync(preProcessPath+'/footer.html', 'utf8'),
				"title": 'Interscan Corporation'
            }
        )))
        .pipe(template().on('error',function(e){
		console.log(e);
	}))
        .pipe(debug())
		.pipe(gulp.dest('tmp'))
);

gulp.task('js', () =>
	gulp.src('html.src/**/*.js')
		.pipe(data(() => (
			{
				"field": "content",
				"static_version": staticVersion,
				"num": "${num}"
			}
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('css', () =>
	gulp.src('html.src/**/*.css')
		.pipe(data(() => (
			{ "field": "content" }
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pngs', () =>
	gulp.src('html.src/**/*.png')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('svg', () =>
	gulp.src('html.src/**/*.svg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('jpegs', () =>
	gulp.src('html.src/**/*.jpg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('gif', () =>
	gulp.src('html.src/**/*.gif')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('ico', () =>
	gulp.src('html.src/**/*.ico')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('dashboards', () =>
	gulp.src('html.src/dashboards/**/*.html')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);
<commit_msg>Fixed gulp preprocessing<commit_after>const gulp = require('gulp');
const template = require('gulp-template');
const data = require('gulp-data');
const debug = require('gulp-debug');
const fs = require('fs');

var preProcessPath = 'html.src/pre';
var postProcessPath = 'tmp';
var today = new Date();
var month = today.getMonth() + 1;

const configJSON = fs.readFileSync('html.src/gulp_config.json');
const configDict = JSON.parse(configJSON);

const videoPath = configDict.videoPath;
const docsPath = configDict.docsPath;
//const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();
const staticVersion = "20220925";

//const contentBlocks = fs.readFileSync('html.src/gulp_contentBlocks.js');

htmlBlocks = {
	"header": "header.html",
	"footer": "footer.html",
	"footer_monitor": "footer.monitor.html",
	"header_2022": "header_2022.html"
};

html2process = {
	"static_version": staticVersion,
	"video_path": videoPath,
	"docs_path": docsPath,
	"company_name": configDict.companyName,
	"company": configDict.companyCode
};

for (const key in htmlBlocks) {
	if (fs.existsSync(postProcessPath+'/'+htmlBlocks[key])) {
		console.log(key + ' found');
		html2process[key] = fs.readFileSync(postProcessPath+'/'+htmlBlocks[key], 'utf8');
	}
	else {
		console.log(key + ' NOT found');
	}
}

gulp.task('hello', function() {
	console.log('Hello, Tony');
});

gulp.task('process', ['pre','js','css','jpegs','pngs','svg','gif','ico', 'dashboards'], () =>
	gulp.src('html.src/**/*.html')
		.pipe(data(() => (html2process)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pre', () =>
	gulp.src(preProcessPath+'/*.html')
		.pipe(data(() => (
			{
				"static_version": staticVersion,
				"video_path": videoPath,
				"docs_path": docsPath,
				"header": fs.readFileSync(preProcessPath+'/header.html', 'utf8'),
				"footer": fs.readFileSync(preProcessPath+'/footer.html', 'utf8'),
				"title": 'Interscan Corporation'
			}
		)))
		.pipe(template().on('error',function(e){
		console.log(e);
	}))
	.pipe(debug())
	.pipe(gulp.dest(postProcessPath))
);

gulp.task('js', () =>
	gulp.src('html.src/**/*.js')
		.pipe(data(() => (
			{
				"field": "content",
				"static_version": staticVersion,
				"num": "${num}"
			}
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('css', () =>
	gulp.src('html.src/**/*.css')
		.pipe(data(() => (
			{ "field": "content" }
		)))
		.pipe(template())
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('pngs', () =>
	gulp.src('html.src/**/*.png')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('svg', () =>
	gulp.src('html.src/**/*.svg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('jpegs', () =>
	gulp.src('html.src/**/*.jpg')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('gif', () =>
	gulp.src('html.src/**/*.gif')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('ico', () =>
	gulp.src('html.src/**/*.ico')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);

gulp.task('dashboards', () =>
	gulp.src('html.src/dashboards/**/*.html')
		.pipe(debug())
		.pipe(gulp.dest('html'))
);
<|endoftext|>


<commit_before><commit_msg>:bug: CSSビルド時のPlumberのerrorHandlerの終了方法が間違っていたので修正<commit_after><|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var eslint = require('gulp-eslint');
var mocha = require('gulp-mocha');
var git = require('gulp-git');
var del = require('rimraf');

var lint = ['index.js', 'lib/*.js'];

function url(repo) {
  return 'https://github.com/' + repo;
}

gulp.task('coverage', function() {
  return gulp.src(lint)
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('mocha', ['coverage'], function() {
  return gulp.src('test/*.js')
    .pipe(mocha({reporter: 'spec'}))
    .pipe(istanbul.writeReports());
});

gulp.task('eslint', function() {
  return gulp.src(lint)
    .pipe(eslint())
});

gulp.task('spec', ['clone'], function(cb) {
  gulp.src('test/_spec/test/*.js')
    .pipe(mocha({reporter: 'spec'}))
    .on('end', function() {
      del('test/_spec', cb);
    });
});

gulp.task('clone', function(cb) {
  del('test/_spec', function(err) {
    if (err) return cb(err);
    git.clone(url('jonschlinkert/templates'), {
      args: 'test/_spec'
    }, cb);
  });
});

gulp.task('default', ['mocha', 'eslint']);
<commit_msg>remove old test logic from gulpfile<commit_after>'use strict';

var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var eslint = require('gulp-eslint');
var mocha = require('gulp-mocha');

gulp.task('coverage', function() {
  return gulp.src(['index.js', 'lib/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('mocha', ['coverage'], function() {
  return gulp.src('test/*.js')
    .pipe(mocha({reporter: 'spec'}))
    .pipe(istanbul.writeReports());
});

gulp.task('eslint', function() {
  return gulp.src(['*.js', 'lib/*.js', 'test/*.js'])
    .pipe(eslint())
});

gulp.task('default', ['mocha', 'eslint']);
<|endoftext|>


<commit_before><commit_msg>add gulp-help to gulp instance<commit_after><|endoftext|>


<commit_before>'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var pagespeed = require('psi');
var htmlmin = require('gulp-htmlmin');
var replace = require('gulp-replace');
var pump = require('pump');

// Lint JavaScript
gulp.task('jshint', function() {
  return gulp.src(['js/compline.js', 'js/chant-element.js', 'js/calendar.js'])
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
  return gulp.src([
    '**/*.gabc',
    'js/require.js',
    'fonts/*.woff',
    'fonts/*.woff2',
    '!dist/**/*',
    '!node_modules/**/*'
  ], {
    dot: true,
    base: '.'
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function() {

  return gulp.src([
    '*.css'
  ])
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'styles'}));
});

// Build one javascript file:
gulp.task('scripts', function() {
  var requirejs = require('requirejs');

  requirejs.optimize({
    'findNestedDependencies': true,
    'baseUrl': './js/',
    'name': 'compline',
    'optimize': 'uglify2',
    'out': './dist/js/compline.js',
    'wrap': true,
    // 'onModuleBundleComplete': function(data) {
    //   var fs = require('fs'),
    //     amdclean = require('amdclean'),
    //     outputFile = data.path;

    //   fs.writeFileSync(outputFile, amdclean.clean({
    //     'wrap': {
    //       // This string is prepended to the file
    //       'start': ';(function() {\n',
    //       // This string is appended to the file
    //       'end': '\n}());'
    //     },
    //     removeUseStricts: false,
    //     shimOverrides: { jquery: 'jQuery' },
    //     'filePath': outputFile
    //   }));
    //}
  });
});

// Concatenate And Minify JavaScript
gulp.task('scripts_old', function(cb) {
  var sources = [
    'js/*.js'
  ];

  pump([
        gulp.src(sources, {base: '.'}),
        $.uglify(),
        gulp.dest('dist'),
        $.size({title: 'scripts'})
    ],
    cb
  );
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function() {

  return gulp.src(['*.html', 'psalms/**/*.html'], {base: '.'})
    // .pipe(replace(/data-main="([^"]+?)(?:\.js)?"\s+src="[^"]+\/require.js"/,'src="$1.js"'))
    // Replace ǽ with æ, since the font we are using right now doesn't look right with the ǽ character,
    // even when trying to use combining diacritics æ\u0301
    // .pipe(replace('ǽ','æ'))
    // The bold unicode accent character for producing œ́ doesn't work, so make sure the accent itself isn't bold
    .pipe(replace(/([^<]+œ)(́)/g, '$1$2'))
    // Minify Any HTML
    .pipe(htmlmin({collapseWhitespace: true, removeComments: true}))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default']);

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function(cb) {
  runSequence('copy', ['html', 'styles', 'scripts'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://compline.us.to',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }<commit_msg>Concatenate css<commit_after>'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var pagespeed = require('psi');
var htmlmin = require('gulp-htmlmin');
var replace = require('gulp-replace');
var pump = require('pump');

// Lint JavaScript
gulp.task('jshint', function() {
  return gulp.src(['js/compline.js', 'js/chant-element.js', 'js/calendar.js'])
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
  return gulp.src([
    '**/*.gabc',
    'js/require.js',
    'fonts/*.woff',
    'fonts/*.woff2',
    '!dist/**/*',
    '!node_modules/**/*'
  ], {
    dot: true,
    base: '.'
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function() {
  var requirejs = require('requirejs');

  requirejs.optimize({
    cssIn: "style.css",
    out: "dist/style.css",
    optimizeCss: "standard"
  });

  // return gulp.src([
  //   'dist/*.css'
  // ])
  //   // Concatenate And Minify Styles
  //   .pipe($.if('*.css', $.csso()))
  //   .pipe(gulp.dest('dist'))
  //   .pipe($.size({title: 'styles'}));
});

// Build one javascript file:
gulp.task('scripts', function() {
  var requirejs = require('requirejs');

  requirejs.optimize({
    'findNestedDependencies': true,
    'baseUrl': './js/',
    'name': 'compline',
    'optimize': 'uglify2',
    'out': './dist/js/compline.js',
    'wrap': true,
    // 'onModuleBundleComplete': function(data) {
    //   var fs = require('fs'),
    //     amdclean = require('amdclean'),
    //     outputFile = data.path;

    //   fs.writeFileSync(outputFile, amdclean.clean({
    //     'wrap': {
    //       // This string is prepended to the file
    //       'start': ';(function() {\n',
    //       // This string is appended to the file
    //       'end': '\n}());'
    //     },
    //     removeUseStricts: false,
    //     shimOverrides: { jquery: 'jQuery' },
    //     'filePath': outputFile
    //   }));
    //}
  });
});

// Concatenate And Minify JavaScript
gulp.task('scripts_old', function(cb) {
  var sources = [
    'js/*.js'
  ];

  pump([
        gulp.src(sources, {base: '.'}),
        $.uglify(),
        gulp.dest('dist'),
        $.size({title: 'scripts'})
    ],
    cb
  );
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function() {

  return gulp.src(['*.html', 'psalms/**/*.html'], {base: '.'})
    // .pipe(replace(/data-main="([^"]+?)(?:\.js)?"\s+src="[^"]+\/require.js"/,'src="$1.js"'))
    // Replace ǽ with æ, since the font we are using right now doesn't look right with the ǽ character,
    // even when trying to use combining diacritics æ\u0301
    // .pipe(replace('ǽ','æ'))
    // The bold unicode accent character for producing œ́ doesn't work, so make sure the accent itself isn't bold
    .pipe(replace(/([^<]+œ)(́)/g, '$1$2'))
    // Minify Any HTML
    .pipe(htmlmin({collapseWhitespace: true, removeComments: true}))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default']);

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function(cb) {
  runSequence('copy', ['html', 'styles', 'scripts'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://compline.us.to',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }<|endoftext|>


<commit_before>/*
 * Copyright 2016 University of Southern California
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// The Chaise RecordSet module
angular.module('recordsetApp', ['ERMrest'])

// Register the 'context' object which can be accessed by config and other
// services.
.constant('context', {
    serviceURL: 'https://localhost/ermrest',
    catalogID: '1',
    schemaName: 'legacy',
    tableName: 'dataset',
    filters: []
})

// Register configuration work to be performed on module loading.
.config(['context', function(context) {
    // Note that we do not like using angular's '$location' service because
    // it encodes and/or decodes the URL in ways that are incompatible with
    // our applications. We need control of the encoding of the URLs.

    // First, configure the service URL, assuming its this origin plus the
    // typical deployment location for ermrest.
    context.serviceURL = window.location.origin + "/ermrest";

    // Then, parse the URL fragment id (aka, hash). Expected format:
    //  "#catalog_id/[schema_name:]table_name[/{attribute::op::value}{/attribute::op::value}*]"
    hash = window.location.hash;
    if (hash === undefined || hash == '' || hash.length == 1) {
        return;
    }

    var parts = hash.substring(1).split('/');
    var len = parts.length;
    context.catalogID = parts[0];
    if (len > 1) {

        // Parse the schema:table name
        schemaTable = parts[1].split(':');
        if (schemaTable.length > 1) {
            context.schemaName = schemaTable[0];
            context.tableName = schemaTable[1];
        }
        else {
            context.schemaName = '';
            context.tableName = schemaTable[0];
        }

        // Parse the filters, currently supports only binary predicates
        for (var i=2; i<len; i++) {
            var fparts = parts[i].split("::");
            if (parts[1] == "eq") {
                context.filters.push({name:fparts[0],op:"=",value:fparts[2]});
            } else {
                context.filters.push({name:fparts[0],op:"::"+fparts[1]+"::",value:fparts[2]});
            }
        }
        console.log(context.filters);
    }
}])

// Register the 'recordsetModel' object, which can be accessed by other
// services, but cannot be access by providers (and config, apparently).
.value('recordsetModel', {header:[],rowset:[]})

// Register the recordset controller
.controller('recordsetController', ['$scope', 'recordsetModel', function($scope, recordsetModel) {
    $scope.vm = recordsetModel;
}])

// Register work to be performed after loading all modules
.run(['context', 'recordsetModel', 'ermrestServerFactory', function(context, recordsetModel, ermrestServerFactory) {
    // Get rowset data from ermrest
    var server = ermrestServerFactory.getServer(context.serviceURL);
    var catalog = server.catalogs.get(context.catalogID).then(function(catalog) {
        console.log(catalog);

        // get table definition
        var table = catalog.schemas.get(context.schemaName).tables.get(context.tableName);
        console.log(table);
        recordsetModel.table = table;
        recordsetModel.header = table.columns.names();
        console.log(recordsetModel.header);

        // get rows
        var filter = null;
        for (var i in context.filters) {
          if (filter == null) {
            filter = new ERMrest.BinaryPredicate(
              table.columns.get(context.filters[i].name),
              context.filters[i].op,
              context.filters[i].value);
          } else if (filter instanceof ERMrest.Conjunction) {
            filter.filters.push(
              new ERMrest.BinaryPredicate(
                table.columns.byName(context.filters[i].name),
                context.filters[i].op,
                context.filters[i].value)
              );
          } else {
              var temp = filter;
              filter = new ERMrest.Conjunction([temp]);
          }
        }
        table.entity.get(filter).then(function (rowset) {
          console.log(rowset);
          recordsetModel.rowset = rowset;
        }, function(error) {
          console.log(error);
        });
    });
}])

/* end recordsetApp */;
<commit_msg>conjuctions use '&' and now work<commit_after>/*
 * Copyright 2016 University of Southern California
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// The Chaise RecordSet module
angular.module('recordsetApp', ['ERMrest'])

// Register the 'context' object which can be accessed by config and other
// services.
.constant('context', {
    serviceURL: 'https://localhost/ermrest',
    catalogID: '1',
    schemaName: 'legacy',
    tableName: 'dataset',
    filters: []
})

// Register configuration work to be performed on module loading.
.config(['context', function(context) {
    // Note that we do not like using angular's '$location' service because
    // it encodes and/or decodes the URL in ways that are incompatible with
    // our applications. We need control of the encoding of the URLs.

    // First, configure the service URL, assuming its this origin plus the
    // typical deployment location for ermrest.
    context.serviceURL = window.location.origin + "/ermrest";

    // Then, parse the URL fragment id (aka, hash). Expected format:
    //  "#catalog_id/[schema_name:]table_name[/{attribute::op::value}{&attribute::op::value}*]"
    hash = window.location.hash;
    if (hash === undefined || hash == '' || hash.length == 1) {
        return;
    }

    var fragment = hash.substring(1).split('/');
    var len = fragment.length;
    context.catalogID = fragment[0];
    if (len > 1) {

        // Parse the schema:table name
        schemaTable = fragment[1].split(':');
        if (schemaTable.length > 1) {
            context.schemaName = schemaTable[0];
            context.tableName = schemaTable[1];
        }
        else {
            context.schemaName = '';
            context.tableName = schemaTable[0];
        }

        // Parse the filters, currently supports only binary predicates
        if (len>2) {
            var conjunction = fragment[2].split('&');
            for (var i in conjunction) {
                var filter = conjunction[i].split("::");
                if (filter[1] === "eq") {
                    context.filters.push({name:filter[0],op:"=",value:filter[2]});
                } else {
                    context.filters.push({name:filter[0],op:"::"+filter[1]+"::",value:filter[2]});
                }
            }
            console.log(context.filters);
        }
    }
}])

// Register the 'recordsetModel' object, which can be accessed by other
// services, but cannot be access by providers (and config, apparently).
.value('recordsetModel', {header:[],rowset:[]})

// Register the recordset controller
.controller('recordsetController', ['$scope', 'recordsetModel', function($scope, recordsetModel) {
    $scope.vm = recordsetModel;
}])

// Register work to be performed after loading all modules
.run(['context', 'recordsetModel', 'ermrestServerFactory', function(context, recordsetModel, ermrestServerFactory) {
    // Get rowset data from ermrest
    var server = ermrestServerFactory.getServer(context.serviceURL);
    var catalog = server.catalogs.get(context.catalogID).then(function(catalog) {
        console.log(catalog);

        // get table definition
        var table = catalog.schemas.get(context.schemaName).tables.get(context.tableName);
        console.log(table);
        recordsetModel.table = table;
        recordsetModel.header = table.columns.names();
        console.log(recordsetModel.header);

        // build up filters
        var filter = null;
        var len = context.filters.length;
        if (len == 1) {
          filter = new ERMrest.BinaryPredicate(
            table.columns.get(context.filters[0].name),
            context.filters[0].op,
            context.filters[0].value);
        }
        else if (len > 1) {
          filter = new ERMrest.Conjunction([]);
          for (var i=0; i<len; i++) {
            filter.filters.push(
              new ERMrest.BinaryPredicate(
                table.columns.get(context.filters[i].name),
                context.filters[i].op,
                context.filters[i].value)
            );
          }
        }

        // get rowset from table
        table.entity.get(filter).then(function (rowset) {
          console.log(rowset);
          recordsetModel.rowset = rowset;
        }, function(error) {
          console.log(error);
        });
    });
}])

/* end recordsetApp */;
<|endoftext|>


<commit_before>"use strict";

var gulp = require("gulp");
var gutil = require("gulp-util");
var connect = require("gulp-connect");
var runSequence = require("run-sequence");
var mocha = require("gulp-mocha");
var webpack = require("webpack");
var WebpackDevServer = require("webpack-dev-server");
var karma = require("karma").server;

var pkg = require("./package.json");
var config = pkg.projectConfig;
var webpackConfig = require("./webpack.config.js");

var webpackDevServer;

//
// HELPER TASKS
//

gulp.task("clean", function(done) {
    require("del")([
        config.dirs.dist
    ], done);
});

gulp.task("copy", [
    "copy:src",
    "copy:normalize"
]);

gulp.task("copy:src", function() {
    return gulp.src(config.dirs.src + "/**.html")
               .pipe(gulp.dest(config.dirs.dist));
});

gulp.task("copy:normalize", function() {
    return gulp.src("node_modules/normalize.css/normalize.css")
               .pipe(gulp.dest(config.dirs.vendor + "/css"));
});

gulp.task("watch:src", function(done) {
    gulp.watch(config.dirs.src + "/**.html", function(event) {
        runSequence(
            "copy:src",
            "webpack-dev-server:reload"
        );
    });
    done();
});

gulp.task("test", [
    "test:unit",
    "test:integration"
]);

gulp.task("test:unit", function() {
    return gulp.src("test/unit/**/*.js", {read: false})
        // gulp-mocha needs filepaths so you can"t have any plugins before it
        .pipe(mocha());
});

gulp.task("test:integration", function(done) {
    karma.start({
        configFile: __dirname + "/karma.conf.js"
    }, done);
});

gulp.task("test:integration:watch", function(done) {
    karma.start({
        configFile: __dirname + "/karma.conf.js",
        singleRun: false
    });
    done();
});

gulp.task("test:build", function() {
    return gulp.src("test/build/**/*.js", {read: false})
        // gulp-mocha needs filepaths so you can"t have any plugins before it
        .pipe(mocha());
});

gulp.task("webpack", function(callback) {
    // run webpack
    webpack(require("./webpack.config.js"), function(err, stats) {
        if (err) {
            throw new gutil.PluginError("webpack", err);
        }
        gutil.log("[webpack]", stats.toString({
            // output options
        }));
        callback();
    });
});

gulp.task("webpack-dev-server", function(callback) {
    // Start a webpack-dev-server
    var webpackDevConfig = Object.create(webpackConfig);
    webpackDevConfig.debug = true;
    webpackDevConfig.devtool = "eval";

    var compiler = webpack(webpackConfig);

    webpackDevServer = new WebpackDevServer(compiler, webpackConfig.devServer);
    webpackDevServer.listen(5000, "0.0.0.0", function(err) {
        if (err) {
            throw new gutil.PluginError("webpack-dev-server", err);
        }
        // Server listening
        gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html");

        // keep the server alive or continue?
        callback();
    });
});

gulp.task("webpack-dev-server:reload", function(done) {
    if (webpackDevServer && webpackDevServer.io) {
        webpackDevServer.io.sockets.emit("ok");
    }
    done();
});

gulp.task("connect", function() {
    connect.server({
        root: config.dirs.dist,
        port: 5000
    });
});

//
// MAIN TASKS
//

gulp.task("build", function(done) {
    runSequence(
        "clean",
        "test",
        "copy",
        "webpack",
        "test:build",
    done);
});

gulp.task("default", function(done) {
    runSequence(
        "build",
        "test:integration:watch",
        "watch:src",
        "webpack-dev-server",
    done);
});
<commit_msg>Add watch task for unit tests<commit_after>"use strict";

var gulp = require("gulp");
var gutil = require("gulp-util");
var connect = require("gulp-connect");
var runSequence = require("run-sequence");
var mocha = require("gulp-mocha");
var webpack = require("webpack");
var WebpackDevServer = require("webpack-dev-server");
var karma = require("karma").server;

var pkg = require("./package.json");
var config = pkg.projectConfig;
var webpackConfig = require("./webpack.config.js");

var webpackDevServer;

//
// HELPER TASKS
//

gulp.task("clean", function(done) {
    require("del")([
        config.dirs.dist
    ], done);
});

gulp.task("copy", [
    "copy:src",
    "copy:normalize"
]);

gulp.task("copy:src", function() {
    return gulp.src(config.dirs.src + "/**.html")
               .pipe(gulp.dest(config.dirs.dist));
});

gulp.task("copy:normalize", function() {
    return gulp.src("node_modules/normalize.css/normalize.css")
               .pipe(gulp.dest(config.dirs.vendor + "/css"));
});

gulp.task("watch:src", function(done) {
    gulp.watch(config.dirs.src + "/**.html", function(event) {
        runSequence(
            "copy:src",
            "webpack-dev-server:reload"
        );
    });
    done();
});

gulp.task("test", [
    "test:unit",
    "test:integration"
]);

gulp.task("test:unit", function() {
    return gulp.src("test/unit/**/*.js", {read: false})
        // gulp-mocha needs filepaths so you can"t have any plugins before it
        .pipe(mocha());
});

gulp.task("test:unit:watch", function(done) {
    gulp.watch(["test/unit/**/*.js", "src/**/*.js"], ["test:unit"]);
    done();
});

gulp.task("test:integration", function(done) {
    karma.start({
        configFile: __dirname + "/karma.conf.js"
    }, done);
});

gulp.task("test:integration:watch", function(done) {
    karma.start({
        configFile: __dirname + "/karma.conf.js",
        singleRun: false
    });
    done();
});

gulp.task("test:build", function() {
    return gulp.src("test/build/**/*.js", {read: false})
        // gulp-mocha needs filepaths so you can"t have any plugins before it
        .pipe(mocha());
});

gulp.task("webpack", function(callback) {
    // run webpack
    webpack(require("./webpack.config.js"), function(err, stats) {
        if (err) {
            throw new gutil.PluginError("webpack", err);
        }
        gutil.log("[webpack]", stats.toString({
            // output options
        }));
        callback();
    });
});

gulp.task("webpack-dev-server", function(callback) {
    // Start a webpack-dev-server
    var webpackDevConfig = Object.create(webpackConfig);
    webpackDevConfig.debug = true;
    webpackDevConfig.devtool = "eval";

    var compiler = webpack(webpackConfig);

    webpackDevServer = new WebpackDevServer(compiler, webpackConfig.devServer);
    webpackDevServer.listen(5000, "0.0.0.0", function(err) {
        if (err) {
            throw new gutil.PluginError("webpack-dev-server", err);
        }
        // Server listening
        gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html");

        // keep the server alive or continue?
        callback();
    });
});

gulp.task("webpack-dev-server:reload", function(done) {
    if (webpackDevServer && webpackDevServer.io) {
        webpackDevServer.io.sockets.emit("ok");
    }
    done();
});

gulp.task("connect", function() {
    connect.server({
        root: config.dirs.dist,
        port: 5000
    });
});

//
// MAIN TASKS
//

gulp.task("dist", function(done) {
    runSequence(
        "clean",
        "test",
        "copy",
        "webpack",
    done);
});

gulp.task("build", function(done) {
    runSequence(
        "dist",
        "test:build",
    done);
});

gulp.task("default", function(done) {
    runSequence(
        "dist",
        "test:unit:watch",
        "test:integration:watch",
        "watch:src",
        "webpack-dev-server",
    done);
});
<|endoftext|>


<commit_before><commit_msg>Separate sourcemaps<commit_after><|endoftext|>


<commit_before><commit_msg>added functionality for lifeCycle events to occur within the creative gulp task<commit_after><|endoftext|>


<commit_before><commit_msg>add extract and index tasks<commit_after><|endoftext|>


<commit_before>var vdf = require('vdf');
var request = require('request');
var fs = require('fs');

var TeamFortress2 = require('./index.js');
var Language = require(__dirname + '/language.js');
var Protos = require(__dirname + '/protos.js');

var base_gcmessages = Protos.base_gcmessages;
var gcsdk_gcmessages = Protos.gcsdk_gcmessages;
var tf_gcmessages = Protos.tf_gcmessages;

var handlers = TeamFortress2.prototype._handlers;

// ClientWelcome and ClientGoodbye
handlers[Language.ClientWelcome] = function(body) {
	var proto = base_gcmessages.CMsgClientWelcome.parse(body);
	this.haveGCSession = true;
	this.emit('connectedToGC', proto.version);
};

handlers[Language.ClientGoodbye] = function(body) {
	var proto = base_gcmessages.CMsgClientGoodbye.parse(body);
	this.haveGCSession = false;
	this.emit('disconnectedFromGC', proto.reason);
};

// Item schema
handlers[Language.UpdateItemSchema] = function(body) {
	var proto = base_gcmessages.CMsgUpdateItemSchema.parse(body);
	this.emit('itemSchema', proto.itemSchemaVersion.toString(16).toUpperCase(), proto.itemsGameUrl);

	var self = this;
	request(proto.itemsGameUrl, function(err, response, body) {
		if(err) {
			self.emit('debug', "Unable to download items_game.txt: " + err);
			self.emit('itemSchemaError', err);
			return;
		}

		self.itemSchema = vdf.parse(body).items_game;
		self.emit('itemSchemaLoaded');
	});
};

// Various notifications (why do we need three distinct interfaces??)
handlers[Language.SystemMessage] = function(body) {
	var proto = base_gcmessages.CMsgSystemBroadcast.parse(body);
	this.emit('systemMessage', proto.message);
};

handlers[Language.ClientDisplayNotification] = function(body) {
	if(!this.lang) {
		// We only handle this if we have a localization file
		return;
	}

	var proto = base_gcmessages.CMsgGCClientDisplayNotification.parse(body);
	var title = this.lang[proto.notificationTitleLocalizationKey.substring(1)];
	var body = (this.lang[proto.notificationBodyLocalizationKey.substring(1)] || '').replace(new RegExp('[\u0001|\u0002]', 'g'), '');
	body = body.replace(/\\"/g, '"'); // The vdf parser appears to not properly parse escaped quotes

	var replacement;
	for(var i = 0; i < proto.bodySubstringKeys.length; i++) {
		replacement = proto.bodySubstringValues[i];
		if(replacement.charAt(0) == '#') {
			replacement = this.lang[replacement.substring(1)];
		}

		body = body.replace('%' + proto.bodySubstringKeys[i] + '%', replacement);
	}

	this.emit('displayNotification', title, body);
};

handlers[Language.TFSpecificItemBroadcast] = function(body) {
	var proto = tf_gcmessages.CMsgGCTFSpecificItemBroadcast.parse(body);
	var defindex = proto.itemDefIndex;

	var message = null;

	if(this.lang && this.itemSchema) {
		var item = this.itemSchema.items[defindex] || {};
		var itemNameKey = item.item_name || '';
		var itemName = this.lang[itemNameKey.substring(1)];

		var localizationKey = proto.wasDestruction ? "TF_Event_Item_Deleted" : "TF_Event_Item_Created";
		message = this.lang[localizationKey].replace('%owner%', proto.userName).replace('%item_name%', itemName);
	}

	this.emit('itemBroadcast', message, proto.userName, proto.wasDestruction, defindex);
};

handlers[Language.Trading_InitiateTradeResponse] = function(body) {
	var response = body.readUInt32LE(0);
	this.emit('debug', "Got trade response " + response);
	this.emit('tradeResponse', response);
};

// SO
handlers[Language.SO_CacheSubscriptionCheck] = function(body) {
	this.emit('debug', "Requesting SO cache subscription refresh");
	this._send(Language.SO_CacheSubscriptionRefresh, gcsdk_gcmessages.CMsgSOCacheSubscriptionRefresh, {"owner": this._steam.steamID});
};

handlers[Language.SO_CacheSubscribed] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOCacheSubscribed.parse(body);
	var self = this;
	proto.objects.forEach(function(cache) {
		switch(cache.typeId) {
			case 1:
				// Backpack
				var items = cache.objectData.map(function(object) {
					return base_gcmessages.CSOEconItem.parse(object);
				});

				self.backpack = items;
				self.emit('backpackLoaded');
				break;
			case 7:
				// Account metadata
				var data = base_gcmessages.CSOEconGameAccountClient.parse(cache.objectData[0]);
				self.premium = !data.trialAccount;
				self.backpackSlots = (data.trialAccount ? 50 : 300) + data.additionalBackpackSlots;
				self.canSendProfessorSpeks = data.needToChooseMostHelpfulFriend;
				self.emit('accountLoaded');
				break;
			default:
				self.emit('debug', "Unknown SO type " + cache.typeId + " with " + cache.objectData.length + " items");
				break;
		}
	});
};

handlers[Language.SO_Create] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOSingleObject.parse(body);
	if(proto.typeId != 1) {
		return; // Not an item
	}

	var item = base_gcmessages.CSOEconItem.parse(proto.objectData);
	this.backpack.push(item);
	this.emit('itemAcquired', item);
};

handlers[Language.SO_Update] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOSingleObject.parse(body);
	this._handleSOUpdate(proto);
};

handlers[Language.SO_UpdateMultiple] = function(body) {
	var items = gcsdk_gcmessages.CMsgSOMultipleObjects.parse(body).objects;
	var self = this;

	items.forEach(function(item) {
		self._handleSOUpdate(item);
	});
};

TeamFortress2.prototype._handleSOUpdate = function(so) {
	switch(so.typeId) {
		case 1:
			var item = base_gcmessages.CSOEconItem.parse(so.objectData);
			for(var i = 0; i < this.backpack.length; i++) {
				if(this.backpack[i].id == item.id) {
					var oldItem = this.backpack[i];
					this.backpack[i] = item;

					this.emit('itemChanged', oldItem, item);
					break;
				}
			}

			break;
		case 7:
			var data = base_gcmessages.CSOEconGameAccountClient.parse(so.objectData);
			var oldData = {
				"premium": this.premium,
				"backpackSlots": this.backpackSlots,
				"canSendProfessorSpeks": this.canSendProfessorSpeks
			};

			this.premium = !data.trialAccount;
			this.backpackSlots = (data.trialAccount ? 50 : 300) + data.additionalBackpackSlots;
			this.canSendProfessorSpeks = data.needToChooseMostHelpfulFriend;

			var changed = {};
			var somethingHasChanged = false;
			for(var i in oldData) {
				if(this[i] != oldData[i]) {
					somethingHasChanged = true;
					changed[i] = oldData[i];
				}
			}

			if(somethingHasChanged) {
				// Only emit the event if a property that we're tracking changes
				this.emit('accountUpdate', changed);
			}

			break;
		default:
			this.emit('debug', "Unknown SO type " + so.typeId + " updated");
			break;
	}
}

handlers[Language.SO_Destroy] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOSingleObject.parse(body);
	if(proto.typeId != 1) {
		return; // Not an item
	}

	var item = base_gcmessages.CSOEconItem.parse(proto.objectData);
	var itemData = null;
	for(var i = 0; i < this.backpack.length; i++) {
		if(this.backpack[i].id == item.id) {
			itemData = this.backpack[i];
			this.backpack.splice(i, 1);
			break;
		}
	}

	this.emit('itemRemoved', itemData);
};

// Item manipulation
handlers[Language.CraftResponse] = function(body) {
	// Maybe in the future figure out what data is passed here?
	this.emit('craftingComplete');
};

// Professor Speks
handlers[Language.FreeTrial_ThankedBySomeone] = function(body) {
	var proto = tf_gcmessages.CMsgTFThankedBySomeone.parse(body);
	this.emit('professorSpeksReceived', proto.thankerSteamId);
};

handlers[Language.FreeTrial_ThankedSomeone] = function(body) {
	this.emit('professorSpeksSent');
};

// Game Servers
handlers[Language.GameServer_CreateIdentityResponse] = function(body) {
	var proto = tf_gcmessages.CMsgGC_GameServer_CreateIdentityResponse.parse(body);
	this.emit('createIdentity', proto.status, proto.accountCreated, proto.gameServerAccountId, proto.gameServerIdentityToken);
};

handlers[Language.GameServer_ListResponse] = function(body) {
	var proto = tf_gcmessages.CMsgGC_GameServer_ListResponse.parse(body);
	this.emit('registeredServers', proto.ownedGameServers || []);
};

handlers[Language.GameServer_ResetIdentityResponse] = function(body) {
	var proto = tf_gcmessages.CMsgGC_GameServer_ResetIdentityResponse.parse(body);
	this.emit('resetIdentity', proto.gameServerIdentityTokenReset, proto.gameServerAccountId, proto.gameServerIdentityToken);
};<commit_msg>Ignore item updates before we get our backpack<commit_after>var vdf = require('vdf');
var request = require('request');
var fs = require('fs');

var TeamFortress2 = require('./index.js');
var Language = require(__dirname + '/language.js');
var Protos = require(__dirname + '/protos.js');

var base_gcmessages = Protos.base_gcmessages;
var gcsdk_gcmessages = Protos.gcsdk_gcmessages;
var tf_gcmessages = Protos.tf_gcmessages;

var handlers = TeamFortress2.prototype._handlers;

// ClientWelcome and ClientGoodbye
handlers[Language.ClientWelcome] = function(body) {
	var proto = base_gcmessages.CMsgClientWelcome.parse(body);
	this.haveGCSession = true;
	this.emit('connectedToGC', proto.version);
};

handlers[Language.ClientGoodbye] = function(body) {
	var proto = base_gcmessages.CMsgClientGoodbye.parse(body);
	this.haveGCSession = false;
	this.emit('disconnectedFromGC', proto.reason);
};

// Item schema
handlers[Language.UpdateItemSchema] = function(body) {
	var proto = base_gcmessages.CMsgUpdateItemSchema.parse(body);
	this.emit('itemSchema', proto.itemSchemaVersion.toString(16).toUpperCase(), proto.itemsGameUrl);

	var self = this;
	request(proto.itemsGameUrl, function(err, response, body) {
		if(err) {
			self.emit('debug', "Unable to download items_game.txt: " + err);
			self.emit('itemSchemaError', err);
			return;
		}

		self.itemSchema = vdf.parse(body).items_game;
		self.emit('itemSchemaLoaded');
	});
};

// Various notifications (why do we need three distinct interfaces??)
handlers[Language.SystemMessage] = function(body) {
	var proto = base_gcmessages.CMsgSystemBroadcast.parse(body);
	this.emit('systemMessage', proto.message);
};

handlers[Language.ClientDisplayNotification] = function(body) {
	if(!this.lang) {
		// We only handle this if we have a localization file
		return;
	}

	var proto = base_gcmessages.CMsgGCClientDisplayNotification.parse(body);
	var title = this.lang[proto.notificationTitleLocalizationKey.substring(1)];
	var body = (this.lang[proto.notificationBodyLocalizationKey.substring(1)] || '').replace(new RegExp('[\u0001|\u0002]', 'g'), '');
	body = body.replace(/\\"/g, '"'); // The vdf parser appears to not properly parse escaped quotes

	var replacement;
	for(var i = 0; i < proto.bodySubstringKeys.length; i++) {
		replacement = proto.bodySubstringValues[i];
		if(replacement.charAt(0) == '#') {
			replacement = this.lang[replacement.substring(1)];
		}

		body = body.replace('%' + proto.bodySubstringKeys[i] + '%', replacement);
	}

	this.emit('displayNotification', title, body);
};

handlers[Language.TFSpecificItemBroadcast] = function(body) {
	var proto = tf_gcmessages.CMsgGCTFSpecificItemBroadcast.parse(body);
	var defindex = proto.itemDefIndex;

	var message = null;

	if(this.lang && this.itemSchema) {
		var item = this.itemSchema.items[defindex] || {};
		var itemNameKey = item.item_name || '';
		var itemName = this.lang[itemNameKey.substring(1)];

		var localizationKey = proto.wasDestruction ? "TF_Event_Item_Deleted" : "TF_Event_Item_Created";
		message = this.lang[localizationKey].replace('%owner%', proto.userName).replace('%item_name%', itemName);
	}

	this.emit('itemBroadcast', message, proto.userName, proto.wasDestruction, defindex);
};

handlers[Language.Trading_InitiateTradeResponse] = function(body) {
	var response = body.readUInt32LE(0);
	this.emit('debug', "Got trade response " + response);
	this.emit('tradeResponse', response);
};

// SO
handlers[Language.SO_CacheSubscriptionCheck] = function(body) {
	this.emit('debug', "Requesting SO cache subscription refresh");
	this._send(Language.SO_CacheSubscriptionRefresh, gcsdk_gcmessages.CMsgSOCacheSubscriptionRefresh, {"owner": this._steam.steamID});
};

handlers[Language.SO_CacheSubscribed] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOCacheSubscribed.parse(body);
	var self = this;
	proto.objects.forEach(function(cache) {
		switch(cache.typeId) {
			case 1:
				// Backpack
				var items = cache.objectData.map(function(object) {
					return base_gcmessages.CSOEconItem.parse(object);
				});

				self.backpack = items;
				self.emit('backpackLoaded');
				break;
			case 7:
				// Account metadata
				var data = base_gcmessages.CSOEconGameAccountClient.parse(cache.objectData[0]);
				self.premium = !data.trialAccount;
				self.backpackSlots = (data.trialAccount ? 50 : 300) + data.additionalBackpackSlots;
				self.canSendProfessorSpeks = data.needToChooseMostHelpfulFriend;
				self.emit('accountLoaded');
				break;
			default:
				self.emit('debug', "Unknown SO type " + cache.typeId + " with " + cache.objectData.length + " items");
				break;
		}
	});
};

handlers[Language.SO_Create] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOSingleObject.parse(body);
	if(proto.typeId != 1) {
		return; // Not an item
	}

	var item = base_gcmessages.CSOEconItem.parse(proto.objectData);
	this.backpack.push(item);
	this.emit('itemAcquired', item);
};

handlers[Language.SO_Update] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOSingleObject.parse(body);
	this._handleSOUpdate(proto);
};

handlers[Language.SO_UpdateMultiple] = function(body) {
	var items = gcsdk_gcmessages.CMsgSOMultipleObjects.parse(body).objects;
	var self = this;

	items.forEach(function(item) {
		self._handleSOUpdate(item);
	});
};

TeamFortress2.prototype._handleSOUpdate = function(so) {
	switch(so.typeId) {
		case 1:
			if(!this.backpack) {
				return; // We don't have our backpack yet!
			}

			var item = base_gcmessages.CSOEconItem.parse(so.objectData);
			for(var i = 0; i < this.backpack.length; i++) {
				if(this.backpack[i].id == item.id) {
					var oldItem = this.backpack[i];
					this.backpack[i] = item;

					this.emit('itemChanged', oldItem, item);
					break;
				}
			}

			break;
		case 7:
			var data = base_gcmessages.CSOEconGameAccountClient.parse(so.objectData);
			var oldData = {
				"premium": this.premium,
				"backpackSlots": this.backpackSlots,
				"canSendProfessorSpeks": this.canSendProfessorSpeks
			};

			this.premium = !data.trialAccount;
			this.backpackSlots = (data.trialAccount ? 50 : 300) + data.additionalBackpackSlots;
			this.canSendProfessorSpeks = data.needToChooseMostHelpfulFriend;

			var changed = {};
			var somethingHasChanged = false;
			for(var i in oldData) {
				if(this[i] != oldData[i]) {
					somethingHasChanged = true;
					changed[i] = oldData[i];
				}
			}

			if(somethingHasChanged) {
				// Only emit the event if a property that we're tracking changes
				this.emit('accountUpdate', changed);
			}

			break;
		default:
			this.emit('debug', "Unknown SO type " + so.typeId + " updated");
			break;
	}
}

handlers[Language.SO_Destroy] = function(body) {
	var proto = gcsdk_gcmessages.CMsgSOSingleObject.parse(body);
	if(proto.typeId != 1) {
		return; // Not an item
	}

	var item = base_gcmessages.CSOEconItem.parse(proto.objectData);
	var itemData = null;
	for(var i = 0; i < this.backpack.length; i++) {
		if(this.backpack[i].id == item.id) {
			itemData = this.backpack[i];
			this.backpack.splice(i, 1);
			break;
		}
	}

	this.emit('itemRemoved', itemData);
};

// Item manipulation
handlers[Language.CraftResponse] = function(body) {
	// Maybe in the future figure out what data is passed here?
	this.emit('craftingComplete');
};

// Professor Speks
handlers[Language.FreeTrial_ThankedBySomeone] = function(body) {
	var proto = tf_gcmessages.CMsgTFThankedBySomeone.parse(body);
	this.emit('professorSpeksReceived', proto.thankerSteamId);
};

handlers[Language.FreeTrial_ThankedSomeone] = function(body) {
	this.emit('professorSpeksSent');
};

// Game Servers
handlers[Language.GameServer_CreateIdentityResponse] = function(body) {
	var proto = tf_gcmessages.CMsgGC_GameServer_CreateIdentityResponse.parse(body);
	this.emit('createIdentity', proto.status, proto.accountCreated, proto.gameServerAccountId, proto.gameServerIdentityToken);
};

handlers[Language.GameServer_ListResponse] = function(body) {
	var proto = tf_gcmessages.CMsgGC_GameServer_ListResponse.parse(body);
	this.emit('registeredServers', proto.ownedGameServers || []);
};

handlers[Language.GameServer_ResetIdentityResponse] = function(body) {
	var proto = tf_gcmessages.CMsgGC_GameServer_ResetIdentityResponse.parse(body);
	this.emit('resetIdentity', proto.gameServerIdentityTokenReset, proto.gameServerAccountId, proto.gameServerIdentityToken);
};<|endoftext|>