'use strict';

var through = require('through2');

// https://github.com/sindresorhus/ansi-regex/blob/47fb974/index.js
var ansiRegex = /(?:(?:\u001b\[)|\u009b)(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\u001b[A-M]/g;

var errorProps = [
  'stack', 
  'annotated', 
  'name', 
  'message', 
  'fileName', 
  'lineNumber', 'line',
  'columnNumber', 'column'
];

function template(error) {
  /*eslint-env browser*/
  console.error(error.name, error);
  if (typeof document === 'undefined') return;
  if (!document.body) {
    document.addEventListener('DOMContentLoaded', print);
  } else {
    print();
  }
  function print() {
    var pre = document.createElement('pre');
    pre.className = 'errorify';
    pre.textContent = error.annotated || error.message || error;
    if (document.body.firstChild) {
      document.body.insertBefore(pre, document.body.firstChild);
    } else {
      document.body.appendChild(pre);
    }
  }
}

function replace(err) {
  var result = {};
  errorProps.forEach(function(key) {
    var val = err[key];
    if (typeof val !== 'undefined') {
      if (typeof val === 'number')
        result[key] = val;
      else
        result[key] = String(val).replace(ansiRegex, '');
    }
  });
  return '!' + template + '(' + JSON.stringify(result) + ')';
}

module.exports = function errorify(b, opts) {
  var bundle = b.bundle.bind(b);
  b.bundle = function(cb) {
    var output = through();
    var pipeline = bundle(cb);
    pipeline.on('error', function(err) {
      console.error('errorify: %s', err);
      output.push(replace(err));
      output.push(null);
      pipeline.unpipe(output);
    });
    pipeline.pipe(output);
    return output;
  };
};

@@ -222,150 +222,8 @@
 g;%0A%0A
-var errorProps = %5B%0A  'stack', %0A  'annotated', %0A  'name', %0A  'message', %0A  'fileName', %0A  'lineNumber', 'line',%0A  'columnNumber', 'column'%0A%5D;%0A%0A
 func
@@ -290,20 +290,8 @@
 ror(
-error.name, 
 erro
@@ -574,27 +574,8 @@
 nt =
- error.annotated %7C%7C
  err
@@ -790,37 +790,358 @@
 %7B%0A  
-var result
+//normalize error properties%0A  err
  = %7B
-%7D;
 %0A  
-errorProps
+  message: err.annotated %7C%7C err.message,%0A    lineNumber: typeof err.line === 'number' ? err.line : err.lineNumber,%0A    columnNumber: typeof err.column === 'number' ? err.column : err.columnNumber,%0A    name: err.name,%0A    stack: err.stack,%0A    fileName: err.fileName%0A  %7D;%0A%0A  var result = %7B%7D;%0A  Object.keys(err)
 .for
@@ -1225,28 +1225,38 @@
 d') %7B%0A      
-if (
+result%5Bkey%5D = 
 typeof val =
@@ -1270,18 +1270,21 @@
 ber'
-)%0A
+ %0A   
         
 resu
@@ -1283,59 +1283,29 @@
     
-result%5Bkey%5D =
+ ?
  val
-;
+ 
 %0A      
-else%0A
       
-  result%5Bkey%5D =
+:
  Str
@@ -1347,17 +1347,17 @@
   %7D%0A  %7D)
-;
+%0A
 %0A  retur

normalize behaviour across babelify and regular browserify