<commit_before>var app = require('../app.js').app;
var request = require('supertest')(app);
var assert = require('assert');
var csv = require('csv');
var _ = require('underscore');

var data_url = 'https://raw.github.com/okfn/datapipes/master/test/data/gla.csv';

// some facts about our data
var num_rows = 100;
var num_cols = 8;
var num_blank_rows = 1;
var num_london_rows = 15; // rows containing the word LONDON

describe('GET /', function(){
  it('should respond with html', function(done){
    request
      .get('/')
      .expect('Content-Type', /html/)
      .expect(200, done);
  });
});

describe('Docs', function(){
  ops = ['none', 'head', 'cut', 'delete', 'grep', 'strip', 'html'];
  _.each(ops, function(op) {
    var url = '/' + op;
    describe('GET ' + url, function(){
      it('should respond with html', function(done){
        request
          .get(url)
          .expect('Content-Type', /html/)
          .expect(200, done);
      });
    });
  });
});

describe('none op', function(){
  var url = '/csv/none/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return csv with ' + num_rows + ' rows and ' + num_cols + ' columns (original file)', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, num_cols);
            })
            .on('end', function(count) {
              assert.equal(count, num_rows);
              done();
            })
          ;
        });
    });
  });
});

describe('head op', function(){
  var url = '/csv/head/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return 10 csv rows', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, 10);
              done();
            })
          ;
        });
    });
  });

  var num_rows_head = 5;
  var url2 = '/csv/head -n ' + num_rows_head + '/?url=' + data_url;
  describe('GET ' + url2, function(){
    it('should return ' + num_rows_head + ' csv rows', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, num_rows_head);
              done();
            })
          ;
        });
    });
  });
});

describe('tail op', function(){
  var url = '/csv/tail/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return 10 csv rows', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, 10);
              done();
            })
          ;
        });
    });
  });

  var num_rows_tail = 5;
  var url2 = '/csv/tail -n ' + num_rows_tail + '/?url=' + data_url;
  describe('GET ' + url2, function(){
    it('should return ' + num_rows_tail + ' csv rows', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, num_rows_tail);
              done();
            })
          ;
        });
    });
  });

  var url3 = '/csv/tail -n +' + num_rows_tail + '/?url=' + data_url;
  describe('GET ' + url3, function(){
    it('should return ' + (num_rows - num_rows_tail) + ' csv rows', function(done){
      request
        .get(url3)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_tail));
              done();
            })
          ;
        });
    });
  });
});

describe('cut op', function(){
  var url = '/csv/cut 0,3/?url=' + data_url;
  describe('GET ' + url, function(){
    var num_cols_removed = 2;
    it('should return csv with ' + (num_cols - num_cols_removed) + ' columns (' + num_cols_removed + ' removed)', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, (num_cols - num_cols_removed));
            })
            .on('end', function(count) {
              done();
            })
          ;
        });
    });
  });

  var url2 = '/csv/cut 0,2-4/?url=' + data_url;
  describe('GET ' + url2, function(){
    var num_cols_removed = 4;
    it('should return csv with ' + (num_cols - num_cols_removed) + ' columns (' + num_cols_removed + ' removed)', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, (num_cols - num_cols_removed));
            })
            .on('end', function(count) {
              done();
            })
          ;
        });
    });
  });

  var url3 = '/csv/cut 0,2-4 --complement/?url=' + data_url;
  describe('GET ' + url2, function(){
    var num_cols_kept = 4;
    it('should return csv with ' + num_cols_kept + ' columns', function(done){
      request
        .get(url3)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, num_cols_kept);
            })
            .on('end', function(count) {
              done();
            })
          ;
        });
    });
  });

  var url4 = '/csv/cut 3/?url=' + data_url;
  describe('GET ' + url, function(){
    var num_cols_removed = 1;
    it('should return csv with ' + (num_cols - num_cols_removed) + ' columns (' + num_cols_removed + ' removed)', function(done){
      request
        .get(url4)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, (num_cols - num_cols_removed));
            })
            .on('end', function(count) {
              done();
            })
          ;
        });
    });
  });
});

describe('delete op', function(){
  var url = '/csv/delete 10,20/?url=' + data_url;
  describe('GET ' + url, function(){
    var num_rows_removed = 2;
    it('should return csv with ' + (num_rows - num_rows_removed) + ' rows (' + num_rows_removed + ' removed)', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_removed));
              done();
            })
          ;
        });
    });
  });

  var url2 = '/csv/delete 1,10:20/?url=' + data_url;
  describe('GET ' + url2, function(){
    var num_rows_removed = 12;
    it('should return csv with ' + (num_rows - num_rows_removed) + ' rows (' + num_rows_removed + ' removed)', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_removed));
              done();
            })
          ;
        });
    });
  });

  var url3 = '/csv/delete 10/?url=' + data_url;
  describe('GET ' + url3, function(){
    var num_rows_removed = 1;
    it('should return csv with ' + (num_rows - num_rows_removed) + ' rows (' + num_rows_removed + ' removed)', function(done){
      request
        .get(url3)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_removed));
              done();
            })
          ;
        });
    });
  });
});

describe('grep op', function(){
  var url = '/csv/grep LONDON/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return csv with ' + (num_london_rows + 1) + ' rows (1 header plus ' + num_london_rows + ' containing the word "LONDON")', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              if (index === 0) {
                // skip the header row
                return;
              }
              var contains_london = _.some(row, function(val) {
                return val.indexOf('LONDON') != -1;
              });
              assert.equal(contains_london, true);
            })
            .on('end', function(count) {
              assert.equal(count, (num_london_rows + 1));
              done();
            })
          ;
        });
    });
  });
});

describe('strip op', function(){
  var url = '/csv/strip/?url=' + data_url;
  var num_non_blank = num_rows - num_blank_rows;
  describe('GET ' + url, function(){
    it('should return ' + num_non_blank + ' csv rows, none of which are empty', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              var emptyRow = _.every(row, function(val) {
                return val === '';
              });
              assert.notEqual(emptyRow, true);
            })
            .on('end', function(count) {
              assert.equal(count, num_non_blank);
              done();
            })
          ;
        });
    });
  });
});

describe('html op', function(){
  var num_rows_head = 5;
  var url = '/csv/head -n ' + num_rows_head + '/html/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return ' + num_rows_head + ' html rows', function(done){
      request
        .get(url)
        .expect('Content-Type', /html/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          var out = res.text;
          var numRows = out.match(/<tr/g).length;
          assert.equal(numRows, num_rows_head);

          done();
        });
    });
  });
});
<commit_msg>Minor code styling tweak<commit_after>var app = require('../app.js').app;
var request = require('supertest')(app);
var assert = require('assert');
var csv = require('csv');
var _ = require('underscore');

var data_url = 'https://raw.github.com/okfn/datapipes/master/test/data/gla.csv';

// some facts about our data
var num_rows = 100;
var num_cols = 8;
var num_blank_rows = 1;
var num_london_rows = 15; // rows containing the word LONDON

describe('GET /', function(){
  it('should respond with html', function(done){
    request
      .get('/')
      .expect('Content-Type', /html/)
      .expect(200, done)
    ;
  });
});

describe('Docs', function(){
  ops = ['none', 'head', 'cut', 'delete', 'grep', 'strip', 'html'];
  _.each(ops, function(op) {
    var url = '/' + op;
    describe('GET ' + url, function(){
      it('should respond with html', function(done){
        request
          .get(url)
          .expect('Content-Type', /html/)
          .expect(200, done)
        ;
      });
    });
  });
});

describe('none op', function(){
  var url = '/csv/none/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return csv with ' + num_rows + ' rows and ' + num_cols + ' columns (original file)', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, num_cols);
            })
            .on('end', function(count) {
              assert.equal(count, num_rows);
              done();
            })
          ;
        })
      ;
    });
  });
});

describe('head op', function(){
  var url = '/csv/head/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return 10 csv rows', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, 10);
              done();
            })
          ;
        })
      ;
    });
  });

  var num_rows_head = 5;
  var url2 = '/csv/head -n ' + num_rows_head + '/?url=' + data_url;
  describe('GET ' + url2, function(){
    it('should return ' + num_rows_head + ' csv rows', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, num_rows_head);
              done();
            })
          ;
        })
      ;
    });
  });
});

describe('tail op', function(){
  var url = '/csv/tail/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return 10 csv rows', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, 10);
              done();
            })
          ;
        })
      ;
    });
  });

  var num_rows_tail = 5;
  var url2 = '/csv/tail -n ' + num_rows_tail + '/?url=' + data_url;
  describe('GET ' + url2, function(){
    it('should return ' + num_rows_tail + ' csv rows', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, num_rows_tail);
              done();
            })
          ;
        })
      ;
    });
  });

  var url3 = '/csv/tail -n +' + num_rows_tail + '/?url=' + data_url;
  describe('GET ' + url3, function(){
    it('should return ' + (num_rows - num_rows_tail) + ' csv rows', function(done){
      request
        .get(url3)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_tail));
              done();
            })
          ;
        })
      ;
    });
  });
});

describe('cut op', function(){
  var url = '/csv/cut 0,3/?url=' + data_url;
  describe('GET ' + url, function(){
    var num_cols_removed = 2;
    it('should return csv with ' + (num_cols - num_cols_removed) + ' columns (' + num_cols_removed + ' removed)', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, (num_cols - num_cols_removed));
            })
            .on('end', function(count) {
              done();
            })
          ;
        })
      ;
    });
  });

  var url2 = '/csv/cut 0,2-4/?url=' + data_url;
  describe('GET ' + url2, function(){
    var num_cols_removed = 4;
    it('should return csv with ' + (num_cols - num_cols_removed) + ' columns (' + num_cols_removed + ' removed)', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, (num_cols - num_cols_removed));
            })
            .on('end', function(count) {
              done();
            })
          ;
        })
      ;
    });
  });

  var url3 = '/csv/cut 0,2-4 --complement/?url=' + data_url;
  describe('GET ' + url2, function(){
    var num_cols_kept = 4;
    it('should return csv with ' + num_cols_kept + ' columns', function(done){
      request
        .get(url3)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, num_cols_kept);
            })
            .on('end', function(count) {
              done();
            })
          ;
        });
    });
  });

  var url4 = '/csv/cut 3/?url=' + data_url;
  describe('GET ' + url, function(){
    var num_cols_removed = 1;
    it('should return csv with ' + (num_cols - num_cols_removed) + ' columns (' + num_cols_removed + ' removed)', function(done){
      request
        .get(url4)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              assert.equal(row.length, (num_cols - num_cols_removed));
            })
            .on('end', function(count) {
              done();
            })
          ;
        });
    });
  });
});

describe('delete op', function(){
  var url = '/csv/delete 10,20/?url=' + data_url;
  describe('GET ' + url, function(){
    var num_rows_removed = 2;
    it('should return csv with ' + (num_rows - num_rows_removed) + ' rows (' + num_rows_removed + ' removed)', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_removed));
              done();
            })
          ;
        })
      ;
    });
  });

  var url2 = '/csv/delete 1,10:20/?url=' + data_url;
  describe('GET ' + url2, function(){
    var num_rows_removed = 12;
    it('should return csv with ' + (num_rows - num_rows_removed) + ' rows (' + num_rows_removed + ' removed)', function(done){
      request
        .get(url2)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_removed));
              done();
            })
          ;
        })
      ;
    });
  });

  var url3 = '/csv/delete 10/?url=' + data_url;
  describe('GET ' + url3, function(){
    var num_rows_removed = 1;
    it('should return csv with ' + (num_rows - num_rows_removed) + ' rows (' + num_rows_removed + ' removed)', function(done){
      request
        .get(url3)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('end', function(count) {
              assert.equal(count, (num_rows - num_rows_removed));
              done();
            })
          ;
        });
    });
  });
});

describe('grep op', function(){
  var url = '/csv/grep LONDON/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return csv with ' + (num_london_rows + 1) + ' rows (1 header plus ' + num_london_rows + ' containing the word "LONDON")', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              if (index === 0) {
                // skip the header row
                return;
              }
              var contains_london = _.some(row, function(val) {
                return val.indexOf('LONDON') != -1;
              });
              assert.equal(contains_london, true);
            })
            .on('end', function(count) {
              assert.equal(count, (num_london_rows + 1));
              done();
            })
          ;
        })
      ;
    });
  });
});

describe('strip op', function(){
  var url = '/csv/strip/?url=' + data_url;
  var num_non_blank = num_rows - num_blank_rows;
  describe('GET ' + url, function(){
    it('should return ' + num_non_blank + ' csv rows, none of which are empty', function(done){
      request
        .get(url)
        .expect('Content-Type', /plain/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          csv()
            .from.string(res.text)
            .on('record', function(row,index){
              var emptyRow = _.every(row, function(val) {
                return val === '';
              });
              assert.notEqual(emptyRow, true);
            })
            .on('end', function(count) {
              assert.equal(count, num_non_blank);
              done();
            })
          ;
        });
    });
  });
});

describe('html op', function(){
  var num_rows_head = 5;
  var url = '/csv/head -n ' + num_rows_head + '/html/?url=' + data_url;
  describe('GET ' + url, function(){
    it('should return ' + num_rows_head + ' html rows', function(done){
      request
        .get(url)
        .expect('Content-Type', /html/)
        .expect(200)
        .end(function(err, res) {
          if (err) done(err);

          var out = res.text;
          var numRows = out.match(/<tr/g).length;
          assert.equal(numRows, num_rows_head);

          done();
        })
      ;
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var mlMatrix = require('ml-matrix');
var padArray = _interopDefault(require('ml-pad-array'));

const defaultOptions = {
  windowSize: 5,
  derivative: 1,
  polynomial: 2,
  pad: 'none',
  padValue: 'replicate'
};

/**
 * Savitzky-Golay filter
 * @param {Array <number>} data
 * @param {number} h
 * @param {Object} options
 * @returns {Array}
 */
function SavitzkyGolay(data, h, options) {
  options = Object.assign({}, defaultOptions, options);
  if (
    options.windowSize % 2 === 0 ||
    options.windowSize < 5 ||
    !Number.isInteger(options.windowSize)
  ) {
    throw new RangeError(
      'Invalid window size (should be odd and at least 5 integer number)'
    );
  }
  if (options.derivative < 0 || !Number.isInteger(options.derivative)) {
    throw new RangeError('Derivative should be a positive integer');
  }
  if (options.polynomial < 1 || !Number.isInteger(options.polynomial)) {
    throw new RangeError('Polynomial should be a positive integer');
  }

  var C, norm;
  var step = Math.floor(options.windowSize / 2);

  if (options.pad === 'pre') {
    data = padArray(data, { size: step, value: options.padValue });
  }

  var ans = new Array(data.length - 2 * step);

  if (
    options.windowSize === 5 &&
    options.polynomial === 2 &&
    (options.derivative === 1 || options.derivative === 2)
  ) {
    if (options.derivative === 1) {
      C = [-2, -1, 0, 1, 2];
      norm = 10;
    } else {
      C = [2, -1, -2, -1, 2];
      norm = 7;
    }
  } else {
    var J = mlMatrix.Matrix.ones(options.windowSize, options.polynomial + 1);
    var inic = -(options.windowSize - 1) / 2;
    for (var i = 0; i < J.rows; i++) {
      for (var j = 0; j < J.columns; j++) {
        if (inic + 1 !== 0 || j !== 0) J.set(i, j, Math.pow(inic + i, j));
      }
    }
    var Jtranspose = new mlMatrix.MatrixTransposeView(J);
    var Jinv = mlMatrix.inverse(Jtranspose.mmul(J));
    C = Jinv.mmul(Jtranspose);
    C = C.getRow(options.derivative);
    norm = 1;
  }
  var det = norm * Math.pow(h, options.derivative);
  for (var k = step; k < data.length - step; k++) {
    var d = 0;
    for (var l = 0; l < C.length; l++) d += (C[l] * data[l + k - step]) / det;
    ans[k - step] = d;
  }

  if (options.pad === 'post') {
    ans = padArray(ans, { size: step, value: options.padValue });
  }

  return ans;
}

module.exports = SavitzkyGolay;
<commit_msg>chore: remove lib/index.js<commit_after><|endoftext|>


<commit_before>'use strict';
var chai = require('chai');
chai.Assertion.includeStack = true;
require('chai').should();
var expect = require('chai').expect;
var nodePath = require('path');
var fs = require('fs');

describe('raptor-render-context' , function() {

    beforeEach(function(done) {
        // for (var k in require.cache) {
        //     if (require.cache.hasOwnProperty(k)) {
        //         delete require.cache[k];
        //     }
        // }

        done();
    });

    it('should render a series of sync calls correctly', function(done) {
        var context = require('../').create();
        context.write('1');
        context.write('2');
        context.write('3');
        context.write('4');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('1234');
            done();
        });
    });

    it('should render a series of sync and async calls correctly', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext1 = context.beginAsync();
        setTimeout(function() {
            asyncContext1.write('2');
            asyncContext1.end();
        }, 100);

        context.write('3');

        var asyncContext2 = context.beginAsync();
        setTimeout(function() {
            asyncContext2.write('4');
            asyncContext2.end();
        }, 10);

        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('1234');
            done();
        });
    });

    it('should allow an async fragment to complete synchronously', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 10);

        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });

    it('should allow the async callback to provide data', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.end('2');
        }, 10);

        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });

    it('should handle timeouts correctly', function(done) {
        var context = require('../').create();
        var errors = [];
        context.on('error', function(e) {
            errors.push(e);
        });

        context.write('1');

        var asyncContext = context.beginAsync(100);
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 200);

        context.write('3');
        context.end();

        context.on('end', function() {
            expect(errors.length).to.equal(1);
            expect(context.getOutput()).to.equal('13');
            done();
        });
    });

    it('should render nested async calls correctly', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2a');

            var nestedAsyncContext = asyncContext.beginAsync();
            setTimeout(function() {
                nestedAsyncContext.write('2b');
                nestedAsyncContext.end();
            }, 10);

            asyncContext.write('2c');
            asyncContext.end();
        }, 10);

        context.write('3');

        var asyncContext2 = context.beginAsync();
        setTimeout(function() {
            var nestedAsyncContext = asyncContext2.beginAsync();
            setTimeout(function() {
                nestedAsyncContext.write('4a');
                nestedAsyncContext.end();
            }, 10);

            var nestedAsyncContext2 = asyncContext2.beginAsync();
            setTimeout(function() {
                nestedAsyncContext2.write('4b');
                nestedAsyncContext2.end();
            }, 10);

            asyncContext2.write('4c');
            asyncContext2.end();
        }, 10);

        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('12a2b2c34a4b4c');
            done();
        });
    });

    it('should handle sync errors correctly', function(done) {
        var context = require('../').create();
        var errors = [];
        context.on('error', function(e) {
            errors.push(e);
        });

        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.error(new Error('test'));
        }, 10);
        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(errors.length).to.equal(1);
            expect(output).to.equal('13');
            done();
        });
    });

    it('should support chaining', function(done) {
        var errors = [];
        var context = require('../').create()
            .on('error', function(e) {
                errors.push(e);
            })
            .on('end', function() {
                var output = context.getOutput();
                expect(errors.length).to.equal(1);
                expect(output).to.equal('13');
                done();
            })
            .write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.error(new Error('test'));
        }, 10);

        context.write('3')
            .end();
    });

    it('should support writing to a through stream', function(done) {

        var output = '';
        var through = require('through')(
            function write(data) {
                output += data;
            }
        );

        var errors = [];
        var context = require('../').create(through)
            .on('error', function(e) {
                errors.push(e);
            })
            .on('end', function() {
                expect(errors.length).to.equal(0);
                expect(output).to.equal('123');
                done();
            })
            .write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 10);

        context.write('3')
            .end();
    });

    it('should support writing to a file output stream', function(done) {

        var outFile = nodePath.join(__dirname, 'test.out');
        var out = fs.createWriteStream(outFile, 'utf8');

        out.on('close', function() {
            var output  = fs.readFileSync(outFile, 'utf8');
            expect(errors.length).to.equal(0);
            expect(output).to.equal('123');
            fs.unlinkSync(outFile);
            done();
        });

        var errors = [];
        var context = require('../').create(out)
            .on('error', function(e) {
                errors.push(e);
            })
            .on('end', function() {
            })
            .write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 10);

        context.write('3')
            .end();
    });

    it('should support piping to an async render context', function(done) {

        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();

        var helloReadStream = fs.createReadStream(nodePath.join(__dirname, 'hello.txt'), 'utf8');
        helloReadStream.pipe(asyncContext);

        context.write('2');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('1Hello World2');
            done();
        });
    });

    it.only('should support a render context being piped to another stream', function(done) {

        var through = require('through')();
        var outStr = '';

        var out = require('through')(
            function write(str) {
                outStr += str;
            }
        );

        through
            .pipe(out)
            .on('end', function() {
                expect(outStr).to.equal('1Hello World2');
                done();
            })
            .on('error', function(e) {
                done(e);
            });

        var context = require('../').create(through);
        context.write('1');

        var asyncContext = context.beginAsync();

        var helloReadStream = fs.createReadStream(nodePath.join(__dirname, 'hello.txt'), 'utf8');
        helloReadStream.pipe(asyncContext);

        context.write('2');
        context.end();

    });

    it('should allow an async fragment to flush last', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync({last: true});
        context.once('last', function() {
            asyncContext.write('2');
            asyncContext.end();
        });

        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });

    it('should allow an async fragment to flush last asynchronously', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync({last: true});
        context.on('last', function() {
            lastFiredCount++;
        });

        context.once('last', function() {
            setTimeout(function() {
                asyncContext.write('2');
                asyncContext.end();
            }, 10);
        });

        var lastFiredCount = 0;

        context.write('3');
        context.end();
        context.on('end', function() {
            expect(lastFiredCount).to.equal(1);
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });
});

<commit_msg>Make sure all tests run<commit_after>'use strict';
var chai = require('chai');
chai.Assertion.includeStack = true;
require('chai').should();
var expect = require('chai').expect;
var nodePath = require('path');
var fs = require('fs');

describe('raptor-render-context' , function() {

    beforeEach(function(done) {
        // for (var k in require.cache) {
        //     if (require.cache.hasOwnProperty(k)) {
        //         delete require.cache[k];
        //     }
        // }

        done();
    });

    it('should render a series of sync calls correctly', function(done) {
        var context = require('../').create();
        context.write('1');
        context.write('2');
        context.write('3');
        context.write('4');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('1234');
            done();
        });
    });

    it('should render a series of sync and async calls correctly', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext1 = context.beginAsync();
        setTimeout(function() {
            asyncContext1.write('2');
            asyncContext1.end();
        }, 100);

        context.write('3');

        var asyncContext2 = context.beginAsync();
        setTimeout(function() {
            asyncContext2.write('4');
            asyncContext2.end();
        }, 10);

        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('1234');
            done();
        });
    });

    it('should allow an async fragment to complete synchronously', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 10);

        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });

    it('should allow the async callback to provide data', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.end('2');
        }, 10);

        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });

    it('should handle timeouts correctly', function(done) {
        var context = require('../').create();
        var errors = [];
        context.on('error', function(e) {
            errors.push(e);
        });

        context.write('1');

        var asyncContext = context.beginAsync(100);
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 200);

        context.write('3');
        context.end();

        context.on('end', function() {
            expect(errors.length).to.equal(1);
            expect(context.getOutput()).to.equal('13');
            done();
        });
    });

    it('should render nested async calls correctly', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2a');

            var nestedAsyncContext = asyncContext.beginAsync();
            setTimeout(function() {
                nestedAsyncContext.write('2b');
                nestedAsyncContext.end();
            }, 10);

            asyncContext.write('2c');
            asyncContext.end();
        }, 10);

        context.write('3');

        var asyncContext2 = context.beginAsync();
        setTimeout(function() {
            var nestedAsyncContext = asyncContext2.beginAsync();
            setTimeout(function() {
                nestedAsyncContext.write('4a');
                nestedAsyncContext.end();
            }, 10);

            var nestedAsyncContext2 = asyncContext2.beginAsync();
            setTimeout(function() {
                nestedAsyncContext2.write('4b');
                nestedAsyncContext2.end();
            }, 10);

            asyncContext2.write('4c');
            asyncContext2.end();
        }, 10);

        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('12a2b2c34a4b4c');
            done();
        });
    });

    it('should handle sync errors correctly', function(done) {
        var context = require('../').create();
        var errors = [];
        context.on('error', function(e) {
            errors.push(e);
        });

        context.write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.error(new Error('test'));
        }, 10);
        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(errors.length).to.equal(1);
            expect(output).to.equal('13');
            done();
        });
    });

    it('should support chaining', function(done) {
        var errors = [];
        var context = require('../').create()
            .on('error', function(e) {
                errors.push(e);
            })
            .on('end', function() {
                var output = context.getOutput();
                expect(errors.length).to.equal(1);
                expect(output).to.equal('13');
                done();
            })
            .write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.error(new Error('test'));
        }, 10);

        context.write('3')
            .end();
    });

    it('should support writing to a through stream', function(done) {

        var output = '';
        var through = require('through')(
            function write(data) {
                output += data;
            }
        );

        var errors = [];
        var context = require('../').create(through)
            .on('error', function(e) {
                errors.push(e);
            })
            .on('end', function() {
                expect(errors.length).to.equal(0);
                expect(output).to.equal('123');
                done();
            })
            .write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 10);

        context.write('3')
            .end();
    });

    it('should support writing to a file output stream', function(done) {

        var outFile = nodePath.join(__dirname, 'test.out');
        var out = fs.createWriteStream(outFile, 'utf8');

        out.on('close', function() {
            var output  = fs.readFileSync(outFile, 'utf8');
            expect(errors.length).to.equal(0);
            expect(output).to.equal('123');
            fs.unlinkSync(outFile);
            done();
        });

        var errors = [];
        var context = require('../').create(out)
            .on('error', function(e) {
                errors.push(e);
            })
            .on('end', function() {
            })
            .write('1');

        var asyncContext = context.beginAsync();
        setTimeout(function() {
            asyncContext.write('2');
            asyncContext.end();
        }, 10);

        context.write('3')
            .end();
    });

    it('should support piping to an async render context', function(done) {

        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync();

        var helloReadStream = fs.createReadStream(nodePath.join(__dirname, 'hello.txt'), 'utf8');
        helloReadStream.pipe(asyncContext);

        context.write('2');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('1Hello World2');
            done();
        });
    });

    it('should support a render context being piped to another stream', function(done) {

        var through = require('through')();
        var outStr = '';

        var out = require('through')(
            function write(str) {
                outStr += str;
            }
        );

        through
            .pipe(out)
            .on('end', function() {
                expect(outStr).to.equal('1Hello World2');
                done();
            })
            .on('error', function(e) {
                done(e);
            });

        var context = require('../').create(through);
        context.write('1');

        var asyncContext = context.beginAsync();

        var helloReadStream = fs.createReadStream(nodePath.join(__dirname, 'hello.txt'), 'utf8');
        helloReadStream.pipe(asyncContext);

        context.write('2');
        context.end();

    });

    it('should allow an async fragment to flush last', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync({last: true});
        context.once('last', function() {
            asyncContext.write('2');
            asyncContext.end();
        });

        context.write('3');
        context.end();
        context.on('end', function() {
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });

    it('should allow an async fragment to flush last asynchronously', function(done) {
        var context = require('../').create();
        context.write('1');

        var asyncContext = context.beginAsync({last: true});
        context.on('last', function() {
            lastFiredCount++;
        });

        context.once('last', function() {
            setTimeout(function() {
                asyncContext.write('2');
                asyncContext.end();
            }, 10);
        });

        var lastFiredCount = 0;

        context.write('3');
        context.end();
        context.on('end', function() {
            expect(lastFiredCount).to.equal(1);
            var output = context.getOutput();
            expect(output).to.equal('123');
            done();
        });
    });
});

<|endoftext|>


<commit_before>/**
 * ///////////////////////////////////////
 * ////////// Middleware chain  //////////
 * ///////////////////////////////////////
 *
 * This module exposes the interface of
 * the middleware chain.
 */

/**
 * Exporting the `Chain` module appropriately given
 * the environment (AMD, Node.js and the browser).
 */
(function (name, definition) {
  if (typeof define === 'function' && define.amd) {
    define(['lodash'], definition);
  } else if (typeof module !== 'undefined' && module.exports) {
    module.exports = definition(require('lodash'));
  } else {
    var global = this;
    var instance = definition(global._);
    var old = global[name];

    /**
     * Allowing to scope the module
     * avoiding global namespace pollution.
     */
    instance.noConflict = function () {
      global[name] = old;
      return instance;
    };
    // Exporting the module in the global
    // namespace in a browser context.
    global[name] = instance;
  }
})('Chain', function (_) {

  /**
   * The chain constructor.
   * @constructor
   */
  var Chain = function () {
    this.chain = [];
    this.errorChain = [];
  };

  /**
   * Pushes a function to the associated
   * array given its arity.
   * @param f the function to push
   */
  var push = function (f) {
    if (f.length === 4) {
      this.errorChain.push(f);
    } else {
      this.chain.push(f);
    }
  };

  /**
   * Pushes a middleware, or a collection of
   * middleware into the chain.
   * @returns {Chain}
   */
  Chain.prototype.use = function () {
    var self = this;

    _.each(arguments, function (f) {
      if (_.isFunction(f)) {
        push.call(self, f);
      } else if (_.isArray(f)) {
        _.each(f, function (value) {
          push.call(self, value);
        });
      }
    });
    return (this);
  };

  /**
   * Triggers a new treatment to be processed by
   * the chain.
   * @param input
   * @param output
   */
  Chain.prototype.handle = function (input, output) {
    var index = 0;
    var errIndex = 0;
    var chain = this.chain;

    var callback = function (chain, value) {
      var nextFunction;
      if (chain === this.chain) {
        if (!!(nextFunction = chain[index++])) {
          nextFunction(input, output, next);
        }
      } else if (chain === this.errorChain) {
        if (!!(nextFunction = chain[errIndex++])) {
          nextFunction(value, input, output, next);
        }
      }
    }.bind(this);

    var next = function (value) {
      if (value instanceof Error) {
        chain = this.errorChain;
      }
      callback(chain, value);
    }.bind(this);

    next();
  };

  return (Chain);
});
<commit_msg>Ignoring UMD wrapper for code coverage<commit_after>/**
 * ///////////////////////////////////////
 * ////////// Middleware chain  //////////
 * ///////////////////////////////////////
 *
 * This module exposes the interface of
 * the middleware chain.
 */

/**
 * Exporting the `Chain` module appropriately given
 * the environment (AMD, Node.js and the browser).
 */
(function (name, definition) {
  /* istanbul ignore next */
  if (typeof define === 'function' && define.amd) {
    define(['lodash'], definition);
  } else if (typeof module !== 'undefined' && module.exports) {
    module.exports = definition(require('lodash'));
  } else {
    var global = this;
    var instance = definition(global._);
    var old = global[name];

    /**
     * Allowing to scope the module
     * avoiding global namespace pollution.
     */
    instance.noConflict = function () {
      global[name] = old;
      return instance;
    };
    // Exporting the module in the global
    // namespace in a browser context.
    global[name] = instance;
  }
})('Chain', function (_) {

  /**
   * The chain constructor.
   * @constructor
   */
  var Chain = function () {
    this.chain = [];
    this.errorChain = [];
  };

  /**
   * Pushes a function to the associated
   * array given its arity.
   * @param f the function to push
   */
  var push = function (f) {
    if (f.length === 4) {
      this.errorChain.push(f);
    } else {
      this.chain.push(f);
    }
  };

  /**
   * Pushes a middleware, or a collection of
   * middleware into the chain.
   * @returns {Chain}
   */
  Chain.prototype.use = function () {
    var self = this;

    _.each(arguments, function (f) {
      if (_.isFunction(f)) {
        push.call(self, f);
      } else if (_.isArray(f)) {
        _.each(f, function (value) {
          push.call(self, value);
        });
      }
    });
    return (this);
  };

  /**
   * Triggers a new treatment to be processed by
   * the chain.
   * @param input
   * @param output
   */
  Chain.prototype.handle = function (input, output) {
    var index = 0;
    var errIndex = 0;
    var chain = this.chain;

    var callback = function (chain, value) {
      var nextFunction;
      if (chain === this.chain) {
        if (!!(nextFunction = chain[index++])) {
          nextFunction(input, output, next);
        }
      } else if (chain === this.errorChain) {
        if (!!(nextFunction = chain[errIndex++])) {
          nextFunction(value, input, output, next);
        }
      }
    }.bind(this);

    var next = function (value) {
      if (value instanceof Error) {
        chain = this.errorChain;
      }
      callback(chain, value);
    }.bind(this);

    next();
  };

  return (Chain);
});
<|endoftext|>


<commit_before>/* eslint global-require: 0, consistent-return: 0 */

const Filter = require('broccoli-persistent-filter');
const CLIEngine = require('eslint').CLIEngine;
const md5Hex = require('md5-hex');
const stringify = require('json-stable-stringify');
const path = require('path');
const escapeStringRegexp = require('escape-string-regexp');
const BUILD_DIR_REGEXP = new RegExp('(' + escapeStringRegexp(path.sep) + ')?build(' + escapeStringRegexp(path.sep) + ')?$');
const IGNORED_FILE_MESSAGE_REGEXP = /(?:File ignored by default\.)|(?:File ignored because of a matching ignore pattern\.)/;

/**
 * Calculates the severity of a eslint.linter.verify result
 * @param {Array} result ESLint's verify() result array
 *    @see: http://eslint.org/docs/developer-guide/nodejs-api#linter
 *
 * @returns {Number} accumulatedSeverity The total severity from of the list of results
 *    0 indicates all-clear
 *    1 indicates a warning-level result
 *    > 1 indicates an error-level result
 */
function getResultSeverity(resultMessages = []) {
  return resultMessages.reduce((accumulatedSeverity, message) => {
    const severity = message.severity || 0;

    if (message.fatal || severity === 2) {
      return accumulatedSeverity + 2;
    }

    return accumulatedSeverity + severity;
  }, 0);
}

/**
 * Ignores messages that are about ignored files as they are intended
 * but we are processing a file at a time
 *
 * @param {Array} errors result errors
 * @returns {Array} filtered errors
 */
function filterIgnoredFileMessages(errors) {
  return errors.filter((error) => !IGNORED_FILE_MESSAGE_REGEXP.test(error.message));
}

/**
 * Filters all ignored file messages from result object
 * @param {Object} result result errors
 * @returns {Object} filtered results
 */
function filterAllIgnoredFileMessages(result) {
  const resultOutput = result;

  resultOutput.results.forEach((resultItem) => {
    resultItem.messages = filterIgnoredFileMessages(resultItem.messages);
  });

  return resultOutput;
}

function isString(x) {
  return toString.call(x) === '[object String]';
}

function resolveInputDirectory(inputNode) {
  if (typeof inputNode === 'string') {
    return inputNode;
  }

  // eslint-disable-next-line no-underscore-dangle
  const nodeInfo = inputNode.__broccoliGetInfo__();

  if (nodeInfo.nodeType === 'source') {
    return nodeInfo.sourceDirectory;
  }

  if (nodeInfo.inputNodes.length > 1) {
    // eslint-disable-next-line max-len
    throw new Error('EslintValidationFilter can only handle one:* broccoli nodes, but part of the given input pipeline is a many:* node. (broccoli-merge-trees is an example of a many:* node) Please perform many:* operations after linting.');
  }

  return resolveInputDirectory(nodeInfo.inputNodes[0]);
}

/**
 * Uses the content of each file in a given node and runs eslint validation on it.
 * @param {Object} inputNode Node from broccoli.makeTree
 * @param {{config: String, rulesdir: String, format: String}} options Filter options
 * @returns {EslintValidationFilter} Filter obconfig @constructor
 */
function EslintValidationFilter(inputNode, options = {}) {
  if (!(this instanceof EslintValidationFilter)) {
    return new EslintValidationFilter(inputNode, options);
  }

  this.internalOptions = options || {};
  const eslintOptions = options.options || {};

  // default ignore:true option
  if (typeof eslintOptions.ignore === 'undefined') {
    eslintOptions.ignore = true;
  }

  // default is to persist filter output
  if (typeof this.internalOptions.persist === 'undefined') {
    this.internalOptions.persist = true;
  }

  // call base class constructor
  Filter.call(this, inputNode, this.internalOptions);

  // set formatter
  if (typeof this.internalOptions.format === 'function') {
    this.formatter = this.internalOptions.format;
  } else {
    // eslint-disable-next-line global-require
    this.formatter = require(this.internalOptions.format || 'eslint/lib/formatters/stylish');
  }

  this.console = options.console || console;

  this.cli = new CLIEngine(eslintOptions);

  this.eslintrc = resolveInputDirectory(inputNode);

  if (isString(this.internalOptions.testGenerator)) {
    const testGenerators = require('./test-generators');

    this.testGenerator = testGenerators[this.internalOptions.testGenerator];
    if (!this.testGenerator) {
      throw new Error(`Could not find '${this.internalOptions.testGenerator}' test generator.`);
    }
  } else {
    this.testGenerator = this.internalOptions.testGenerator;
  }

  if (this.testGenerator) {
    this.targetExtension = 'lint-test.js';
  }
}

module.exports = EslintValidationFilter;
EslintValidationFilter.prototype = Object.create(Filter.prototype);
EslintValidationFilter.prototype.constructor = EslintValidationFilter;
EslintValidationFilter.prototype.extensions = ['js'];
EslintValidationFilter.prototype.targetExtension = 'js';

EslintValidationFilter.prototype.baseDir = function baseDir() {
  return __dirname.replace(BUILD_DIR_REGEXP, '');
};

EslintValidationFilter.prototype.cacheKeyProcessString = function cacheKeyProcessString(content, relativePath) {
  function functionStringifier(key, value) {
    if (typeof value === 'function') {
      return value.toString();
    }
    return value;
  }

  return md5Hex([
    content,
    relativePath,
    stringify(this.internalOptions, { replacer: functionStringifier }),
    stringify(this.cli.getConfigForFile(path.join(this.eslintrc, relativePath)))
  ]);
};

EslintValidationFilter.prototype.processString = function processString(content, relativePath) {
  // verify file content
  const configPath = path.join(this.eslintrc, relativePath);
  const report = this.cli.executeOnText(content, configPath);
  const filteredReport = filterAllIgnoredFileMessages(report);

  const toCache = { report, output: content };

  if (this.testGenerator && Array.isArray(filteredReport.results)) {
    const result = filteredReport.results[0] || {};
    const messages = result.messages || [];

    toCache.output = this.testGenerator(relativePath, messages, result);
  }

  return toCache;
};

/**
 * Post-process the filtered output, calculating the result severity from the report
 * if the option to `throwOnError` has been set
 *
 * @param {Object} results A results object returned from `processString` containing
 * the following properties:
 *    report {Object}: The report returned from this.cli.executeOnText()
 *    output {string}: The original file content passed to `processString` -- or the
 *      result of executing the a provided `testGenerator` function on the `report`
 *
 * @returns {Object} An object with an `.output` property, which will be
 *    used as the emitted file contents
 */
 EslintValidationFilter.prototype.postProcess = function postProcess({ report, output } /* , relativePath */) {

   // if verification has result
   if (report.results.length &&
       report.results[0].messages.length) {

     // log formatter output
     this.console.log(this.formatter(report.results));

     const throwOnWarn = !!this.internalOptions.throwOnWarn;
     const throwOnError = !!this.internalOptions.throwOnError;

     if (throwOnWarn || throwOnError) {
       const resultSeverity = getResultSeverity(report.results[0].messages);

       if (resultSeverity === 1 && throwOnWarn) {
         throw new Error('rules violation with `warn` severity level');
       }

       if (resultSeverity >= 2 && (throwOnWarn || throwOnError)) {
         throw new Error('rules violation with `error` severity level');
       }
     }
   }

   return {
     output
   };
};
<commit_msg>Fix API doc references<commit_after>/* eslint global-require: 0, consistent-return: 0 */

const Filter = require('broccoli-persistent-filter');
const CLIEngine = require('eslint').CLIEngine;
const md5Hex = require('md5-hex');
const stringify = require('json-stable-stringify');
const path = require('path');
const escapeStringRegexp = require('escape-string-regexp');
const BUILD_DIR_REGEXP = new RegExp('(' + escapeStringRegexp(path.sep) + ')?build(' + escapeStringRegexp(path.sep) + ')?$');
const IGNORED_FILE_MESSAGE_REGEXP = /(?:File ignored by default\.)|(?:File ignored because of a matching ignore pattern\.)/;

/**
 * Calculates the severity of a eslint.linter.verify result
 * @param {Array} resultMessages ESLint's verify() result array
 *    @see: http://eslint.org/docs/developer-guide/nodejs-api#linter
 *
 * @returns {Number} accumulatedSeverity The total severity from of the list of results
 *    0 indicates all-clear
 *    1 indicates a warning-level result
 *    > 1 indicates an error-level result
 */
function getResultSeverity(resultMessages = []) {
  return resultMessages.reduce((accumulatedSeverity, message) => {
    const severity = message.severity || 0;

    if (message.fatal || severity === 2) {
      return accumulatedSeverity + 2;
    }

    return accumulatedSeverity + severity;
  }, 0);
}

/**
 * Ignores messages that are about ignored files as they are intended
 * but we are processing a file at a time
 *
 * @param {Array} errors result errors
 * @returns {Array} filtered errors
 */
function filterIgnoredFileMessages(errors) {
  return errors.filter((error) => !IGNORED_FILE_MESSAGE_REGEXP.test(error.message));
}

/**
 * Filters all ignored file messages from result object
 * @param {Object} result result errors
 * @returns {Object} filtered results
 */
function filterAllIgnoredFileMessages(result) {
  const resultOutput = result;

  resultOutput.results.forEach((resultItem) => {
    resultItem.messages = filterIgnoredFileMessages(resultItem.messages);
  });

  return resultOutput;
}

function isString(x) {
  return toString.call(x) === '[object String]';
}

function resolveInputDirectory(inputNode) {
  if (typeof inputNode === 'string') {
    return inputNode;
  }

  // eslint-disable-next-line no-underscore-dangle
  const nodeInfo = inputNode.__broccoliGetInfo__();

  if (nodeInfo.nodeType === 'source') {
    return nodeInfo.sourceDirectory;
  }

  if (nodeInfo.inputNodes.length > 1) {
    // eslint-disable-next-line max-len
    throw new Error('EslintValidationFilter can only handle one:* broccoli nodes, but part of the given input pipeline is a many:* node. (broccoli-merge-trees is an example of a many:* node) Please perform many:* operations after linting.');
  }

  return resolveInputDirectory(nodeInfo.inputNodes[0]);
}

/**
 * Uses the content of each file in a given node and runs eslint validation on it.
 * @param {Object} inputNode Node from broccoli.makeTree
 * @param {{config: String, rulesdir: String, format: String}} options Filter options
 * @returns {EslintValidationFilter} Filter obconfig @constructor
 */
function EslintValidationFilter(inputNode, options = {}) {
  if (!(this instanceof EslintValidationFilter)) {
    return new EslintValidationFilter(inputNode, options);
  }

  this.internalOptions = options || {};
  const eslintOptions = options.options || {};

  // default ignore:true option
  if (typeof eslintOptions.ignore === 'undefined') {
    eslintOptions.ignore = true;
  }

  // default is to persist filter output
  if (typeof this.internalOptions.persist === 'undefined') {
    this.internalOptions.persist = true;
  }

  // call base class constructor
  Filter.call(this, inputNode, this.internalOptions);

  // set formatter
  if (typeof this.internalOptions.format === 'function') {
    this.formatter = this.internalOptions.format;
  } else {
    // eslint-disable-next-line global-require
    this.formatter = require(this.internalOptions.format || 'eslint/lib/formatters/stylish');
  }

  this.console = options.console || console;

  this.cli = new CLIEngine(eslintOptions);

  this.eslintrc = resolveInputDirectory(inputNode);

  if (isString(this.internalOptions.testGenerator)) {
    const testGenerators = require('./test-generators');

    this.testGenerator = testGenerators[this.internalOptions.testGenerator];
    if (!this.testGenerator) {
      throw new Error(`Could not find '${this.internalOptions.testGenerator}' test generator.`);
    }
  } else {
    this.testGenerator = this.internalOptions.testGenerator;
  }

  if (this.testGenerator) {
    this.targetExtension = 'lint-test.js';
  }
}

module.exports = EslintValidationFilter;
EslintValidationFilter.prototype = Object.create(Filter.prototype);
EslintValidationFilter.prototype.constructor = EslintValidationFilter;
EslintValidationFilter.prototype.extensions = ['js'];
EslintValidationFilter.prototype.targetExtension = 'js';

EslintValidationFilter.prototype.baseDir = function baseDir() {
  return __dirname.replace(BUILD_DIR_REGEXP, '');
};

EslintValidationFilter.prototype.cacheKeyProcessString = function cacheKeyProcessString(content, relativePath) {
  function functionStringifier(key, value) {
    if (typeof value === 'function') {
      return value.toString();
    }
    return value;
  }

  return md5Hex([
    content,
    relativePath,
    stringify(this.internalOptions, { replacer: functionStringifier }),
    stringify(this.cli.getConfigForFile(path.join(this.eslintrc, relativePath)))
  ]);
};

EslintValidationFilter.prototype.processString = function processString(content, relativePath) {
  // verify file content
  const configPath = path.join(this.eslintrc, relativePath);
  const report = this.cli.executeOnText(content, configPath);
  const filteredReport = filterAllIgnoredFileMessages(report);

  const toCache = { report, output: content };

  if (this.testGenerator && Array.isArray(filteredReport.results)) {
    const result = filteredReport.results[0] || {};
    const messages = result.messages || [];

    toCache.output = this.testGenerator(relativePath, messages, result);
  }

  return toCache;
};

/**
 * Post-process the filtered output, calculating the result severity from the report
 * if the option to `throwOnError` has been set
 *
 * @param {Object} results A results object returned from `processString`
 * @param {Object} results.report The report returned from this.cli.executeOnText()
 * @param {string} results.output The original file content passed to `processString` -- or the
 *      result of executing the a provided `testGenerator` function on the `report`
 *
 * @returns {Object} An object with an `.output` property, which will be
 *    used as the emitted file contents
 */
 EslintValidationFilter.prototype.postProcess = function postProcess(results /* , relativePath */) {
   let { report, output } = results;

   // if verification has result
   if (report.results.length &&
       report.results[0].messages.length) {

     // log formatter output
     this.console.log(this.formatter(report.results));

     const throwOnWarn = !!this.internalOptions.throwOnWarn;
     const throwOnError = !!this.internalOptions.throwOnError;

     if (throwOnWarn || throwOnError) {
       const resultSeverity = getResultSeverity(report.results[0].messages);

       if (resultSeverity === 1 && throwOnWarn) {
         throw new Error('rules violation with `warn` severity level');
       }

       if (resultSeverity >= 2 && (throwOnWarn || throwOnError)) {
         throw new Error('rules violation with `error` severity level');
       }
     }
   }

   return {
     output
   };
};
<|endoftext|>


<commit_before>/*global afterEach, describe, it */
'use strict';

var assert = require('assert');
var Decompress = require('../');
var fs = require('fs');
var path = require('path');
var rm = require('rimraf');

describe('decompress()', function () {
    afterEach(function (cb) {
        rm(path.join(__dirname, 'tmp'), cb);
    });

    it('should extract .tar', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.tar())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .tar.gz', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar.gz'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.targz())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip using the strip option', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test-strip.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip({ strip: 1 }))
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });
});
<commit_msg>Fix tests<commit_after>/*global afterEach, describe, it */
'use strict';

var assert = require('assert');
var Decompress = require('../');
var fs = require('fs');
var path = require('path');
var rm = require('rimraf');

describe('decompress()', function () {
    afterEach(function (cb) {
        rm(path.join(__dirname, 'tmp'), cb);
    });

    it('should extract .tar', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.tar())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .tar.gz', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.tar.gz'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.targz())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip())
            .decompress(function (err) {
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test.jpg')));
                cb();
            });
    });

    it('should extract .zip using the strip option', function (cb) {
        var decompress = new Decompress();

        decompress
            .src(path.join(__dirname, 'fixtures/test-strip.zip'))
            .dest(path.join(__dirname, 'tmp'))
            .use(Decompress.zip({ strip: 1 }))
            .decompress(function (err) {
                console.log(err);
                assert(!err);
                assert(fs.existsSync(path.join(__dirname, 'tmp/test-strip.jpg')));
                cb();
            });
    });
});
<|endoftext|>


<commit_before>/*jslint indent: 2*/
/*global require: true, module: true*/
(function () {
  'use strict';

  var InvalidInputError = require('./input-error.js'),
    transformationFunctions = require('./transforms'),
    transformationKeys = require('./keys'),
    regex = /^(\d*)d(\d+|\%)(([\+\-\/\*bw])(\d+))?$/,
    roll;

  roll = function (random) {
    this.random = random || function () {
      return Math.random();
    };
  };

  roll.prototype.validate = function (s) {
    return regex.test(s);
  };

  roll.prototype.parse = function (s) {
    if (!this.validate(s)) {
      throw new InvalidInputError(s);
    }

    var match = regex.exec(s),
      quantity = match[1], // 2d20+3 => 2
      sides = match[2], // 2d20+3 => 20
      hasTransformation = !!match[3], // 2d20+3 => true
      operator,
      transformationParameter,
      transforms = [],
      opIndex = 0,
      segments = s.split(/[\+\-]/);

    if (segments[0].indexOf('b') > -1) {
      transforms.push(transformationKeys[match[4]](parseInt(match[5], 10)));
    }
    for (var seg = 1; seg < segments.length; seg++) {
      opIndex += segments[seg - 1].length;
      operator = s[opIndex]; // 2d20+3 => "+"
      opIndex += 1;
      transformationParameter = segments[seg]; // 2d20+3 => 3
      if (transformationParameter.indexOf('d') > -1) {
        transforms.push(transformationKeys[operator](parseInt(this.roll(transformationParameter).result, 10)));
      } else {
        transforms.push(transformationKeys[operator](parseInt(transformationParameter, 10)));
      }
    }

    return {
      quantity: quantity ? parseInt(quantity, 10) : 1,
      sides: sides === '%' ? 100 : parseInt(sides, 10),
      transformations: hasTransformation || transforms.length > 0 ? transforms.length > 0 ? transforms : transformationKeys[match[4]](parseInt(match[5], 10)) : ['sum'],
      toString: function () {
        return s;
      }
    };
  };

  roll.prototype.roll = function (input) {
    if (!input) {
      throw new InvalidInputError();
    } else if (typeof input === 'string') {
      input = this.parse(input);
    }

    var rolled = [],
     calculations = [];

    while (rolled.length < input.quantity) {
      rolled.push(Math.floor((this.random() * input.sides) + 1));
    }

    calculations = input.transformations.reduce(function (previous, transformation) {
      var transformationFunction,
        transformationAdditionalParameter;

      if (typeof transformation === 'function') { // lets you pass something custom in
        transformationFunction = transformation;
      } else if (typeof transformation === 'string') { // "sum"
        transformationFunction = transformationFunctions[transformation];
      } else if (transformation instanceof Array) { // ["add", 3]
        transformationFunction = transformationFunctions[transformation[0]]; // fn for "add"
        transformationAdditionalParameter = transformation[1]; // 3
      }

      previous.unshift(transformationFunction(previous[0], transformationAdditionalParameter));
      return previous;
    }, [rolled]);

    return {
      input: input,
      calculations: calculations,
      rolled: calculations[calculations.length - 1],
      result: Number(calculations[0].toString())
    };
  };

  module.exports = roll;
  module.exports.InvalidInputError = InvalidInputError;

}());

<commit_msg>revert<commit_after>/*jslint indent: 2*/
/*global require: true, module: true*/
(function () {
  'use strict';

  var InvalidInputError = require('./input-error.js'),
    transformationFunctions = require('./transforms'),
    transformationKeys = require('./keys'),
    regex = /^(\d*)d(\d+|\%)(([\+\-\/\*bw])(\d+))?$/,
    roll;

  roll = function (random) {
    this.random = random || function () {
      return Math.random();
    };
  };

  roll.prototype.validate = function (s) {
    return regex.test(s);
  };

  roll.prototype.parse = function (s) {
    if (!this.validate(s)) {
      throw new InvalidInputError(s);
    }

    var match = regex.exec(s),
      quantity = match[1], // 2d20+3 => 2
      sides = match[2], // 2d20+3 => 20
      hasTransformation = !!match[3], // 2d20+3 => true
      operator,
      transformationParameter,
      transforms = [],
      opIndex = 0,
      segments = s.split(/[\+\-]/);

    if (segments[0].indexOf('b') > -1) {
      transforms.push(transformationKeys[match[4]](parseInt(match[5], 10)));
    }
    for (var seg = 1; seg < segments.length; seg++) {
      opIndex += segments[seg - 1].length;
      operator = s[opIndex]; // 2d20+3 => "+"
      opIndex += 1;
      transformationParameter = segments[seg]; // 2d20+3 => 3
      if (transformationParameter.indexOf('d') > -1) {
        transforms.push(transformationKeys[operator](parseInt(this.roll(transformationParameter).result, 10)));
      } else {
        transforms.push(transformationKeys[operator](parseInt(transformationParameter, 10)));
      }
    }

    return {
      quantity: quantity ? parseInt(quantity, 10) : 1,
      sides: sides === '%' ? 100 : parseInt(sides, 10),
      transformations: hasTransformation || transforms.length > 0 ? transforms.length > 0 ? transforms : transformationKeys[match[4]](parseInt(match[5], 10)) : ['sum'],
      toString: function () {
        return s;
      }
    };
  };

  roll.prototype.roll = function (input) {
    if (!input) {
      throw new InvalidInputError();
    } else if (typeof input === 'string') {
      input = this.parse(input);
    }

    var rolled = [],
     calculations = [];

    while (rolled.length < input.quantity) {
      rolled.push(Math.floor((this.random() * input.sides) + 1));
    }

    calculations = input.transformations.reduce(function (previous, transformation) {
      var transformationFunction,
        transformationAdditionalParameter;

      if (typeof transformation === 'function') { // lets you pass something custom in
        transformationFunction = transformation;
      } else if (typeof transformation === 'string') { // "sum"
        transformationFunction = transformationFunctions[transformation];
      } else if (transformation instanceof Array) { // ["add", 3]
        transformationFunction = transformationFunctions[transformation[0]]; // fn for "add"
        transformationAdditionalParameter = transformation[1]; // 3
      }

      previous.unshift(transformationFunction(previous[0], transformationAdditionalParameter));
      return previous;
    }, [rolled]);

    return {
      input: input,
      calculations: calculations,
      rolled: calculations[calculations.length - 1],
      result: calculations[0]
    };
  };

  module.exports = roll;
  module.exports.InvalidInputError = InvalidInputError;

}());

<|endoftext|>