<commit_before>
/**
 * Modules dependencies.
 * @api private
 */

var trace = require('trace')('channel');


/**
 * Create a single data chanel from the peer connection
 * once created.
 *
 * Extend peer with a send handler to send data over
 * the peer data channel.
 *
 * Examples:
 *
 *   peer.use(channel('chat'));
 * 
 * @param {String || JSON} name
 * @api public
 */

module.exports = function(name) {

  return function(peer) {
    var channel;
    var constraints = {};

    // it seems it doesn't change anything
    // detect('cw', function() {
    //   constraints = {
    //     reliable: false
    //   };
    // });


    /**
     * Send data through channel.
     * 
     * @param  {String } data 
     * @return {this}
     * @api public
     */

    peer.send = function(data) {
      if(typeof data === 'object') {
        data = JSON.stringify(data);
      }
      channel.send(data);
    };


    // create data channel on offer
    
    peer.on('before offer', function() {
      trace('create channel');
      channel = peer.connection.createDataChannel(name, constraints);
      setChannel(peer, channel);
    });


    // create data channel on answer
    
    peer.on('before answer', function() {
      // we will have to clean that up
      peer.connection.ondatachannel = function(event) {
        trace('receive channel');
        channel = event.channel;
        setChannel(peer, channel);
      };
    });

  };
};


function setChannel(peer, channel) {

  channel.onmessage = function (event) {
    peer.emit('message', event.data);
  };

  channel.onerror = function (error) {
    peer.emit('error', error);
  };

  channel.onopen = function () {
    peer.emit('channel open', name);
  };

  channel.onclose = function () {
    peer.emit('channel close', name);
  };

}<commit_msg>refactor channel<commit_after>

module.exports = function(name, peer) {
  return function(peer) {

  }
}

/**
 * Initialize peer data channel connection.
 *
 * @param {String} name
 * @param {Peer} peer
 * @param {RTCDataChannel}
 * @api private
 */

function init(name, peer) {
  var channel = peer.createDataChannel(name)
  channel.onmessage = function (event) {
    console.log("received: " + event.data)
  }
  channel.onopen = function () {
    console.log("datachannel open");
  }
  channel.onclose = function () {
    console.log("datachannel close")
  }
  return channel
}

{'fraction_non_alphanumeric': 0.14697286012526095, 'fraction_numerical': 0.0, 'mean_word_length': 2.533923303834808, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '6373986', 'n_tokens_mistral': 743, 'n_tokens_neox': 718, 'n_words': 183}