Source: compiler.js

var _ = require('lodash')
  , Utils = require('src/utils')
  , Parser = require('src/parser')
  , stream = require('stream')
  , util = require('util')
  , fs = require('fs')
;

/**
 * @class Compiler
 * @param {Object|Function} opts
 */
var Compiler = module.exports = function Compiler(opts)
{
  if(!(this instanceof Compiler))
    return new Compiler(opts);

  stream.Transform.call(this, {objectMode: true});
}
util.inherits(Compiler, stream.Transform);


Compiler.prototype._transform = function (chunk, enc, done) {
  return this.compileString(chunk);
  done();
};


Compiler.prototype._compileRoutine = function (stream, done) {
  var self = this
    , done = done || function(){}
    , parser = new Parser()
    , out = []
  ;

  parser.on('data', function(chunk){
    out = out.concat(chunk);
    self.push(chunk);
  });

  parser.on('end', function(){
    done(null, out);
  });

  parser.on('error', function(err){
    if( typeof done === 'function' ) return done(err);
    throw err;
  });

  return stream
    .pipe(parser)
  ;
};

/**
 * @function Compiler#compileString
 * @param {string} str
 *
 * @TODO Write unit test
 */
Compiler.prototype.compileString = function (str, done)
{
  var stringStream = new stream.Readable()
  ;

  stringStream._read = function(){
    this.push(str);
    this.push(null);
  };

  return this._compileRoutine(stringStream, done);
  ;
}

/**
 * @function Compiler#compileFile
 * @param {string} fileName
 *
 * @TODO Write unit test
 */
Compiler.prototype.compileFile = function (fileName, done)
{
  var fileStream = fs.createReadStream(fileName)
  return this._compileRoutine(fileStream, done);
}