<commit_before>/**
 * Gulp operations for Backbone-Parse-ES6
 *
 * The following tasks are available:
 * bundle - Creates one or more bundles defined in './bundle-config.js'
 * docs - Creates documentation and outputs it in './docs'
 * lint - Runs ESLint outputting to console.
 * jspm-inspect - Executes 'jspm inspect'
 * jspm-install - Executes 'jspm install'
 * jspm-update - Executes 'jspm update'
 * npm-install - Executes 'npm install'
 * npm-uninstall - Executes 'npm uninstall'
 * test - Runs lint and bundle tasks.  (Add "--travis" argument to run minimal bundle op for Travis CI)
 */

/* eslint-disable */

var gulp =        require('gulp');

var argv =        require('yargs').argv;
var esdoc =       require('gulp-esdoc');
var eslint =      require('gulp-eslint');
var fs =          require('fs');
var jspm =        require('jspm');

var Promise =     require("bluebird");

// Set the package path to the local root where config.js is located.
jspm.setPackagePath('.');

/**
 * Bundles Backbone-Parse-ES6 via the config file found in './bundle-config.json'. This file contains an array of
 * parameters for invoking SystemJS Builder.
 *
 * An example entry:
 *    {
 *       "destBaseDir": "./dist/",        // Root destination directory for bundle output.
 *       "destFilename": "backbone.js",   // Destination bundle file name.
 *       "formats": ["amd", "cjs"],       // Module format to use / also defines destination sub-directory.
 *       "mangle": false,                 // Uglify mangle property used by SystemJS Builder.
 *       "minify": false,                 // Minify mangle property used by SystemJS Builder.
 *       "src": "src/ModuleRuntime.js",   // Source file for SystemJS Builder
 *       "extraConfig":                   // Defines additional config parameters to load after ./config.json is loaded.
 *       {
 *          "meta":
 *          {
 *             "jquery": { "build": false },
 *             "underscore": { "build": false }
 *          }
 *       }
 *    },
 */
gulp.task('bundle', function()
{
   var promiseList = [];

   // When testing the build in Travis CI we only need to run a single bundle operation.
   var bundleInfo = argv.travis ? require('./bundle-config-travis.json') : require('./bundle-config.json');

   // Attempt to create './dist' directory if it does not exist.
   if (!fs.existsSync('dist'))
   {
      fs.mkdirSync('dist');
   }

   for (var cntr = 0; cntr < bundleInfo.entryPoints.length; cntr++)
   {
      var entry = bundleInfo.entryPoints[cntr];

      var destBaseDir = entry.destBaseDir;
      var destFilename = entry.destFilename;
      var srcFilename = entry.src;
      var extraConfig = entry.extraConfig;
      var formats = entry.formats;
      var mangle = entry.mangle;
      var minify = entry.minify;

      for (var cntr2 = 0; cntr2 < formats.length; cntr2++)
      {
         var format = formats[cntr2];

         var destDir = destBaseDir +format;
         var destFilepath = destDir +'/' +destFilename;

         promiseList.push(buildStatic(srcFilename, destDir, destFilepath, minify, mangle, format, extraConfig));
      }
   }

   return Promise.all(promiseList).then(function()
   {
      console.log('All Bundle Tasks Complete');
   })
   .catch(function (err)
   {
      console.log('Bundle error: ' +err);
      process.exit(1);
   });
});

/**
 * Create docs from ./src using ESDoc. The docs are located in ./docs
 */
gulp.task('docs', function()
{
   var path = require('path');

   var esdocConfig = require('.' +path.sep +'esdoc.json');

   // Launch ESDoc
   return gulp.src(esdocConfig.source).pipe(esdoc(esdocConfig));
});

/**
 * Runs "git push", but only if the test task (lint & bundle) complete successfully. Also removes all path and map
 * statements that may be populated in `config.js`. If `config.js` is modified an additional commit is added.
 *
 * Note: Make sure to pass in `--travis` as an argument to this task to run an in memory build / test.
 */
gulp.task('git push', ['test'], function(cb)
{
   var vm = require('vm');
   var exec = require('child_process').exec;

   var buffer = fs.readFileSync('./config.js', 'utf8');

   // Remove the leading and trailing Javascript SystemJS config method invocation so we are left with a JSON file.
   buffer = buffer.replace('System.config(', '');
   buffer = buffer.replace(');', '');

   // Load buffer as object.
   var config = vm.runInThisContext('object = ' +buffer);

   // Only modify config.js if map and paths is not empty.
   if (Object.keys(config.map).length > 0 || Object.keys(config.paths).length > 0)
   {
      // Remove map and paths.
      config.map = {};
      config.paths = {};

      // Rewrite the config.js buffer.
      buffer = 'System.config(' + JSON.stringify(config, null, 2) +');';

      // Remove quotes around primary keys ignoring babelOptions / "optional".
      buffer = buffer.replace(/"([a-zA-Z]+)":/g, function(match, p1)
      {
         return p1 !== 'optional' ? p1 +':' : match;
      });

      // Rewrite 'config.js'.
      fs.writeFileSync('./config.js', buffer);

      // Execute git commmit.
      exec("git commit -m 'Removed extra config.js data' config.js", function (err, stdout, stderr)
      {
         console.log(stdout);
         console.log(stderr);
      });
   }

   // Execute git push.
   exec('git push', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs eslint
 */
gulp.task('lint', function()
{
   return gulp.src('./src/**/*.js')
    .pipe(eslint({ useEslintrc: true }))
    .pipe(eslint.formatEach('compact', process.stderr))
    .pipe(eslint.failOnError());
});

/**
 * Runs "jspm inspect"
 */
gulp.task('jspm-inspect', function(cb)
{
   var exec = require('child_process').exec;
   exec('jspm inspect', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "jspm install"
 */
gulp.task('jspm-install', function(cb)
{
   var exec = require('child_process').exec;
   exec('jspm install', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "npm install"
 */
gulp.task('npm-install', function(cb)
{
   var exec = require('child_process').exec;
   exec('npm install', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "npm uninstall <package> for all node modules installed."
 */
gulp.task('npm-uninstall', function(cb)
{
   var exec = require('child_process').exec;
   exec('for package in `ls node_modules`; do npm uninstall $package; done;', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "lint" and "bundle"; useful for testing and Travis CI.
 */
gulp.task('test', ['lint', 'bundle']);

/**
 * Returns a Promise which encapsulates an execution of SystemJS Builder.
 *
 * @param srcFilename
 * @param destDir
 * @param destFilepath
 * @param minify
 * @param mangle
 * @param format
 * @param extraConfig
 * @returns {bluebird} Promise
 */
function buildStatic(srcFilename, destDir, destFilepath, minify, mangle, format, extraConfig)
{
   return new Promise(function(resolve, reject)
   {
      // Attempt to create destDir if it does not exist.
      if (!fs.existsSync(destDir))
      {
         fs.mkdirSync(destDir);
      }

      // Error out early if destDir does not exist.
      if (!fs.existsSync(destDir))
      {
         console.error('Could not create destination directory: ' +destDir);
         reject();
      }

      var builder = new jspm.Builder();
      builder.loadConfig('./config.js').then(function()
      {
         if (typeof extraConfig !== 'undefined')
         {
            builder.config(extraConfig);
         }

         console.log('Bundle queued - srcFilename: ' +srcFilename +'; format: ' +format  +'; mangle: ' +mangle
          +'; minify: ' +minify +'; destDir: ' +destDir +'; destFilepath: ' +destFilepath);

         var builderPromise;
         var builderConfig =
         {
            minify: minify,
            mangle: mangle,
            format: format
         };

         // When testing we only need to do an in memory build.
         if (argv.travis)
         {
            builderPromise = builder.buildStatic(srcFilename, builderConfig);
         }
         else
         {
            builderPromise = builder.buildStatic(srcFilename, destFilepath, builderConfig);
         }

         builderPromise.then(function ()
         {
            console.log('Bundle complete - filename: ' +destFilepath +' minify: ' +minify +'; mangle: ' +mangle
             +'; format: ' +format);

            resolve();
         })
         .catch(function (err)
         {
            console.log('Bundle error - filename: ' +destFilepath +' minify: ' +minify + '; mangle: ' +mangle
             +'; format: ' +format);

            console.log(err);

            reject();
         });
      });
   });
}<commit_msg>Fixed promise reject in gulp function.<commit_after>/**
 * Gulp operations for Backbone-Parse-ES6
 *
 * The following tasks are available:
 * bundle - Creates one or more bundles defined in './bundle-config.js'
 * docs - Creates documentation and outputs it in './docs'
 * lint - Runs ESLint outputting to console.
 * jspm-inspect - Executes 'jspm inspect'
 * jspm-install - Executes 'jspm install'
 * jspm-update - Executes 'jspm update'
 * npm-install - Executes 'npm install'
 * npm-uninstall - Executes 'npm uninstall'
 * test - Runs lint and bundle tasks.  (Add "--travis" argument to run minimal bundle op for Travis CI)
 */

/* eslint-disable */

var gulp =        require('gulp');

var argv =        require('yargs').argv;
var esdoc =       require('gulp-esdoc');
var eslint =      require('gulp-eslint');
var fs =          require('fs');
var jspm =        require('jspm');

var Promise =     require("bluebird");

// Set the package path to the local root where config.js is located.
jspm.setPackagePath('.');

/**
 * Bundles Backbone-Parse-ES6 via the config file found in './bundle-config.json'. This file contains an array of
 * parameters for invoking SystemJS Builder.
 *
 * An example entry:
 *    {
 *       "destBaseDir": "./dist/",        // Root destination directory for bundle output.
 *       "destFilename": "backbone.js",   // Destination bundle file name.
 *       "formats": ["amd", "cjs"],       // Module format to use / also defines destination sub-directory.
 *       "mangle": false,                 // Uglify mangle property used by SystemJS Builder.
 *       "minify": false,                 // Minify mangle property used by SystemJS Builder.
 *       "src": "src/ModuleRuntime.js",   // Source file for SystemJS Builder
 *       "extraConfig":                   // Defines additional config parameters to load after ./config.json is loaded.
 *       {
 *          "meta":
 *          {
 *             "jquery": { "build": false },
 *             "underscore": { "build": false }
 *          }
 *       }
 *    },
 */
gulp.task('bundle', function()
{
   var promiseList = [];

   // When testing the build in Travis CI we only need to run a single bundle operation.
   var bundleInfo = argv.travis ? require('./bundle-config-travis.json') : require('./bundle-config.json');

   // Attempt to create './dist' directory if it does not exist.
   if (!fs.existsSync('dist'))
   {
      fs.mkdirSync('dist');
   }

   for (var cntr = 0; cntr < bundleInfo.entryPoints.length; cntr++)
   {
      var entry = bundleInfo.entryPoints[cntr];

      var destBaseDir = entry.destBaseDir;
      var destFilename = entry.destFilename;
      var srcFilename = entry.src;
      var extraConfig = entry.extraConfig;
      var formats = entry.formats;
      var mangle = entry.mangle;
      var minify = entry.minify;

      for (var cntr2 = 0; cntr2 < formats.length; cntr2++)
      {
         var format = formats[cntr2];

         var destDir = destBaseDir +format;
         var destFilepath = destDir +'/' +destFilename;

         promiseList.push(buildStatic(srcFilename, destDir, destFilepath, minify, mangle, format, extraConfig));
      }
   }

   return Promise.all(promiseList).then(function()
   {
      console.log('All Bundle Tasks Complete');
   })
   .catch(function (err)
   {
      console.log('Bundle error: ' +err);
      process.exit(1);
   });
});

/**
 * Create docs from ./src using ESDoc. The docs are located in ./docs
 */
gulp.task('docs', function()
{
   var path = require('path');

   var esdocConfig = require('.' +path.sep +'esdoc.json');

   // Launch ESDoc
   return gulp.src(esdocConfig.source).pipe(esdoc(esdocConfig));
});

/**
 * Runs "git push", but only if the test task (lint & bundle) complete successfully. Also removes all path and map
 * statements that may be populated in `config.js`. If `config.js` is modified an additional commit is added.
 *
 * Note: Make sure to pass in `--travis` as an argument to this task to run an in memory build / test.
 */
gulp.task('git push', ['test'], function(cb)
{
   var vm = require('vm');
   var exec = require('child_process').exec;

   var buffer = fs.readFileSync('./config.js', 'utf8');

   // Remove the leading and trailing Javascript SystemJS config method invocation so we are left with a JSON file.
   buffer = buffer.replace('System.config(', '');
   buffer = buffer.replace(');', '');

   // Load buffer as object.
   var config = vm.runInThisContext('object = ' +buffer);

   // Only modify config.js if map and paths is not empty.
   if (Object.keys(config.map).length > 0 || Object.keys(config.paths).length > 0)
   {
      // Remove map and paths.
      config.map = {};
      config.paths = {};

      // Rewrite the config.js buffer.
      buffer = 'System.config(' + JSON.stringify(config, null, 2) +');';

      // Remove quotes around primary keys ignoring babelOptions / "optional".
      buffer = buffer.replace(/"([a-zA-Z]+)":/g, function(match, p1)
      {
         return p1 !== 'optional' ? p1 +':' : match;
      });

      // Rewrite 'config.js'.
      fs.writeFileSync('./config.js', buffer);

      // Execute git commmit.
      exec("git commit -m 'Removed extra config.js data' config.js", function (err, stdout, stderr)
      {
         console.log(stdout);
         console.log(stderr);
      });
   }

   // Execute git push.
   exec('git push', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs eslint
 */
gulp.task('lint', function()
{
   return gulp.src('./src/**/*.js')
    .pipe(eslint({ useEslintrc: true }))
    .pipe(eslint.formatEach('compact', process.stderr))
    .pipe(eslint.failOnError());
});

/**
 * Runs "jspm inspect"
 */
gulp.task('jspm-inspect', function(cb)
{
   var exec = require('child_process').exec;
   exec('jspm inspect', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "jspm install"
 */
gulp.task('jspm-install', function(cb)
{
   var exec = require('child_process').exec;
   exec('jspm install', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "npm install"
 */
gulp.task('npm-install', function(cb)
{
   var exec = require('child_process').exec;
   exec('npm install', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "npm uninstall <package> for all node modules installed."
 */
gulp.task('npm-uninstall', function(cb)
{
   var exec = require('child_process').exec;
   exec('for package in `ls node_modules`; do npm uninstall $package; done;', function (err, stdout, stderr)
   {
      console.log(stdout);
      console.log(stderr);
      cb(err);
   });
});

/**
 * Runs "lint" and "bundle"; useful for testing and Travis CI.
 */
gulp.task('test', ['lint', 'bundle']);

/**
 * Returns a Promise which encapsulates an execution of SystemJS Builder.
 *
 * @param srcFilename
 * @param destDir
 * @param destFilepath
 * @param minify
 * @param mangle
 * @param format
 * @param extraConfig
 * @returns {bluebird} Promise
 */
function buildStatic(srcFilename, destDir, destFilepath, minify, mangle, format, extraConfig)
{
   return new Promise(function(resolve, reject)
   {
      // Attempt to create destDir if it does not exist.
      if (!fs.existsSync(destDir))
      {
         fs.mkdirSync(destDir);
      }

      // Error out early if destDir does not exist.
      if (!fs.existsSync(destDir))
      {
         console.error('Could not create destination directory: ' +destDir);
         reject();
      }

      var builder = new jspm.Builder();
      builder.loadConfig('./config.js').then(function()
      {
         if (typeof extraConfig !== 'undefined')
         {
            builder.config(extraConfig);
         }

         console.log('Bundle queued - srcFilename: ' +srcFilename +'; format: ' +format  +'; mangle: ' +mangle
          +'; minify: ' +minify +'; destDir: ' +destDir +'; destFilepath: ' +destFilepath);

         var builderPromise;
         var builderConfig =
         {
            minify: minify,
            mangle: mangle,
            format: format
         };

         // When testing we only need to do an in memory build.
         if (argv.travis)
         {
            builderPromise = builder.buildStatic(srcFilename, builderConfig);
         }
         else
         {
            builderPromise = builder.buildStatic(srcFilename, destFilepath, builderConfig);
         }

         builderPromise.then(function ()
         {
            console.log('Bundle complete - filename: ' +destFilepath +' minify: ' +minify +'; mangle: ' +mangle
             +'; format: ' +format);

            resolve();
         })
         .catch(function (err)
         {
            console.log('Bundle error - filename: ' +destFilepath +' minify: ' +minify + '; mangle: ' +mangle
             +'; format: ' +format);

            console.log(err);

            reject(err);
         });
      });
   });
}<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const gulp = require('gulp');
const excludeGitignore = require('gulp-exclude-gitignore');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');
const nsp = require('gulp-nsp');
const plumber = require('gulp-plumber');
const coveralls = require('gulp-coveralls');
const jscs = require('gulp-jscs');
const babel = require('gulp-babel');
const bump = require('gulp-bump');
const shell = require('gulp-shell');
const runSequence = require('run-sequence');
const fs = require('fs');

gulp.task('nsp', (cb) => {
    nsp('package.json', cb);
});

gulp.task('pre-test', () => {
    return gulp.src('src/**/*.js')
        .pipe(istanbul({
            includeUntested: true
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], (cb) => {
    let mochaErr;

    gulp.src('test/**/*.js')
        .pipe(babel())
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', (err) => {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', () => {
            cb(mochaErr);
        });
});

gulp.task('coveralls', ['test'], () => {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('babel', () => {
    return gulp.src('src/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('jscs', () => {
    return gulp.src('**/*.js')
        .pipe(excludeGitignore())
        .pipe(jscs())
        .pipe(jscs.reporter());
});

gulp.task('watch', () => {
    gulp.watch('**/*.js', ['build']);
});

gulp.task('bump', () => {
    let type = process.argv[process.argv.length - 1].slice(2);

    return gulp.src('./package.json')
        .pipe(bump({type: type}))
        .pipe(gulp.dest('./'));
});

gulp.task('tag', (cb) => {
    fs.readFile('./package.json', (err, file) => {
        if (err) {
            throw err;
        }

        let version = JSON.parse(file).version;
        let command = `git add package.json && git commit --allow-empty -m "Release v${version}" &&
            git tag v${version} && git push origin master --tags`;

        gulp.src('')
            .pipe(shell([command]))
            .on('end', cb);
    });
});

gulp.task('npm', shell.task(['npm publish']));

gulp.task('publish', (cb) => {
    runSequence('build', 'bump', 'tag', 'npm', cb);
});

gulp.task('build', ['jscs', 'test', 'nsp', 'babel']);

<commit_msg>Throw error if bump argument is invalid<commit_after>'use strict';

const path = require('path');
const gulp = require('gulp');
const excludeGitignore = require('gulp-exclude-gitignore');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');
const nsp = require('gulp-nsp');
const plumber = require('gulp-plumber');
const coveralls = require('gulp-coveralls');
const jscs = require('gulp-jscs');
const babel = require('gulp-babel');
const bump = require('gulp-bump');
const shell = require('gulp-shell');
const runSequence = require('run-sequence');
const fs = require('fs');

gulp.task('nsp', (cb) => {
    nsp('package.json', cb);
});

gulp.task('pre-test', () => {
    return gulp.src('src/**/*.js')
        .pipe(istanbul({
            includeUntested: true
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], (cb) => {
    let mochaErr;

    gulp.src('test/**/*.js')
        .pipe(babel())
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', (err) => {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', () => {
            cb(mochaErr);
        });
});

gulp.task('coveralls', ['test'], () => {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('babel', () => {
    return gulp.src('src/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('jscs', () => {
    return gulp.src('**/*.js')
        .pipe(excludeGitignore())
        .pipe(jscs())
        .pipe(jscs.reporter());
});

gulp.task('watch', () => {
    gulp.watch('**/*.js', ['build']);
});

gulp.task('bump', () => {
    let type = process.argv[process.argv.length - 1].slice(2);

    if (typeof type !== 'string') {
        throw new Error(`Please provide version increase type: patch, minor or major`);
    }

    return gulp.src('./package.json')
        .pipe(bump({type: type}))
        .pipe(gulp.dest('./'));
});

gulp.task('tag', (cb) => {
    fs.readFile('./package.json', (err, file) => {
        if (err) {
            throw err;
        }

        let version = JSON.parse(file).version;
        let command = `git add package.json && git commit --allow-empty -m "Release v${version}" &&
            git tag v${version} && git push origin master --tags`;

        gulp.src('')
            .pipe(shell([command]))
            .on('end', cb);
    });
});

gulp.task('npm', shell.task(['npm publish']));

gulp.task('publish', (cb) => {
    runSequence('build', 'bump', 'tag', 'npm', cb);
});

gulp.task('build', ['jscs', 'test', 'nsp', 'babel']);

<|endoftext|>


<commit_before>//Import dependencies
var gulp = require('gulp');
var path = require('path');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');

//Build the svg sprite task
gulp.task('build', function()
{
  //Source files
  var src = [ 'action/*.svg', 'alert/*.svg', 'navigation/*.svg' ];

  //Get the svg files
  return gulp.src(src)

  //Minimize each file
  .pipe(svgmin(function(file)
  {
    //Get the file parent folder and name
    var name = file.path.split(path.sep).slice(-2).join('-');

    //Remove the file extension
    var prefix = path.basename(name, path.extname(name));

    //Get the icon prefix
    //var prefix = path.basename(file.relative, path.extname(file.relative));

    //Display in console
    console.log('Processing ' + prefix);

    //Return the prefix plugin
    return { plugins: [ { cleanupIDs: { prefix: prefix + '-',  minify: true } } ] };
  }))

  //Build the sprite
  .pipe(svgstore())

  //Save the sprite image
  .pipe(gulp.dest('./'));
});

//Default task
gulp.task('default', [ 'build' ]);<commit_msg>Import gulp-rename method. Rename output svg sprite file.<commit_after>//Import dependencies
var rmr = require('rmr');
var gulp = require('gulp');
var path = require('path');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');
var rename = require("gulp-rename");

//Clean the dist folder
gulp.task('clean', function()
{
  //Clean the dist folder
  return rmr.sync('./dist');
});

//Build the svg sprite task
gulp.task('build', function()
{
  //Source files
  var src = [ 'action/*.svg', 'alert/*.svg', 'navigation/*.svg' ];

  //Get the svg files
  return gulp.src(src)

  //Minimize each file
  .pipe(svgmin(function(file)
  {
    //Get the file parent folder and name
    var name = file.path.split(path.sep).slice(-2).join('-');

    //Remove the file extension
    var prefix = path.basename(name, path.extname(name));

    //Get the icon prefix
    //var prefix = path.basename(file.relative, path.extname(file.relative));

    //Display in console
    console.log('Processing ' + prefix);

    //Return the prefix plugin
    return { plugins: [ { cleanupIDs: { prefix: prefix + '-',  minify: true } } ] };
  }))

  //Build the sprite
  .pipe(svgstore())

  //Rename the output file
  .pipe(rename({ basename: 'siimple-icons' }))

  //Save the sprite image
  .pipe(gulp.dest('./dist'));
});

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


<commit_before>var gulp = require('gulp'),
    eslint = require('gulp-eslint');

gulp.task('lint', function () {
    return gulp.src(['lib/*.js'])
        // eslint() attaches the lint output to the eslint property
        // of the file object so it can be used by other modules.
        .pipe(eslint())
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failOnError last.
        .pipe(eslint.failOnError());
});

gulp.task('default',['lint'],function(){
    console.log('Successful build')
});
<commit_msg>Remove gulpfile.js<commit_after><|endoftext|>


<commit_before>const gulp = require('gulp')
const fs = require('fs')
const path = require('path')
const uglify = require('gulp-uglify')
const concat = require('gulp-concat-util')
const del = require('del')
const less = require('gulp-less')
const preprocess = require('gulp-preprocess')

const pushPlayerToGrid = require('./tools/pushPlayerToGrid')

var paths = {
	less: './less/build.less',
	less360: './less/build_threesixty.less',
	js: {
		plugins: './browser/plugins/*.plugin.js',
		engine: [
			'./browser/vendor/when.js',

			'./browser/scripts/event-emitter.js',
			'./browser/scripts/core.js',
			'./browser/scripts/util.js',

			'./browser/scripts/connection.js',
			'./browser/scripts/variables.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/autoSlotGroup.js',

			'./browser/scripts/plugin.js',
			'./browser/scripts/subGraphPlugin.js',
			'./browser/scripts/threeObject3dPlugin.js',
			'./browser/scripts/abstractObjectGazePlugin.js',
			'./browser/scripts/abstractThreeLoaderObjPlugin.js',
			'./browser/scripts/abstractThreeMaterialPlugin.js',
			'./browser/scripts/abstractThreeMeshPlugin.js',
			'./browser/scripts/abstractArrayBlendModulatorPlugin.js',
			'./browser/scripts/abstractAnimateValueOnTriggerPlugin.js',

			'./browser/scripts/blendFunctions.js',

			'./browser/scripts/worldEditor/worldEditor.js',
			'./browser/scripts/worldEditor/worldEditorPerspectiveCamera.js',
			'./browser/scripts/worldEditor/worldEditorOrthographicCamera.js',
			'./browser/scripts/worldEditor/worldEditorCameraSelector.js',
			'./browser/scripts/worldEditor/worldEditorOriginGrid.js',
			'./browser/scripts/worldEditor/worldEditorRadialHelper.js',

			'./browser/scripts/screenshot/ScreenshotRenderer.js',

			'./browser/scripts/loaders/loader.js',
			'./browser/scripts/loaders/imageLoader.js',
			'./browser/scripts/loaders/textureLoader.js',
			'./browser/scripts/loaders/modelLoader.js',
			'./browser/scripts/loaders/sceneLoader.js',
			'./browser/scripts/loaders/assetLoader.js',
			'./browser/scripts/loaders/audioBufferLoader.js',
			'./browser/scripts/loaders/multiObjectLoader.js',

			'./browser/scripts/documentation/pluginDocsCache.js',

			'./browser/vendor/three/three.js',
			'./browser/vendor/three/OBJLoader.js',
			'./browser/vendor/three/OBJMTLLoader.js',
			'./browser/vendor/three/MTLLoader.js',
			'./browser/vendor/three/DDSLoader.js',
			'./browser/vendor/three/VREffect.js',
			'./browser/vendor/three/CardboardEffect.js',
			'./browser/vendor/three/VRControls.js',
			'./browser/vendor/three/SceneLoader.js',
			'./browser/vendor/three/MorphAnimMesh.js',

			'./browser/vendor/borismus/webvr-polyfill.js',
			'./browser/vendor/borismus/webvr-manager.js',

			'./browser/scripts/noise.js',
			'./browser/vendor/random.min.js',

			'./browser/scripts/datatypes/environmentSettings.js',

			'./browser/scripts/textureCache.js',

			'./browser/scripts/plugin-manager-bundled.js'
		],

		player: [
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
}

function errorHandler(err) {
	console.error(err.message, err.lineNumber, err.stack)
	this.emit('end')
}

gulp.task('clean:js:player', function(cb) {
	del('./browser/dist/player.min.js', cb)
})

gulp.task('clean:js:engine', function(cb) {
	del('./browser/dist/engine.js', cb)
})

gulp.task('clean:less360', function(cb)
{
	del('./browser/style/threesixty.css', cb);
});

gulp.task('clean:less', function(cb) {
	del('./browser/style/less.css', cb)
})

gulp.task('clean:js', ['clean:js:player', 'clean:js:engine'])

gulp.task('clean', ['clean:js'])

gulp.task('js:engine', ['clean:js:engine'], function(done) {
	gulp.src(paths.js.engine)
	.pipe(concat.header(';\n'))
	.pipe(concat('engine.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('js:player', ['clean:js:player', 'js:engine'], function(done) {
	var playerPipe = gulp.src(paths.js.engine.concat(paths.js.player))

	// only uglify in production
	if (process.env.NODE_ENV === 'production') {
		playerPipe = playerPipe
			.pipe(uglify().on('error', errorHandler))
	}

	playerPipe
	.pipe(concat.header(';\n'))
	.pipe(concat('player.min.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('push', ['js:player'], function(done) {
	pushPlayerToGrid()
		.then(done, errorHandler)
})

gulp.task('js', ['js:player'])

gulp.task('less', ['clean:less'], function() {
	gulp.src(paths.less)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('less.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
})

gulp.task('less360', ['clean:less360'], function() {
	gulp.src(paths.less360)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('threesixty.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
});

gulp.task('watch', ['default'], function() {
	gulp.watch('less/**/*', ['less', 'less360']);
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('watch:less360', function() {
	gulp.watch('less/threesixty.less', ['less360']);
});

gulp.task('watch:less', function() {
	gulp.watch('less/**/*', ['less'])
})

gulp.task('watch:player', function() {
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('golive', ['less', 'less360', 'js'])

gulp.task('default', ['less', 'less360', 'js', 'push'])

<commit_msg>Add THREE.MeshLine.js<commit_after>const gulp = require('gulp')
const fs = require('fs')
const path = require('path')
const uglify = require('gulp-uglify')
const concat = require('gulp-concat-util')
const del = require('del')
const less = require('gulp-less')
const preprocess = require('gulp-preprocess')

const pushPlayerToGrid = require('./tools/pushPlayerToGrid')

var paths = {
	less: './less/build.less',
	less360: './less/build_threesixty.less',
	js: {
		plugins: './browser/plugins/*.plugin.js',
		engine: [
			'./browser/vendor/when.js',

			'./browser/scripts/event-emitter.js',
			'./browser/scripts/core.js',
			'./browser/scripts/util.js',

			'./browser/scripts/connection.js',
			'./browser/scripts/variables.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/autoSlotGroup.js',

			'./browser/scripts/plugin.js',
			'./browser/scripts/subGraphPlugin.js',
			'./browser/scripts/threeObject3dPlugin.js',
			'./browser/scripts/abstractObjectGazePlugin.js',
			'./browser/scripts/abstractThreeLoaderObjPlugin.js',
			'./browser/scripts/abstractThreeMaterialPlugin.js',
			'./browser/scripts/abstractThreeMeshPlugin.js',
			'./browser/scripts/abstractArrayBlendModulatorPlugin.js',
			'./browser/scripts/abstractAnimateValueOnTriggerPlugin.js',

			'./browser/scripts/blendFunctions.js',

			'./browser/scripts/worldEditor/worldEditor.js',
			'./browser/scripts/worldEditor/worldEditorPerspectiveCamera.js',
			'./browser/scripts/worldEditor/worldEditorOrthographicCamera.js',
			'./browser/scripts/worldEditor/worldEditorCameraSelector.js',
			'./browser/scripts/worldEditor/worldEditorOriginGrid.js',
			'./browser/scripts/worldEditor/worldEditorRadialHelper.js',

			'./browser/scripts/screenshot/ScreenshotRenderer.js',

			'./browser/scripts/loaders/loader.js',
			'./browser/scripts/loaders/imageLoader.js',
			'./browser/scripts/loaders/textureLoader.js',
			'./browser/scripts/loaders/modelLoader.js',
			'./browser/scripts/loaders/sceneLoader.js',
			'./browser/scripts/loaders/assetLoader.js',
			'./browser/scripts/loaders/audioBufferLoader.js',
			'./browser/scripts/loaders/multiObjectLoader.js',

			'./browser/scripts/documentation/pluginDocsCache.js',

			'./browser/vendor/three/three.js',
			'./browser/vendor/three/OBJLoader.js',
			'./browser/vendor/three/OBJMTLLoader.js',
			'./browser/vendor/three/MTLLoader.js',
			'./browser/vendor/three/DDSLoader.js',
			'./browser/vendor/three/VREffect.js',
			'./browser/vendor/three/CardboardEffect.js',
			'./browser/vendor/three/VRControls.js',
			'./browser/vendor/three/SceneLoader.js',
			'./browser/vendor/three/MorphAnimMesh.js',
			'./browser/vendor/three/THREE.MeshLine.js',

			'./browser/vendor/borismus/webvr-polyfill.js',
			'./browser/vendor/borismus/webvr-manager.js',

			'./browser/scripts/noise.js',
			'./browser/vendor/random.min.js',

			'./browser/scripts/datatypes/environmentSettings.js',

			'./browser/scripts/textureCache.js',

			'./browser/scripts/plugin-manager-bundled.js'
		],

		player: [
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
}

function errorHandler(err) {
	console.error(err.message, err.lineNumber, err.stack)
	this.emit('end')
}

gulp.task('clean:js:player', function(cb) {
	del('./browser/dist/player.min.js', cb)
})

gulp.task('clean:js:engine', function(cb) {
	del('./browser/dist/engine.js', cb)
})

gulp.task('clean:less360', function(cb)
{
	del('./browser/style/threesixty.css', cb);
});

gulp.task('clean:less', function(cb) {
	del('./browser/style/less.css', cb)
})

gulp.task('clean:js', ['clean:js:player', 'clean:js:engine'])

gulp.task('clean', ['clean:js'])

gulp.task('js:engine', ['clean:js:engine'], function(done) {
	gulp.src(paths.js.engine)
	.pipe(concat.header(';\n'))
	.pipe(concat('engine.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('js:player', ['clean:js:player', 'js:engine'], function(done) {
	var playerPipe = gulp.src(paths.js.engine.concat(paths.js.player))

	// only uglify in production
	if (process.env.NODE_ENV === 'production') {
		playerPipe = playerPipe
			.pipe(uglify().on('error', errorHandler))
	}

	playerPipe
	.pipe(concat.header(';\n'))
	.pipe(concat('player.min.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('push', ['js:player'], function(done) {
	pushPlayerToGrid()
		.then(done, errorHandler)
})

gulp.task('js', ['js:player'])

gulp.task('less', ['clean:less'], function() {
	gulp.src(paths.less)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('less.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
})

gulp.task('less360', ['clean:less360'], function() {
	gulp.src(paths.less360)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('threesixty.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
});

gulp.task('watch', ['default'], function() {
	gulp.watch('less/**/*', ['less', 'less360']);
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('watch:less360', function() {
	gulp.watch('less/threesixty.less', ['less360']);
});

gulp.task('watch:less', function() {
	gulp.watch('less/**/*', ['less'])
})

gulp.task('watch:player', function() {
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('golive', ['less', 'less360', 'js'])

gulp.task('default', ['less', 'less360', 'js', 'push'])

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import { Overlay, Popover, Input, Glyphicon } from 'react-bootstrap';
require('./bootstrap-clockpicker.css');

const CP_EDITING = {
  NOT_EDITING: 0,
  HOURS: 1,
  MINUTES: 2
};

export default class ClockPicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editing: CP_EDITING.NOT_EDITING
    };
  }

  static propTypes = {
    hours: React.PropTypes.number.isRequired,
    minutes: React.PropTypes.number.isRequired,
    onChange: React.PropTypes.func.isRequired,
    placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']).isRequired,
    addonBefore: React.PropTypes.node,
    disabled: React.PropTypes.bool.isRequired
  };

  static defaultProps = {
    hours: 13,
    minutes: 30,
    placement: 'bottom',
    disabled: false
  };

  render() {
    const { hours, minutes, onChange, placement, addonBefore, disabled } = this.props;

    let hourTicks = [],
      minuteTicks = [];

    const tickRadius = 13,
      dialRadius = 100,
      outerRadius = 80,
      innerRadius = 54,
      leadingZero = (num) => (num < 10 ? '0' : '') + num;

    const title = (

         this.setState({editing: CP_EDITING.HOURS})}>
          {leadingZero(hours)}

        {' : '}
         this.setState({editing: CP_EDITING.MINUTES})}>
          {leadingZero(minutes)}

    );

    for (let i = 0; i < 24; i += 1) {
      const radian = i / 6 * Math.PI;
      const inner = i > 0 && i < 13;
      const radius = inner ? innerRadius : outerRadius;
      const left = dialRadius + Math.sin(radian) * radius - tickRadius;
      const top = dialRadius - Math.cos(radian) * radius - tickRadius;
      const text = i === 0 ? '00' : i;

      hourTicks.push(

 {
            this.setState({ editing: CP_EDITING.MINUTES })
            onChange(i, minutes)
          }}
          style={{left, top, fontSize: inner ? '120%' : '100%'}}>
          {text}

      );
    }

    for (let i = 0; i < 60; i += 5) {
      const radian = i / 30 * Math.PI;
      const left = dialRadius + Math.sin(radian) * outerRadius - tickRadius;
      const top = dialRadius - Math.cos(radian) * outerRadius - tickRadius;
      const text = leadingZero(i);

      minuteTicks.push(

 {
            this.setState({ editing: CP_EDITING.NOT_EDITING })
            onChange(hours, i)
          }}
          style={{left, top, fontSize: '120%'}}>
          {text}

      );
    }

    const value = this.state.editing === CP_EDITING.HOURS ? hours : minutes,
      unit = Math.PI / (this.state.editing === CP_EDITING.HOURS ? 6 : 30),
      radian = value * unit,
      radius = this.state.editing === CP_EDITING.HOURS && value > 0 && value < 13 ? innerRadius : outerRadius,
      x = Math.sin(radian) * radius,
      y = - Math.cos(radian) * radius;

    const hand = (
      <svg className="clockpicker-svg" width="200" height="200">
        <g transform="translate(100,100)">
          <line x1="0" y1="0" x2={x} y2={y}></line>
          <circle className="clockpicker-canvas-fg" r="3.5" cx={x} cy={y}></circle>
          <circle className="clockpicker-canvas-bg" r="13" cx={x} cy={y}></circle>
          <circle className="clockpicker-canvas-bearing" cx="0" cy="0" r="2"></circle>
        </g>
      </svg>
    );

    const startEditing = () => {
      if (!disabled) {
        this.setState({ editing: CP_EDITING.HOURS });
      }
    }

    return (

        <Input
          type="text"
          ref="target"
          className="clockpicker"
          disabled={disabled}
          value={leadingZero(hours) + ':' + leadingZero(minutes)}
          onChange={() => false} // TODO
          onClick={startEditing}
          addonBefore={addonBefore}
          addonAfter={<Glyphicon glyph="time" onClick={startEditing} />} />
        <Overlay
          placement={placement}
          animation={false}
          show={this.state.editing !== CP_EDITING.NOT_EDITING}
          rootClose={true}
          onHide={() => this.setState({ editing: CP_EDITING.NOT_EDITING })}
          container={this}
          target={() => findDOMNode(this.refs.target)}>
          <Popover id="clockpicker" className="clockpicker-popover" title={title}>

                { hand }

              { this.state.editing === CP_EDITING.HOURS ?

                { hourTicks }

 :

                { minuteTicks }

              }

          </Popover>
        </Overlay>

    );
  }
}
<commit_msg>Switch from Overlay to OverlayTrigger<commit_after>import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import { OverlayTrigger, Popover, Input, Glyphicon } from 'react-bootstrap';
require('./bootstrap-clockpicker.css');

const CP_EDITING = {
  NOT_EDITING: 0,
  HOURS: 1,
  MINUTES: 2
};

export default class ClockPicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editing: CP_EDITING.NOT_EDITING
    };
  }

  static propTypes = {
    hours: React.PropTypes.number.isRequired,
    minutes: React.PropTypes.number.isRequired,
    onChange: React.PropTypes.func.isRequired,
    placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']).isRequired,
    addonBefore: React.PropTypes.node,
    disabled: React.PropTypes.bool.isRequired
  };

  static defaultProps = {
    hours: 13,
    minutes: 30,
    placement: 'bottom',
    disabled: false
  };

  render() {
    const { hours, minutes, onChange, placement, addonBefore, disabled } = this.props;

    let hourTicks = [],
      minuteTicks = [];

    const tickRadius = 13,
      dialRadius = 100,
      outerRadius = 80,
      innerRadius = 54,
      leadingZero = (num) => (num < 10 ? '0' : '') + num;

    const title = (

         this.setState({editing: CP_EDITING.HOURS})}>
          {leadingZero(hours)}

        {' : '}
         this.setState({editing: CP_EDITING.MINUTES})}>
          {leadingZero(minutes)}

    );

    for (let i = 0; i < 24; i += 1) {
      const radian = i / 6 * Math.PI;
      const inner = i > 0 && i < 13;
      const radius = inner ? innerRadius : outerRadius;
      const left = dialRadius + Math.sin(radian) * radius - tickRadius;
      const top = dialRadius - Math.cos(radian) * radius - tickRadius;
      const text = i === 0 ? '00' : i;

      hourTicks.push(

 {
            this.setState({ editing: CP_EDITING.MINUTES })
            onChange(i, minutes)
          }}
          style={{left, top, fontSize: inner ? '120%' : '100%'}}>
          {text}

      );
    }

    for (let i = 0; i < 60; i += 5) {
      const radian = i / 30 * Math.PI;
      const left = dialRadius + Math.sin(radian) * outerRadius - tickRadius;
      const top = dialRadius - Math.cos(radian) * outerRadius - tickRadius;
      const text = leadingZero(i);

      minuteTicks.push(

 {
            this.setState({ editing: CP_EDITING.NOT_EDITING })
            onChange(hours, i)
          }}
          style={{left, top, fontSize: '120%'}}>
          {text}

      );
    }

    const value = this.state.editing === CP_EDITING.HOURS ? hours : minutes,
      unit = Math.PI / (this.state.editing === CP_EDITING.HOURS ? 6 : 30),
      radian = value * unit,
      radius = this.state.editing === CP_EDITING.HOURS && value > 0 && value < 13 ? innerRadius : outerRadius,
      x = Math.sin(radian) * radius,
      y = - Math.cos(radian) * radius;

    const hand = (
      <svg className="clockpicker-svg" width="200" height="200">
        <g transform="translate(100,100)">
          <line x1="0" y1="0" x2={x} y2={y}></line>
          <circle className="clockpicker-canvas-fg" r="3.5" cx={x} cy={y}></circle>
          <circle className="clockpicker-canvas-bg" r="13" cx={x} cy={y}></circle>
          <circle className="clockpicker-canvas-bearing" cx="0" cy="0" r="2"></circle>
        </g>
      </svg>
    );

    const startEditing = () => {
      if (!disabled) {
        this.setState({ editing: CP_EDITING.HOURS });
      }
    }

    const popover = (
      <Popover id="clockpicker" className="clockpicker-popover" title={title}>

            { hand }

          { this.state.editing === CP_EDITING.HOURS ?

            { hourTicks }

 :

            { minuteTicks }

          }

      </Popover>
    );

    return (

        <OverlayTrigger
          trigger="click"
          placement={placement}
          animation={false}
          show={this.state.editing !== CP_EDITING.NOT_EDITING}
          rootClose={true}
          onHide={() => this.setState({ editing: CP_EDITING.NOT_EDITING })}
          overlay={popover}>
          <Input
            type="text"
            ref="target"
            className="clockpicker"
            disabled={disabled}
            value={leadingZero(hours) + ':' + leadingZero(minutes)}
            onChange={() => false} // TODO
            onClick={startEditing}
            addonBefore={addonBefore}
            addonAfter={<Glyphicon glyph="time" onClick={startEditing} />} />
        </OverlayTrigger>

    );
  }
}
<|endoftext|>


<commit_before>/** ----------------------------------------------------------------------------
 * @author  Avin Cheng
 * @desc    Build and zip theme flat-ghost.
 * @license MIT
 ** --------------------------------------------------------------------------*/
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const { src, dest, series, parallel } = require('gulp');

/**
 * Gulp Plugins
 */
const concat = require('gulp-concat');
const processHtml = require('gulp-processhtml');
const postCss = require('gulp-postcss');
const minifyJs = require('gulp-uglify');
const rev = require('gulp-rev');
const revRewrite = require('gulp-rev-rewrite')
const zip = require('gulp-zip');

/**
 * PostCSS Plugins
 */
const autoPreFixer = require('autoprefixer');
const url = require('postcss-url');
const cssNano = require('cssnano');

/**
 * Global Variables
 */
const DIST_DIR = './dist/';
const BUILD_DIR = './dist/build/';
const ASSETS_DIR = './dist/build/assets/';
const MANIFEST_FILE = path.join('./dist/rev-manifest.json');

/**
 * Clean Files
 */
function cleanFiles(cb) {
  rimraf(DIST_DIR, cb);
}

/**
 * Copy Files
 */
function copyFiles() {
  return src([
    './*.md',
    './*.json',
    './LICENSE',

    // assets
    './assets/images/*.*',
    './assets/screenshots/*.*',

    // handlebars
    './*.hbs',
    './partials/*.hbs',
    '!./default.hbs'
  ], { base: './' })
    .pipe(dest(BUILD_DIR));
}

/**
 * Process Handlebars
 */
function processHbs() {
  return src('./default.hbs')
    .pipe(processHtml())
    .pipe(dest(BUILD_DIR));
}

/**
 * Process CSS
 */
function processCss() {
  const urlOptions = {
    url: 'inline',
    encodeType: 'base64',
    maxSize: 8 * 1024
  }

  const postCssPlugins = [
    autoPreFixer(),
    url(urlOptions),
    cssNano()
  ];

  return src([
    './assets/libraries/prism/prism.css',
    './assets/css/basic.css',
    './assets/css/global.css',
    './assets/css/screen.css',
    './assets/css/widgets.css',
    './assets/css/mobile.css',
  ], { base: './assets/' })
    .pipe(concat('css/bundle.css'))
    .pipe(postCss(postCssPlugins))
    .pipe(rev())
    .pipe(dest(ASSETS_DIR))
    .pipe(rev.manifest(MANIFEST_FILE, { base: DIST_DIR, merge: true }))
    .pipe(dest(DIST_DIR));
}

/**
 * Process JS
 */
function processJs() {
  return src('./assets/js/*.js', { base: './assets/' })
    .pipe(concat('js/bundle.js'))
    .pipe(minifyJs())
    .pipe(rev())
    .pipe(dest(ASSETS_DIR))
    .pipe(rev.manifest(MANIFEST_FILE, { base: DIST_DIR, merge: true }))
    .pipe(dest(DIST_DIR));
}

/**
 * Rewrite references to assets revisioned by `gulp-rev`
 */
function reWriteRefs() {
  return src(path.join(BUILD_DIR, 'default.hbs'))
    .pipe(revRewrite({ manifest: src(MANIFEST_FILE) }))
    .pipe(dest(BUILD_DIR));
}

/**
 * Zip Theme
 */
// require(./package.json) can run into caching issues
const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));
const filename = packageJson.name + '_v' + packageJson.version + '.zip';

function zipper() {
  return src('./dist/build/**/*.*')
    .pipe(zip(filename))
    .pipe(dest(DIST_DIR));
}

/**
 * Exports
 */
exports.build = series(
  cleanFiles,
  processHbs,
  parallel(copyFiles, processCss, processJs),
  reWriteRefs
);

exports.zip = series(
  cleanFiles,
  processHbs,
  parallel(copyFiles, processCss, processJs),
  zipper
);
<commit_msg>fix: fix zip error<commit_after>/** ----------------------------------------------------------------------------
 * @author  Avin Cheng
 * @desc    Build and zip theme flat-ghost.
 * @license MIT
 ** --------------------------------------------------------------------------*/
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const { src, dest, series, parallel } = require('gulp');

/**
 * Gulp Plugins
 */
const concat = require('gulp-concat');
const processHtml = require('gulp-processhtml');
const postCss = require('gulp-postcss');
const minifyJs = require('gulp-uglify');
const rev = require('gulp-rev');
const revRewrite = require('gulp-rev-rewrite')
const zip = require('gulp-zip');

/**
 * PostCSS Plugins
 */
const autoPreFixer = require('autoprefixer');
const url = require('postcss-url');
const cssNano = require('cssnano');

/**
 * Global Variables
 */
const DIST_DIR = './dist/';
const BUILD_DIR = './dist/build/';
const ASSETS_DIR = './dist/build/assets/';
const MANIFEST_FILE = path.join('./dist/rev-manifest.json');

/**
 * Clean Files
 */
function cleanFiles(cb) {
  rimraf(DIST_DIR, cb);
}

/**
 * Copy Files
 */
function copyFiles() {
  return src([
    './*.md',
    './*.json',
    './LICENSE',

    // assets
    './assets/images/*.*',
    './assets/screenshots/*.*',

    // handlebars
    './*.hbs',
    './partials/*.hbs',
    '!./default.hbs'
  ], { base: './' })
    .pipe(dest(BUILD_DIR));
}

/**
 * Process Handlebars
 */
function processHbs() {
  return src('./default.hbs')
    .pipe(processHtml())
    .pipe(dest(BUILD_DIR));
}

/**
 * Process CSS
 */
function processCss() {
  const urlOptions = {
    url: 'inline',
    encodeType: 'base64',
    maxSize: 8 * 1024
  }

  const postCssPlugins = [
    autoPreFixer(),
    url(urlOptions),
    cssNano()
  ];

  return src([
    './assets/libraries/prism/prism.css',
    './assets/css/basic.css',
    './assets/css/global.css',
    './assets/css/screen.css',
    './assets/css/widgets.css',
    './assets/css/mobile.css',
  ], { base: './assets/' })
    .pipe(concat('css/bundle.css'))
    .pipe(postCss(postCssPlugins))
    .pipe(rev())
    .pipe(dest(ASSETS_DIR))
    .pipe(rev.manifest(MANIFEST_FILE, { base: DIST_DIR, merge: true }))
    .pipe(dest(DIST_DIR));
}

/**
 * Process JS
 */
function processJs() {
  return src('./assets/js/*.js', { base: './assets/' })
    .pipe(concat('js/bundle.js'))
    .pipe(minifyJs())
    .pipe(rev())
    .pipe(dest(ASSETS_DIR))
    .pipe(rev.manifest(MANIFEST_FILE, { base: DIST_DIR, merge: true }))
    .pipe(dest(DIST_DIR));
}

/**
 * Rewrite references to assets revisioned by `gulp-rev`
 */
function reWriteRefs() {
  return src(path.join(BUILD_DIR, 'default.hbs'))
    .pipe(revRewrite({ manifest: src(MANIFEST_FILE) }))
    .pipe(dest(BUILD_DIR));
}

/**
 * Zip Theme
 */
// require(./package.json) can run into caching issues
const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));
const filename = packageJson.name + '_v' + packageJson.version + '.zip';

function zipper() {
  return src('./dist/build/**/*.*')
    .pipe(zip(filename))
    .pipe(dest(DIST_DIR));
}

/**
 * Exports
 */
exports.build = series(
  cleanFiles,
  processHbs,
  parallel(copyFiles, processCss, processJs),
  reWriteRefs
);

exports.zip = series(
  cleanFiles,
  processHbs,
  parallel(copyFiles, processCss, processJs),
  reWriteRefs,
  zipper
);
<|endoftext|>


<commit_before>// How large a result set we try to return before splitting it up into smaller
// chunks
var CHUNK_SIZE = 100;

// Okay, so this is some dodgy meta shit that I probably really shouldn't be
// doing in javascript. It's not my fault the API is odd.
function apply_constructor(klass, opts) {
	function applicator() {
		// This seems to be the only way to call .apply on a
		// constructor in javascript
		return klass.apply(this, opts);
	}
	applicator.prototype = klass.prototype;
	return new applicator();
}

// Stops execution, sending a HTTP 400 response
function argument_error(message)
{
	throw nlapiCreateError('400', message);
}

// Returns a simple record as an associative array
function get_record_by_id(type_id, fields, id)
{
	var record = nlapiLoadRecord(type_id, id);
	var response = {};

	for(var i = 0; i < fields.length; i++ ) {
		response[fields[i]] = record.getFieldValue(fields[i]);
	}

	return(response);
}

// Transfrom from a record type, to another, given ID. The set a bunch of
// fields on that new record type.
// Arguments::
// 	source_id:: source record internal id
// 	source_type_id:: source record type, e.g. invoice
// 	target_type_id:: target record type, e.g. customerpayment
// 	data:: hash of key/values to set before saving the new deferred record
// 	fields:: array of fields for target type
function transform(request)
{
	var deferred = nlapiTransformRecord(
		request.source_type_id,
		request.source_id,
		request.target_type_id
	);

	for(var field in request.data) {
		deferred.setFieldValue(field, request.data[field]);
	}

	return(get_record_by_id(
		request.target_type_id,
		request.fields,
		nlapiSubmitRecord(deferred, true)
	));
}

// In order to update an item, we create a diff of what has actually changed,
// then commit just those changes.
function update(request)
{
	if(!request.data.hasOwnProperty('id')) {
		argument_error('update action requires an id');
	}

	var diff = {};
	var record = nlapiLoadRecord(request.type_id, request.data.id);

	for(var field in request.data) {
		if(record.getFieldValue(field) != request.data[field]) {
			diff[field] = request.data[field];
		}
	}

	for(var field in diff) {
		record.setFieldValue(field, diff[field]);
	}

	return(get_record_by_id(
		request.type_id,
		request.fields,
		nlapiSubmitRecord(record, true)
	));
}

// Return an array of hashes representing the result set.
function retrieve_result_set(results, fields)
{
	var response = [];
	// Can't seem to get all columns back without running nlapiLoadRecord,
	// I tried a few different ways and netsuite either returned null
	// responses or exploded spectacularly. So, we are inefficient for now.
	//
	// This is what has lead to the whole configurable chunking
	// implementation.
	for(var i = 0; i < results.length; i++ ) {
		var result = results[i];
		response.push(
			get_record_by_id(
				result.getRecordType(),
				fields,
				result.getId()
			)
		);
	}

	return response;
}

// Return the requested chunk offset, which should be incremented by one for
// each chunk.
function search_chunked(search, fields, chunk)
{
	var offset = chunk * CHUNK_SIZE;
	var results = search.runSearch().getResults(offset, offset + CHUNK_SIZE);
	if(results.length == 0) {
		throw nlapiCreateError('400', 'NO_MORE_CHUNKS');
	}
	return(retrieve_result_set(results, fields));
}

// Called if we aren't specifically asking for a chunk of the result set.
// Returns:: An array of records of length < CHUNK_SIZE
// Raises:: A 400, 'CHUNKY_MONKEY' if the result size is >= CHUNK_SIZE, it is
// 	expected that you now send a follow up request asking for chunks until
// 	you recive another error, 'NO_MORE_CHUNKS'
function search_no_chunked(search, fields)
{
	var results = search.runSearch().getResults(0, CHUNK_SIZE);

	// If there are CHUNK_SIZE results, we need to chunk
	if (results.length == CHUNK_SIZE) {
		// So we send an error message to signify that the client
		// should make a different kind of search request
		throw nlapiCreateError('400', 'CHUNKY_MONKEY');
	}

	return(retrieve_result_set(results, fields));
}

// Only return the columns requested, not whole objects.
// Returns:: Array of arrays containing all columns requested.
function raw_search(request)
{
	var columns = [];
	var filters = [];
	var response = [];

	// Generate filters
	for(var i = 0; i < request.data.filters.length; i++ ) {
		filters.push(
			apply_constructor(
				nlobjSearchFilter, request.data.filters[i]
			)
		);
	}

	// Doesn't work when we try to create columns then supply them at
	// creation, so we create them after we create the search.
	var search = nlapiCreateSearch(request.type_id, filters, []);

	// Now, for whatever reason, we can add columns.
	for(var i = 0; i < request.data.columns.length; i++ ) {
		columns.push(apply_constructor(
			nlobjSearchColumn, request.data.columns[i]
		));
		search.addColumn(columns[i]);
	}

	var search_result = search.runSearch();
	// We go 1000 at a time as that is the maximum we are allowed
	var MAX_PER_GET=1000;
	for(var i = 0; true; i += MAX_PER_GET) {
		var result_set = search_result.getResults(i, MAX_PER_GET);
		for(var j = 0; j < result_set.length; j++) {
			response.push([]);
			for(var k = 0; k < columns.length; k++) {
				response[j].push(
					result_set[j].getValue(columns[k])
				);
			}
		}
		if(result_set.length < MAX_PER_GET) {
			// No more results
			break;
		}
	}

	return(response);
}

function search(request)
{
	// Maximum results to return before we split our response into a
	// chunked, multi request response. Note, this has nothing to do with a
	// HTTP chunked response, it's simply us requesting a different offest
	// each time.

	var filters = [];
	for(var i = 0; i < request.data.filters.length; i++ ) {
		filters.push(
			apply_constructor(
				nlobjSearchFilter, request.data.filters[i]
			)
		);
	}

	var search = nlapiCreateSearch(request.type_id, filters, []);

	if(request.data.hasOwnProperty('chunk')){
		return(search_chunked(
			search, request.fields, request.data.chunk
		));
	} else {
		return search_no_chunked(search, request.fields);
	}
}

// Retrieve a single record by id
function retrieve(request)
{
	if(!request.data.hasOwnProperty('id')) {
		argument_error('retrieve action requires an id');
	}

	return(get_record_by_id(
		request.type_id, request.fields, request.data.id)
	);
}

// Load a list of fields for type specified by type_id
// Returns:: Array of strings
// Delete a record by id
function delete_id(request)
{
	if(!request.data.hasOwnProperty('id')) {
		argument_error('delete action requires an id');
	}

	// Return value is moot, should throw an error on failure
	nlapiDeleteRecord(request.type_id, parseInt(request.data.id));
	return([]);
}

// Create a new record
function create(request)
{
	var record = nlapiCreateRecord(request.type_id);

	for(var field in request.data) {
		record.setFieldValue(field, request.data[field]);
	}

	// request.sublists is a hash that looks like this:
	// {'addressbook' => [{'addr1' => 'line 1 of address'}]
	//
	// Note: For some reason when you try to commit the line item, as the
	// documentation says you *must*, the item is not saved.
	//
	// So, we don't. And it works.
	for(var sublist_id in request.sublists) {
		for(var i = 0; i < request.sublists[sublist_id].length; i++) {
			var item = request.sublists[sublist_id][i];
			record.insertLineItem(sublist_id, i + 1);
			for(var subfield in item) {
				record.setLineItemValue(
					sublist_id,
					subfield,
					i + 1,
					item[subfield]
				);
			}
		}
	}

	return(get_record_by_id(
		request.type_id,
		request.fields,
		nlapiSubmitRecord(record, true)
	));
}

// Given a record, sublist_id and array of fields, retrieve the whole sublist
// as an array of hashes
function get_sublist(record, sublist_id, fields)
{
	var len = record.getLineItemCount(request.sublist_id);
	var response = [];
	for(var i = 1; i <= len; i++) {
		list_item = {};
		for(var j = 0; j < fields.length; j++) {
			list_item[fields[j]] = record.getLineItemValue(
				sublist_id, fields[j], i
			)
		}
		response.push(list_item);
	}
	return(response);
}

// Basically a wrapper for get_sublist()
function fetch_sublist(request)
{
	if(!request.hasOwnProperty('parent_id')) {
		argument_error("Missing mandatory argument: parent_id");
	}

	if(!request.hasOwnProperty('sublist_id')) {
		argument_error("Missing mandatory argument: sublist_id");
	}

	var record = nlapiLoadRecord(request.type_id, request.parent_id);
	return(get_sublist(record, request.sublist_id, request.fields));
}

// Make sure we have the required arguments in our request object
function pre_flight_check(request)
{
	delete(request['code']);

	if (!request.hasOwnProperty('action')) {
		argument_error("Missing mandatory argument: action");
	}

	// Some actions may not care about these
	if (!request.hasOwnProperty('fields')) {
		request.fields = [];
	}
	if (!request.hasOwnProperty('sublists')) {
		request.sublists = {};
	}
	if (!request.hasOwnProperty('data')) {
		request.data = {};
	}
}

// Render a PDF invoice
//
// Arguments::
// 	invoice_id:: the ID of the invoice to render
//
// Returns:: An array with only element, a base64 encoded string of the
// generated PDF
function invoice_pdf(request) {
	if(!request.hasOwnProperty('invoice_id')) {
		argument_error('Missing mandatory argument: invoice_id');
	};

	var file = nlapiPrintRecord(
		'TRANSACTION',
		request.invoice_id,
		'PDF',
		null
	);

	return [file.getValue()];
}

// Attach all customers in data from ourselves
// Arguments::
// 	target_type_id:: target 'type_id'
// 	attachee_id:: id of record type 'type_id' to attach from
// 	data:: array of ids to attach
// 	attributes:: optional attributes
function attach(request) {
	for(var i = 0; i < request.data.length; i++) {
		nlapiAttachRecord(
			request.type_id,
			request.attachee_id,
			request.target_type_id,
			parseInt(request.data[i]),
			request.attributes
		);
	}
	return([]);
}
//
// Detach all customers in data from ourselves
// Arguments::
// 	target_type_id:: target 'type_id'
// 	attachee_id:: id of record type 'type_id' to detach from
// 	data:: array of ids to attach
// 	attributes:: optional attributes
function detach(request) {
	for(var i = 0; i < request.data.length; i++) {
		nlapiDetachRecord(
			request.type_id,
			request.attachee_id,
			request.target_type_id,
			parseInt(request.data[i])
		);
	}
	return([]);
}

// As the last visible function, this is the one actually run and the return
// value is sent back to the client as JSON.
function main(request)
{
	pre_flight_check(request);

	var actions = {
		'delete'        : delete_id, // delete is a reserved word
		'create'        : create,
		'retrieve'      : retrieve,
		'search'        : search,
		'update'        : update,
		'fetch_sublist' : fetch_sublist,
		'invoice_pdf'   : invoice_pdf,
		'attach'   	: attach,
		'detach'   	: detach,
		'raw_search'   	: raw_search,
		'transform'   	: transform
	}

	if(!(request.action in actions)) {
		argument_error("Unknown action: " + request.action);
	}

	return actions[request.action](request);
}
<commit_msg>There is a 1/1000 chance that raw_search is broken for more than a thousand records. We shall soon see. Exciting.<commit_after>// How large a result set we try to return before splitting it up into smaller
// chunks
var CHUNK_SIZE = 100;

// Okay, so this is some dodgy meta shit that I probably really shouldn't be
// doing in javascript. It's not my fault the API is odd.
function apply_constructor(klass, opts) {
	function applicator() {
		// This seems to be the only way to call .apply on a
		// constructor in javascript
		return klass.apply(this, opts);
	}
	applicator.prototype = klass.prototype;
	return new applicator();
}

// Stops execution, sending a HTTP 400 response
function argument_error(message)
{
	throw nlapiCreateError('400', message);
}

// Returns a simple record as an associative array
function get_record_by_id(type_id, fields, id)
{
	var record = nlapiLoadRecord(type_id, id);
	var response = {};

	for(var i = 0; i < fields.length; i++ ) {
		response[fields[i]] = record.getFieldValue(fields[i]);
	}

	return(response);
}

// Transfrom from a record type, to another, given ID. The set a bunch of
// fields on that new record type.
// Arguments::
// 	source_id:: source record internal id
// 	source_type_id:: source record type, e.g. invoice
// 	target_type_id:: target record type, e.g. customerpayment
// 	data:: hash of key/values to set before saving the new deferred record
// 	fields:: array of fields for target type
function transform(request)
{
	var deferred = nlapiTransformRecord(
		request.source_type_id,
		request.source_id,
		request.target_type_id
	);

	for(var field in request.data) {
		deferred.setFieldValue(field, request.data[field]);
	}

	return(get_record_by_id(
		request.target_type_id,
		request.fields,
		nlapiSubmitRecord(deferred, true)
	));
}

// In order to update an item, we create a diff of what has actually changed,
// then commit just those changes.
function update(request)
{
	if(!request.data.hasOwnProperty('id')) {
		argument_error('update action requires an id');
	}

	var diff = {};
	var record = nlapiLoadRecord(request.type_id, request.data.id);

	for(var field in request.data) {
		if(record.getFieldValue(field) != request.data[field]) {
			diff[field] = request.data[field];
		}
	}

	for(var field in diff) {
		record.setFieldValue(field, diff[field]);
	}

	return(get_record_by_id(
		request.type_id,
		request.fields,
		nlapiSubmitRecord(record, true)
	));
}

// Return an array of hashes representing the result set.
function retrieve_result_set(results, fields)
{
	var response = [];
	// Can't seem to get all columns back without running nlapiLoadRecord,
	// I tried a few different ways and netsuite either returned null
	// responses or exploded spectacularly. So, we are inefficient for now.
	//
	// This is what has lead to the whole configurable chunking
	// implementation.
	for(var i = 0; i < results.length; i++ ) {
		var result = results[i];
		response.push(
			get_record_by_id(
				result.getRecordType(),
				fields,
				result.getId()
			)
		);
	}

	return response;
}

// Return the requested chunk offset, which should be incremented by one for
// each chunk.
function search_chunked(search, fields, chunk)
{
	var offset = chunk * CHUNK_SIZE;
	var results = search.runSearch().getResults(offset, offset + CHUNK_SIZE);
	if(results.length == 0) {
		throw nlapiCreateError('400', 'NO_MORE_CHUNKS');
	}
	return(retrieve_result_set(results, fields));
}

// Called if we aren't specifically asking for a chunk of the result set.
// Returns:: An array of records of length < CHUNK_SIZE
// Raises:: A 400, 'CHUNKY_MONKEY' if the result size is >= CHUNK_SIZE, it is
// 	expected that you now send a follow up request asking for chunks until
// 	you recive another error, 'NO_MORE_CHUNKS'
function search_no_chunked(search, fields)
{
	var results = search.runSearch().getResults(0, CHUNK_SIZE);

	// If there are CHUNK_SIZE results, we need to chunk
	if (results.length == CHUNK_SIZE) {
		// So we send an error message to signify that the client
		// should make a different kind of search request
		throw nlapiCreateError('400', 'CHUNKY_MONKEY');
	}

	return(retrieve_result_set(results, fields));
}

// Only return the columns requested, not whole objects.
// Returns:: Array of arrays containing all columns requested.
function raw_search(request)
{
	var columns = [];
	var filters = [];
	var response = [];

	// Generate filters
	for(var i = 0; i < request.data.filters.length; i++ ) {
		filters.push(
			apply_constructor(
				nlobjSearchFilter, request.data.filters[i]
			)
		);
	}

	// Doesn't work when we try to create columns then supply them at
	// creation, so we create them after we create the search.
	var search = nlapiCreateSearch(request.type_id, filters, []);

	// Now, for whatever reason, we can add columns.
	for(var i = 0; i < request.data.columns.length; i++ ) {
		columns.push(apply_constructor(
			nlobjSearchColumn, request.data.columns[i]
		));
		search.addColumn(columns[i]);
	}

	var search_result = search.runSearch();
	// We go 1000 at a time as that is the maximum we are allowed
	var MAX_PER_GET=1000;
	for(var i = 0; true; i += MAX_PER_GET) {
		var result_set = search_result.getResults(i, MAX_PER_GET);
		for(var j = 0; j < result_set.length; j++) {
			response.push([]);
			for(var k = 0; k < columns.length; k++) {
				response[j+i].push(
					result_set[j].getValue(columns[k])
				);
			}
		}
		if(result_set.length < MAX_PER_GET) {
			// No more results
			break;
		}
	}

	return(response);
}

function search(request)
{
	// Maximum results to return before we split our response into a
	// chunked, multi request response. Note, this has nothing to do with a
	// HTTP chunked response, it's simply us requesting a different offest
	// each time.

	var filters = [];
	for(var i = 0; i < request.data.filters.length; i++ ) {
		filters.push(
			apply_constructor(
				nlobjSearchFilter, request.data.filters[i]
			)
		);
	}

	var search = nlapiCreateSearch(request.type_id, filters, []);

	if(request.data.hasOwnProperty('chunk')){
		return(search_chunked(
			search, request.fields, request.data.chunk
		));
	} else {
		return search_no_chunked(search, request.fields);
	}
}

// Retrieve a single record by id
function retrieve(request)
{
	if(!request.data.hasOwnProperty('id')) {
		argument_error('retrieve action requires an id');
	}

	return(get_record_by_id(
		request.type_id, request.fields, request.data.id)
	);
}

// Load a list of fields for type specified by type_id
// Returns:: Array of strings
// Delete a record by id
function delete_id(request)
{
	if(!request.data.hasOwnProperty('id')) {
		argument_error('delete action requires an id');
	}

	// Return value is moot, should throw an error on failure
	nlapiDeleteRecord(request.type_id, parseInt(request.data.id));
	return([]);
}

// Create a new record
function create(request)
{
	var record = nlapiCreateRecord(request.type_id);

	for(var field in request.data) {
		record.setFieldValue(field, request.data[field]);
	}

	// request.sublists is a hash that looks like this:
	// {'addressbook' => [{'addr1' => 'line 1 of address'}]
	//
	// Note: For some reason when you try to commit the line item, as the
	// documentation says you *must*, the item is not saved.
	//
	// So, we don't. And it works.
	for(var sublist_id in request.sublists) {
		for(var i = 0; i < request.sublists[sublist_id].length; i++) {
			var item = request.sublists[sublist_id][i];
			record.insertLineItem(sublist_id, i + 1);
			for(var subfield in item) {
				record.setLineItemValue(
					sublist_id,
					subfield,
					i + 1,
					item[subfield]
				);
			}
		}
	}

	return(get_record_by_id(
		request.type_id,
		request.fields,
		nlapiSubmitRecord(record, true)
	));
}

// Given a record, sublist_id and array of fields, retrieve the whole sublist
// as an array of hashes
function get_sublist(record, sublist_id, fields)
{
	var len = record.getLineItemCount(request.sublist_id);
	var response = [];
	for(var i = 1; i <= len; i++) {
		list_item = {};
		for(var j = 0; j < fields.length; j++) {
			list_item[fields[j]] = record.getLineItemValue(
				sublist_id, fields[j], i
			)
		}
		response.push(list_item);
	}
	return(response);
}

// Basically a wrapper for get_sublist()
function fetch_sublist(request)
{
	if(!request.hasOwnProperty('parent_id')) {
		argument_error("Missing mandatory argument: parent_id");
	}

	if(!request.hasOwnProperty('sublist_id')) {
		argument_error("Missing mandatory argument: sublist_id");
	}

	var record = nlapiLoadRecord(request.type_id, request.parent_id);
	return(get_sublist(record, request.sublist_id, request.fields));
}

// Make sure we have the required arguments in our request object
function pre_flight_check(request)
{
	delete(request['code']);

	if (!request.hasOwnProperty('action')) {
		argument_error("Missing mandatory argument: action");
	}

	// Some actions may not care about these
	if (!request.hasOwnProperty('fields')) {
		request.fields = [];
	}
	if (!request.hasOwnProperty('sublists')) {
		request.sublists = {};
	}
	if (!request.hasOwnProperty('data')) {
		request.data = {};
	}
}

// Render a PDF invoice
//
// Arguments::
// 	invoice_id:: the ID of the invoice to render
//
// Returns:: An array with only element, a base64 encoded string of the
// generated PDF
function invoice_pdf(request) {
	if(!request.hasOwnProperty('invoice_id')) {
		argument_error('Missing mandatory argument: invoice_id');
	};

	var file = nlapiPrintRecord(
		'TRANSACTION',
		request.invoice_id,
		'PDF',
		null
	);

	return [file.getValue()];
}

// Attach all customers in data from ourselves
// Arguments::
// 	target_type_id:: target 'type_id'
// 	attachee_id:: id of record type 'type_id' to attach from
// 	data:: array of ids to attach
// 	attributes:: optional attributes
function attach(request) {
	for(var i = 0; i < request.data.length; i++) {
		nlapiAttachRecord(
			request.type_id,
			request.attachee_id,
			request.target_type_id,
			parseInt(request.data[i]),
			request.attributes
		);
	}
	return([]);
}
//
// Detach all customers in data from ourselves
// Arguments::
// 	target_type_id:: target 'type_id'
// 	attachee_id:: id of record type 'type_id' to detach from
// 	data:: array of ids to attach
// 	attributes:: optional attributes
function detach(request) {
	for(var i = 0; i < request.data.length; i++) {
		nlapiDetachRecord(
			request.type_id,
			request.attachee_id,
			request.target_type_id,
			parseInt(request.data[i])
		);
	}
	return([]);
}

// As the last visible function, this is the one actually run and the return
// value is sent back to the client as JSON.
function main(request)
{
	pre_flight_check(request);

	var actions = {
		'delete'        : delete_id, // delete is a reserved word
		'create'        : create,
		'retrieve'      : retrieve,
		'search'        : search,
		'update'        : update,
		'fetch_sublist' : fetch_sublist,
		'invoice_pdf'   : invoice_pdf,
		'attach'   	: attach,
		'detach'   	: detach,
		'raw_search'   	: raw_search,
		'transform'   	: transform
	}

	if(!(request.action in actions)) {
		argument_error("Unknown action: " + request.action);
	}

	return actions[request.action](request);
}
<|endoftext|>


<commit_before>import _Input from 'react/components/UI/Inputs/components/Input';
import _Textarea from 'react/components/UI/Inputs/components/Textarea';
import _Select from 'react/components/UI/Inputs/components/Select';
import _Checkbox from 'react/components/UI/Inputs/components/Checkbox';
import _ErrorMessage from 'react/components/UI/Inputs/components/ErrorMessage';
import _TextInput from 'react/components/UI/Inputs/components/TextInput';
import _Label from 'react/components/UI/Inputs/components/Label';
import _mixin from 'react/components/UI/Inputs/mixin';

export const Input = _Input;
export const Textarea = _Textarea;
export const Select = _Select;
export const Checkbox = _Checkbox;
export const ErrorMessage = _ErrorMessage;
export const TextInput = _TextInput;
export const Label = _Label;
export const mixin = _mixin;
export const inputVerticalPadding = x => `${x.theme.space[4]}`;
export const inputHorizontalPadding = x => `${x.theme.space[5]}`;
export const inputPadding = `${inputVerticalPadding} ${inputHorizontalPadding}`;
<commit_msg>Fixes inputPadding<commit_after>import _Input from 'react/components/UI/Inputs/components/Input';
import _Textarea from 'react/components/UI/Inputs/components/Textarea';
import _Select from 'react/components/UI/Inputs/components/Select';
import _Checkbox from 'react/components/UI/Inputs/components/Checkbox';
import _ErrorMessage from 'react/components/UI/Inputs/components/ErrorMessage';
import _TextInput from 'react/components/UI/Inputs/components/TextInput';
import _Label from 'react/components/UI/Inputs/components/Label';
import _mixin from 'react/components/UI/Inputs/mixin';

export const Input = _Input;
export const Textarea = _Textarea;
export const Select = _Select;
export const Checkbox = _Checkbox;
export const ErrorMessage = _ErrorMessage;
export const TextInput = _TextInput;
export const Label = _Label;
export const mixin = _mixin;
export const inputVerticalPadding = x => `${x.theme.space[4]}`;
export const inputHorizontalPadding = x => `${x.theme.space[5]}`;
export const inputPadding = x => `${x.theme.space[4]} ${x.theme.space[5]}`;
<|endoftext|>


<commit_before>var gulp       = require('gulp'),
    fs         = require('fs'),
    browserify = require('browserify'),
    babelify   = require('babelify'),
    source     = require('vinyl-source-stream');

gulp.task('build', function() {
  return browserify({
    entries: './lib/index.js',
    debug: false,
    // builtins     : false,
    insertGlobals: false,
    cache        : {},
    packageCache : {},
    fullPaths    : false
  })
    .transform(babelify)
    .bundle()
    .on('error', function(err) {
      console.log('Error:', err.message);
    })
    .pipe(source('index.js'))
    .pipe(gulp.dest('./build'));
});<commit_msg>update build<commit_after>var gulp       = require('gulp'),
    fs         = require('fs'),
    browserify = require('browserify'),
    babelify   = require('babelify'),
    source     = require('vinyl-source-stream');

gulp.task('build', function() {
  return browserify({
    entries: './lib/index.js',
    debug: false,
    // builtins     : false,
    insertGlobals: false,
    cache        : {},
    packageCache : {},
    node: true,
    fullPaths    : false
  })
    .transform(babelify)
    .bundle()
    .on('error', function(err) {
      console.log('Error:', err.message);
    })
    .pipe(source('index.js'))
    .pipe(gulp.dest('./build'));
});<|endoftext|>


<commit_before>const gulp = require('gulp');
const sass = require('node-sass');
const inlineTemplates = require('gulp-inline-ng2-template');
const exec = require('child_process').exec;

/**
 * Inline templates configuration.
 * @see  https://github.com/ludohenin/gulp-inline-ng2-template
 */
const INLINE_TEMPLATES = {
  SRC: './src/**/*.ts',
  DIST: './tmp/src-inlined',
  CONFIG: {
    base: '/src',
    target: 'es6',
    useRelativePaths: true,
    styleProcessor: compileSass
  }
};

/**
 * Inline external HTML and SCSS templates into Angular component files.
 * @see: https://github.com/ludohenin/gulp-inline-ng2-template
 */
gulp.task('inline-templates', () => {
  return gulp.src(INLINE_TEMPLATES.SRC)
    .pipe(inlineTemplates(INLINE_TEMPLATES.CONFIG))
    .pipe(gulp.dest(INLINE_TEMPLATES.DIST));
});

/**
 * Build ESM by running npm task.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm', ['inline-templates'], (callback) => {
  exec('npm run ngcompile', function (error, stdout, stderr) {
    console.log(stdout, stderr);
    callback(error)
  });
});

/**
 * Implements ESM build watch mode.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm:watch', ['build:esm'], () => {
  gulp.watch('src/**/*', ['build:esm']);
});

/**
 * Compile SASS to CSS.
 * @see https://github.com/ludohenin/gulp-inline-ng2-template
 * @see https://github.com/sass/node-sass
 */
function compileSass(path, ext, file, callback) {
  let compiledCss = sass.renderSync({
    data: file,
    outputStyle: 'compressed',
  });
  callback(null, compiledCss.css);
}
<commit_msg>fix(build): allow empty SCSS files and imports inside SCSS<commit_after>const gulp = require('gulp');
const sass = require('node-sass');
const inlineTemplates = require('gulp-inline-ng2-template');
const exec = require('child_process').exec;

/**
 * Inline templates configuration.
 * @see  https://github.com/ludohenin/gulp-inline-ng2-template
 */
const INLINE_TEMPLATES = {
  SRC: './src/**/*.ts',
  DIST: './tmp/src-inlined',
  CONFIG: {
    base: '/src',
    target: 'es6',
    useRelativePaths: true,
    styleProcessor: compileSass
  }
};

/**
 * Inline external HTML and SCSS templates into Angular component files.
 * @see: https://github.com/ludohenin/gulp-inline-ng2-template
 */
gulp.task('inline-templates', () => {
  return gulp.src(INLINE_TEMPLATES.SRC)
    .pipe(inlineTemplates(INLINE_TEMPLATES.CONFIG))
    .pipe(gulp.dest(INLINE_TEMPLATES.DIST));
});

/**
 * Build ESM by running npm task.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm', ['inline-templates'], (callback) => {
  exec('npm run ngcompile', function (error, stdout, stderr) {
    console.log(stdout, stderr);
    callback(error)
  });
});

/**
 * Implements ESM build watch mode.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm:watch', ['build:esm'], () => {
  gulp.watch('src/**/*', ['build:esm']);
});

/**
 * Compile SASS to CSS.
 * @see https://github.com/ludohenin/gulp-inline-ng2-template
 * @see https://github.com/sass/node-sass
 */
function compileSass(path, ext, file, callback) {
  let compiledCss = sass.renderSync({
    file: path,
    outputStyle: 'compressed',
  });
  callback(null, compiledCss.css);
}
<|endoftext|>


<commit_before>/*
 * gulp-stubby-server
 * https://github.com/felixzapata/gulp-stubby-server
 *
 * Copyright (c) 2014 Felix Zapata
 * Licensed under the MIT license.
 */

'use strict';

var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    stubby = require('./index.js'),
    nodeunit = require('gulp-nodeunit');

gulp.task('jshint', function() {
    var options = {
        jshintrc: '.jshintrc'
    };
    return gulp.src([
            'gulpfile.js',
            'tasks/*.js',
            '<%= nodeunit.tests %>'
        ])
        .pipe(jshint(options));
});

gulp.task('stubby', function(cb) {
    var options = {
        stubs: 8000,
        tls: 8443,
        admin: 8001,
        persistent: false,
        files: [
            'test/fixtures/cities.yml',
            'test/fixtures/localities.yaml',
            'test/fixtures/places.json',
            'test/fixtures/towns.js',
            'test/fixtures/users.json',
            'test/fixtures/*.{json,yaml,yml,js}'
        ]
    };
    return stubby(options, cb);
});

gulp.task('nodeunit', ['stubby'], function() {
    return gulp.src('test/test.js').pipe(nodeunit()).on('end', function() {
        process.nextTick(function() {
            process.exit(0);
        });
    });
});
<commit_msg>feat(jshint): activate jshint before stubby<commit_after>/*
 * gulp-stubby-server
 * https://github.com/felixzapata/gulp-stubby-server
 *
 * Copyright (c) 2014 Felix Zapata
 * Licensed under the MIT license.
 */

'use strict';

var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    stubby = require('./index.js'),
    nodeunit = require('gulp-nodeunit');

gulp.task('jshint', function() {
    var options = {
        jshintrc: '.jshintrc'
    };
    return gulp.src([
            'gulpfile.js',
            'index.js',
            'test/test.js'
        ])
        .pipe(jshint(options));
});

gulp.task('stubby', ['jshint'], function(cb) {
    var options = {
        stubs: 8000,
        tls: 8443,
        admin: 8001,
        persistent: false,
        files: [
            'test/fixtures/cities.yml',
            'test/fixtures/localities.yaml',
            'test/fixtures/places.json',
            'test/fixtures/towns.js',
            'test/fixtures/users.json',
            'test/fixtures/*.{json,yaml,yml,js}'
        ]
    };
    return stubby(options, cb);
});

gulp.task('nodeunit', ['stubby'], function() {
    return gulp.src('test/test.js').pipe(nodeunit()).on('end', function() {
        process.nextTick(function() {
            process.exit(0);
        });
    });
});
<|endoftext|>


<commit_before>/* vim: set filetype=javascript shiftwidth=4 tabstop=4 expandtab: */
"use strict";

var gulp = require("gulp");
var sass = require("gulp-sass");
var browserify = require("browserify");
var espowerify = require("espowerify");
var transform = require("vinyl-transform");
var exorcist = require("exorcist");

var argv = require("yargs").argv;

var isRelease = argv.release

var SRC_JS = "./script/main.js";
var SRC_CSS = "./style/main.scss";
var DIST_BUILD_DIR = "./build/";
var DIST_JS_MAP_FILE = DIST_BUILD_DIR + "main.js.map";

var SRC_TEST = "./test/manifest.js";
var DIST_TEST_DIR = "./powered-test/";

gulp.task("css", function() {
    var option = {
        errLogToConsole: true,
        // sourcemap
        sourceComments: isRelease ? "none" : "map",
        // "expanded" are not supported currently by libsass
        outputStyle: "expanded",
    };

    gulp.src(SRC_CSS)
        .pipe(sass(option))
        .pipe(gulp.dest(DIST_BUILD_DIR));
});

gulp.task("js", function() {
    var option = {
        insertGlobals: false,
        debug: isRelease ? false : true,
    };

    var browserifier = transform(function(filename){
        var b = browserify(option).add(filename)
        return b.bundle();
    });

    gulp.src(SRC_JS)
        .pipe(browserifier)
        .pipe(exorcister)
        .pipe(gulp.dest(DIST_BUILD_DIR));
});

gulp.task("espower", function() {
    var option = {
        insertGlobals : false,
        debug : true,
    };

    var browserifier = transform(function(filename){
        var b = browserify(option).add(filename)
                                  .transform(espowerify);
        return b.bundle();
    });

    gulp.src(SRC_TEST)
        .pipe(browserifier)
        .pipe(gulp.dest(DIST_TEST_DIR));
});

gulp.task("jstest", ["espower"], function() {});
gulp.task("build", ["css", "js"], function() {});

// Split sourcemap into the file.
var exorcister = transform(function(){
    return exorcist(DIST_JS_MAP_FILE);
});
<commit_msg>Split css sourcemap into the separated file.<commit_after>/* vim: set filetype=javascript shiftwidth=4 tabstop=4 expandtab: */
"use strict";

var gulp = require("gulp");
var sass = require("gulp-sass");
var browserify = require("browserify");
var espowerify = require("espowerify");
var transform = require("vinyl-transform");
var exorcist = require("exorcist"); // Split sourcemap into the file.

var argv = require("yargs").argv;

var isRelease = argv.release

var SRC_JS = "./script/main.js";
var SRC_CSS = "./style/main.scss";
var DIST_BUILD_DIR = "./build/";
var DIST_JS_MAP_FILE = DIST_BUILD_DIR + "main.js.map";
var DIST_CSS_MAP_FILE = DIST_BUILD_DIR + "main.scss.map";

var SRC_TEST = "./test/manifest.js";
var DIST_TEST_DIR = "./powered-test/";

gulp.task("css", function() {
    var option = {
        errLogToConsole: true,
        // sourcemap
        sourceComments: isRelease ? "none" : "map",
        // "expanded" are not supported currently by libsass
        outputStyle: "expanded",
    };

    var exorcister = transform(function(){
        return exorcist(DIST_CSS_MAP_FILE);
    });

    gulp.src(SRC_CSS)
        .pipe(sass(option))
        .pipe(exorcister)
        .pipe(gulp.dest(DIST_BUILD_DIR));
});

gulp.task("js", function() {
    var option = {
        insertGlobals: false,
        debug: isRelease ? false : true,
    };

    var browserifier = transform(function(filename){
        var b = browserify(option).add(filename)
        return b.bundle();
    });

    var exorcister = transform(function(){
        return exorcist(DIST_JS_MAP_FILE);
    });

    gulp.src(SRC_JS)
        .pipe(browserifier)
        .pipe(exorcister)
        .pipe(gulp.dest(DIST_BUILD_DIR));
});

gulp.task("espower", function() {
    var option = {
        insertGlobals : false,
        debug : true,
    };

    var browserifier = transform(function(filename){
        var b = browserify(option).add(filename)
                                  .transform(espowerify);
        return b.bundle();
    });

    gulp.src(SRC_TEST)
        .pipe(browserifier)
        .pipe(gulp.dest(DIST_TEST_DIR));
});

gulp.task("jstest", ["espower"], function() {});
gulp.task("build", ["css", "js"], function() {});
<|endoftext|>