/*
 * core.js: Core functionality for the Flatiron HTTP plugin. 
 *
 * (C) 2011, Nodejitsu Inc.
 * MIT LICENSE
 *
 */

var http = require('http'),
    https = require('https'),
    fs = require('fs'),
    stream = require('stream'),
    HttpStream = require('./http-stream'),
    RoutingStream = require('./routing-stream');
    
var core = exports;

core.createServer = function (options) {
  var isArray = Array.isArray(options.after);
  
  if (!options) {
    throw new Error('options is required to create a server');
  }
  
  function requestHandler(req, res) {
    var routingStream = new RoutingStream({
      before: options.before,
      // without new after is a huge memory leak that pipes to every
      // single open connection
      after: isArray && 
        options.after.map(function (a) { 
          return new a; 
        }),
      response: res,
      limit: options.limit,
      headers: options.headers
    });
    
    routingStream.on('error', function (err) {
      var fn = options.onError || core.errorHandler;
      fn(err, routingStream, routingStream.target, function () {
        routingStream.target.emit('next');
      });
    });
    req.pipe(routingStream);
  }
  
  if (options.https) {
    if (!options.https.key || !options.https.cert) {
      throw new Error('Both `options.https.key` and `options.https.cert` are required.');
    }
    
    var credentials = {
      key: fs.readFileSync(options.https.key),
      cert: fs.readFileSync(options.https.cert)
    };
    
    if (options.https.ca) {
      credentials.ca = fs.readFileSync(options.https.ca);
    }
    
    return https.createServer(credentials, requestHandler);
  } 
  
  return http.createServer(requestHandler);
};

core.errorHandler = function error(err, req, res) {
  if (err) {
    res.writeHead(err.status || 500, err.headers || { "Content-Type": "text/plain" });
    res.end(err.stack + "\n");
    return;
  }
  
  res.writeHead(404, {"Content-Type": "text/plain"});
  res.end("Not Found\n");
};

@@ -1784,19 +1784,33 @@
 ) %7B%0A    
-res
+(this.res %7C%7C res)
 .writeHe
@@ -1885,19 +1885,33 @@
 %7D);%0A    
-res
+(this.res %7C%7C res)
 .end(err
@@ -1947,19 +1947,33 @@
  %7D%0A  %0A  
-res
+(this.res %7C%7C res)
 .writeHe
@@ -2015,19 +2015,33 @@
 n%22%7D);%0A  
-res
+(this.res %7C%7C res)
 .end(%22No

Fix a regression due to director errorHandling