<commit_before>var Net = require('net'),
    EventEmitter = require('events').EventEmitter,
    Buffer = require('buffer').Buffer,
    debugProtocol = require('debug')('node-inspector:protocol:v8-debug'),
    callbackHandler = require('./callback').create();

function makeMessage() {
  return {
    headersDone: false,
    headers: null,
    contentLength: 0
  };
}

///////////////////////////////////////////////////////////
//  exports

exports.attachDebugger = function(port) {
  var connected = false,
      debugBuffer = '',
      msg = false,
      conn = Net.createConnection(port),
      debugr,
      offset,
      contentLengthMatch,
      lastError;
  conn.setEncoding('utf8');

  function parse() {
    var b, obj;
    if (msg && msg.headersDone) {
      //parse body
      if (Buffer.byteLength(debugBuffer) >= msg.contentLength) {
        b = new Buffer(debugBuffer);
        msg.body = b.toString('utf8', 0, msg.contentLength);
        debugBuffer = b.toString('utf8', msg.contentLength, b.length);
        if (msg.body.length > 0) {
          obj = JSON.parse(msg.body);
          if (typeof obj.running === 'boolean') {
            debugr.isRunning = obj.running;
          }
          if (obj.type === 'response' && obj.request_seq > 0) {
            debugProtocol('response: ' + msg.body);
            callbackHandler.processResponse(obj.request_seq, [obj]);
          }
          else if (obj.type === 'event') {
            debugProtocol('event: ' + msg.body);
            if (['break', 'exception'].indexOf(obj.event) > -1) {
              debugr.isRunning = false;
            }
            debugr.emit(obj.event, obj);
          }
          else {
            debugProtocol('unknown: ' + msg.body);
          }
        }
        msg = false;
        parse();
      }
      return;
    }
    if (!msg) {
      msg = makeMessage();
    }

    offset = debugBuffer.indexOf('\r\n\r\n');
    if (offset > 0) {
      msg.headersDone = true;
      msg.headers = debugBuffer.substr(0, offset + 4);
      contentLengthMatch = /Content-Length: (\d+)/.exec(msg.headers);
      if (contentLengthMatch[1]) {
        msg.contentLength = parseInt(contentLengthMatch[1], 10);
      }
      else {
        console.warn('no Content-Length');
      }
      debugBuffer = debugBuffer.slice(offset + 4);
      parse();
    }
  }

  debugr = Object.create(EventEmitter.prototype, {
    isRunning: { writable: true, value: true },

    send: {
      value: function(data)
      {
        debugProtocol('request: ' + data);
        if (connected) {
          conn.write('Content-Length: ' + data.length + '\r\n\r\n' + data);
        }
      }
    },

    request: {
      value: function(command, params, callback) {
        var msg = {
          seq: 0,
          type: 'request',
          command: command
        };
        if (typeof callback == 'function') {
          msg.seq = callbackHandler.wrap(callback);
        }
        if (params) {
          Object.keys(params).forEach(function(key) {
            msg[key] = params[key];
          });
        }
        this.send(JSON.stringify(msg));
      }
    },

    close: {
      value: function()
      {
        conn.end();
      }
    },
    connected: {
      get: function() { return connected; }
    }
  });

  conn.on('connect', function() {
    connected = true;
    debugr.emit('connect');
  });

  conn.on('data', function(data) {
    debugBuffer += data;
    parse();
  });

  conn.on('error', function(e) {
    if (e.code == 'ECONNREFUSED') {
      e.helpString = 'Is node running with --debug port ' + port + '?';
    } else if (e.code == 'ECONNRESET') {
      e.helpString = 'Check there is no other debugger client attached to port ' + port + '.';
    }

    lastError = e.toString();
    if (e.helpString) {
      lastError += '. ' + e.helpString;
    }

    debugr.emit('error', e);
  });

  conn.on('end', function() {
    debugr.close();
  });

  conn.on('close', function() {
    connected = false;
    debugr.emit('close', lastError || 'Debugged process exited.');
  });

  return debugr;
};
<commit_msg>Switch to core _debugger module.<commit_after>var Net = require('net'),
    Protocol = require('_debugger').Protocol,
    inherits = require('util').inherits,
    EventEmitter = require('events').EventEmitter,
    debugProtocol = require('debug')('node-inspector:protocol:v8-debug'),
    callbackHandler = require('./callback').create();

/**
* @param {Number} port
*/
function Debugger(port){
  this._port = port;
  this._connected = false;
  this._connection = null;
  this._lastError = null;
  
  this._setupConnection();
}

inherits(Debugger, EventEmitter);

Object.defineProperties(Debugger.prototype, {
  /** @type {boolean} */
  isRunning: { writable: true, value: true },
  
  /** @type {boolean} */
  connected: {
    get: function() {
      return this._connected;
    }
  }
});

Debugger.prototype._setupConnection = function() {
  var connection = Net.createConnection(this._port),
      protocol = new Protocol();
  
  protocol.onResponse = this._processResponse.bind(this);

  connection
    .on('connect', this._onConnectionOpen.bind(this))
    .on('data', protocol.execute.bind(protocol))
    .on('error', this._onConnectionError.bind(this))
    .on('end', this.close.bind(this))
    .on('close', this._onConnectionClose.bind(this))
    .setEncoding('utf8');
    
  this._connection = connection;
};

Debugger.prototype._onConnectionOpen = function() {
  this._connected = true;
  this.emit('connect');
};


/**
* @param {Error} err
*/
Debugger.prototype._onConnectionError = function(err) {
  if (err.code == 'ECONNREFUSED') {
    err.helpString = 'Is node running with --debug port ' + this._port + '?';
  } else if (err.code == 'ECONNRESET') {
    err.helpString = 'Check there is no other debugger client attached to port ' + this._port + '.';
  }

  this._lastError = err.toString();
  if (err.helpString) {
    this._lastError += '. ' + err.helpString;
  }

  this.emit('error', err);
};

Debugger.prototype._onConnectionClose = function(hadError) {
  this.emit('close', hadError ? this._lastError : 'Debugged process exited.');
  
  this._port = null;
  this._connected = false;
  this._connection = null;
  this._lastError = null;
};

Debugger.prototype._processResponse = function(message) {
  var obj = message.body;

  if (typeof obj.running === 'boolean') {
    this.isRunning = obj.running;
  }
  if (obj.type === 'response' && obj.request_seq > 0) {
    debugProtocol('response: ' + message.body);
    callbackHandler.processResponse(obj.request_seq, [obj]);
  }
  else if (obj.type === 'event') {
    debugProtocol('event: ' + message.body);
    if (['break', 'exception'].indexOf(obj.event) > -1) {
      this.isRunning = false;
    }
    this.emit(obj.event, obj);
  }
  else {
    debugProtocol('unknown: ' + message.body);
  }
};

/**
* @param {string} data
*/
Debugger.prototype.send = function(data) {
  debugProtocol('request: ' + data);
  if (this.connected) {
    this._connection.write('Content-Length: ' + data.length + '\r\n\r\n' + data);
  }
};


/**
* @param {string} command
* @param {Object} params
* @param {function} callback
*/
Debugger.prototype.request = function(command, params, callback) {
  var message = {
    seq: 0,
    type: 'request',
    command: command
  };
  if (typeof callback === 'function') {
    message.seq = callbackHandler.wrap(callback);
  }
  if (params) {
    Object.keys(params).forEach(function(key) {
      message[key] = params[key];
    });
  }
  this.send(JSON.stringify(message));
};

/**
*/
Debugger.prototype.close = function() {
  this._connection.end();
};

/**
* @param {Number} port
* @type {Debugger}
*/
module.exports.attachDebugger = function(port) {
  return new Debugger(port);
};
{'fraction_non_alphanumeric': 0.17064054646217297, 'fraction_numerical': 0.0029642995231344243, 'mean_word_length': 2.5320892125625853, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7100519', 'n_tokens_mistral': 2424, 'n_tokens_neox': 2424, 'n_words': 473}