Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

removed cleartext piping hack + refctoring + test

  • Loading branch information...
commit d64f69deff7736b4d7aafc57ac882911e4676909 1 parent 8c35f04
Kilian Ciuffolo authored
2  Makefile
... ... @@ -1,7 +1,7 @@
1 1 REPORTER = spec
2 2
3 3 test:
4   - @NODE_ENV=test ./node_modules/.bin/mocha test-mocha/*.test.js $(OPT) --colors --reporter $(REPORTER)
  4 + @NODE_ENV=test ./node_modules/.bin/mocha test/*.test.js $(OPT) --colors --reporter $(REPORTER)
5 5
6 6 test-bail:
7 7 $(MAKE) test OPT=--bail
31 examples/bla.js
... ... @@ -1,18 +1,15 @@
1   -
2   -var nssocket = require('../lib/nssocket');
3   -
4   -var sockets = [];
5   -var server = nssocket.createServer(function (socket) {
6   -
7   - sockets.push(socket);
8   -
9   - socket.data('Connecting', function (data) {
10   - console.log("There are now", sockets.length);
11   -
12   - for(var i=0, l=sockets.length; i<l; i++) {
13   - sockets[i].send('Broadcasting', data);
  1 +var nssocket = require('../')
  2 +
  3 +var sockets = []
  4 +nssocket.createServer(function (socket) {
  5 + sockets.push(socket)
  6 + socket.ondata('connecting', function (data) {
  7 + console.log('There are now', sockets.length)
  8 + sockets.forEach(function (s) {
  9 + if (socket !== socket) {
  10 + s.send('broadcasting', data)
14 11 }
15   - console.dir(data);
16   - });
17   -
18   -}).listen(4949);
  12 + })
  13 + console.dir(data)
  14 + })
  15 +}).listen(4949)
16 examples/foo.js
... ... @@ -1,10 +1,8 @@
1   -var nssocket = require('../lib/nssocket');
2   -var outbound = new nssocket.NsSocket();
3   -
4   -outbound.data('Broadcasting', function (data) {
5   - console.log(data)
6   -});
7   -
8   -outbound.connect(4949);
  1 +var nssocket = require('../')
  2 +var outbound = nssocket()
9 3
10   -outbound.send('Connecting', { "random": Math.random() });
  4 +outbound.on('data::broadcasting', function (data) {
  5 + console.log(data)
  6 +}).connect(4949, function () {
  7 + outbound.send('connecting', { 'random' : Math.random() })
  8 +})
31 examples/reconnect.js
... ... @@ -1,29 +1,12 @@
1 1 var net = require('net'),
2   - nssocket = require('../lib/nssocket');
  2 + nssocket = require('../')
3 3
4 4 net.createServer(function (socket) {
5   - //
6   - // Close the underlying socket after `1000ms`
7   - //
8 5 setTimeout(function () {
9   - socket.destroy();
10   - }, 1000);
11   -}).listen(8345);
  6 + socket.destroy()
  7 + }, 1000)
  8 +}).listen(8345)
12 9
13   -//
14   -// Create an NsSocket instance with reconnect enabled
15   -//
16   -var socket = new nssocket.NsSocket({
17   - reconnect: true,
18   - type: 'tcp4',
19   -});
20   -
21   -socket.on('start', function () {
22   - //
23   - // The socket will emit this event periodically
24   - // as it attempts to reconnect
25   - //
26   - console.dir('start');
27   -});
28   -
29   -socket.connect(8345);
  10 +nssocket({ reconnect: true }).on('start', function () {
  11 + console.log('start')
  12 +}).connect(8345)
30 examples/simple-protocol.js
... ... @@ -1,10 +1,10 @@
1   -var nssocket = require('../lib/nssocket');
  1 +var nssocket = require('../')
2 2
3 3 //
4 4 // define a simple message protocol as [<type>, <id>] and create some messages that use it.
5 5 //
6   -var message1 = ['message', 'one'];
7   -var message2 = ['message', 'two'];
  6 +var message1 = ['message', 'one']
  7 +var message2 = ['message', 'two']
8 8
9 9 //
10 10 // Create an `nssocket` TCP server and tell the server to listen on port `6785`.
@@ -15,37 +15,37 @@ var server = nssocket.createServer(function (socket) {
15 15 // Here `socket` will be an instance of `nssocket.NsSocket`.
16 16 // When there is a connection, send `message1` to the socket.
17 17 //
18   - socket.send(message1);
  18 + socket.send(message1)
19 19
20 20 //
21 21 // listen for `message2` from the connecting socket.
22 22 //
23   - socket.data(message2, function (data) {
  23 + socket.ondata(message2, function (data) {
24 24
25 25 //
26 26 // If this callback is called, we know that the socket
27 27 // speaks our language, we will likely be provided with
28 28 // a payload. In this case `{ "foo": "bar" }`.
29 29 //
30   - console.dir(data);
  30 + console.log(data)
31 31 })
32 32
33   -}).listen(6785);
  33 +}).listen(6785)
34 34
35 35 //
36 36 // Create a new `nssocket` instance and then connect to the server in 1000 miliseconds.
37 37 //
38 38 setTimeout(function() {
39 39
40   - var outbound = new nssocket.NsSocket();
  40 + var outbound = nssocket()
41 41
42 42 //
43   - //
44 43 //
45   - outbound.data(message1, function () {
46   - outbound.send(message2, { "foo": "bar" });
47   - });
  44 + //
  45 + outbound.ondata(message1, function () {
  46 + outbound.send(message2, { "foo": "bar" })
  47 + })
  48 +
  49 + outbound.connect(6785)
48 50
49   - outbound.connect(6785);
50   -
51   -}, 1000);
  51 +}, 1000)
27 examples/verbose-protocol.js
... ... @@ -1,4 +1,4 @@
1   - var nssocket = require('../lib/nssocket');
  1 + var nssocket = require('../')
2 2
3 3 //
4 4 // Create an `nssocket` TCP server
@@ -8,30 +8,27 @@
8 8 // Here `socket` will be an instance of `nssocket.NsSocket`.
9 9 //
10 10
11   - socket.send(['drink', 'rum']);
12   - socket.send(['drink', 'vodka']);
  11 + socket.send(['drink', 'rum'])
  12 + socket.send(['drink', 'vodka'])
13 13
14 14 // socket.data(['iam', 'here'], function (data) {
15 15 // //
16   - // // Good! The socket speaks our language
  16 + // // Good! The socket speaks our language
17 17 // // (i.e. simple 'you::there', 'iam::here' protocol)
18 18 // //
19 19 // // { iam: true, indeedHere: true }
20 20 // //
21   - // console.dir(data);
22   - // });
23   - });
  21 + // console.dir(data)
  22 + // })
  23 + })
24 24
25 25 //
26 26 // Tell the server to listen on port `6785` and then connect to it
27 27 // using another NsSocket instance.
28 28 //
29   - server.listen(6785);
  29 + server.listen(6785)
30 30
31   - var outbound = new nssocket.NsSocket();
32   - outbound.data(['drink', '*'], function () {
33   - console.log('I can mix a', this.event[2], 'drink');
34   - //outbound.send(['iam', 'here'], { iam: true, indeedHere: true });
35   - });
36   -
37   - outbound.connect(6785);
  31 + nssocket().ondata(['drink', '*'], function () {
  32 + console.log('I can mix a', this.event[2], 'drink')
  33 + //outbound.send(['iam', 'here'], { iam: true, indeedHere: true })
  34 + }).connect(6785)
2  index.js
... ... @@ -1,3 +1,3 @@
1   -module.exports = process.env.NSSSOCKET_COV
  1 +module.exports = process.env.NSSOCKET_COV
2 2 ? require('./lib-cov/nssocket')
3 3 : require('./lib/nssocket')
529 lib-cov/nssocket.js
... ... @@ -0,0 +1,529 @@
  1 +/* automatically generated by JSCoverage - do not edit */
  2 +if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
  3 +if (! _$jscoverage['nssocket.js']) {
  4 + _$jscoverage['nssocket.js'] = [];
  5 + _$jscoverage['nssocket.js'][1] = 0;
  6 + _$jscoverage['nssocket.js'][8] = 0;
  7 + _$jscoverage['nssocket.js'][9] = 0;
  8 + _$jscoverage['nssocket.js'][10] = 0;
  9 + _$jscoverage['nssocket.js'][11] = 0;
  10 + _$jscoverage['nssocket.js'][12] = 0;
  11 + _$jscoverage['nssocket.js'][15] = 0;
  12 + _$jscoverage['nssocket.js'][16] = 0;
  13 + _$jscoverage['nssocket.js'][18] = 0;
  14 + _$jscoverage['nssocket.js'][19] = 0;
  15 + _$jscoverage['nssocket.js'][20] = 0;
  16 + _$jscoverage['nssocket.js'][23] = 0;
  17 + _$jscoverage['nssocket.js'][29] = 0;
  18 + _$jscoverage['nssocket.js'][30] = 0;
  19 + _$jscoverage['nssocket.js'][31] = 0;
  20 + _$jscoverage['nssocket.js'][33] = 0;
  21 + _$jscoverage['nssocket.js'][34] = 0;
  22 + _$jscoverage['nssocket.js'][35] = 0;
  23 + _$jscoverage['nssocket.js'][38] = 0;
  24 + _$jscoverage['nssocket.js'][39] = 0;
  25 + _$jscoverage['nssocket.js'][42] = 0;
  26 + _$jscoverage['nssocket.js'][43] = 0;
  27 + _$jscoverage['nssocket.js'][44] = 0;
  28 + _$jscoverage['nssocket.js'][51] = 0;
  29 + _$jscoverage['nssocket.js'][57] = 0;
  30 + _$jscoverage['nssocket.js'][58] = 0;
  31 + _$jscoverage['nssocket.js'][59] = 0;
  32 + _$jscoverage['nssocket.js'][60] = 0;
  33 + _$jscoverage['nssocket.js'][61] = 0;
  34 + _$jscoverage['nssocket.js'][65] = 0;
  35 + _$jscoverage['nssocket.js'][67] = 0;
  36 + _$jscoverage['nssocket.js'][68] = 0;
  37 + _$jscoverage['nssocket.js'][69] = 0;
  38 + _$jscoverage['nssocket.js'][71] = 0;
  39 + _$jscoverage['nssocket.js'][72] = 0;
  40 + _$jscoverage['nssocket.js'][73] = 0;
  41 + _$jscoverage['nssocket.js'][74] = 0;
  42 + _$jscoverage['nssocket.js'][76] = 0;
  43 + _$jscoverage['nssocket.js'][78] = 0;
  44 + _$jscoverage['nssocket.js'][80] = 0;
  45 + _$jscoverage['nssocket.js'][83] = 0;
  46 + _$jscoverage['nssocket.js'][84] = 0;
  47 + _$jscoverage['nssocket.js'][87] = 0;
  48 + _$jscoverage['nssocket.js'][89] = 0;
  49 + _$jscoverage['nssocket.js'][90] = 0;
  50 + _$jscoverage['nssocket.js'][93] = 0;
  51 + _$jscoverage['nssocket.js'][94] = 0;
  52 + _$jscoverage['nssocket.js'][95] = 0;
  53 + _$jscoverage['nssocket.js'][96] = 0;
  54 + _$jscoverage['nssocket.js'][99] = 0;
  55 + _$jscoverage['nssocket.js'][102] = 0;
  56 + _$jscoverage['nssocket.js'][103] = 0;
  57 + _$jscoverage['nssocket.js'][105] = 0;
  58 + _$jscoverage['nssocket.js'][106] = 0;
  59 + _$jscoverage['nssocket.js'][109] = 0;
  60 + _$jscoverage['nssocket.js'][111] = 0;
  61 + _$jscoverage['nssocket.js'][112] = 0;
  62 + _$jscoverage['nssocket.js'][114] = 0;
  63 + _$jscoverage['nssocket.js'][115] = 0;
  64 + _$jscoverage['nssocket.js'][118] = 0;
  65 + _$jscoverage['nssocket.js'][119] = 0;
  66 + _$jscoverage['nssocket.js'][121] = 0;
  67 + _$jscoverage['nssocket.js'][124] = 0;
  68 + _$jscoverage['nssocket.js'][125] = 0;
  69 + _$jscoverage['nssocket.js'][126] = 0;
  70 + _$jscoverage['nssocket.js'][128] = 0;
  71 + _$jscoverage['nssocket.js'][131] = 0;
  72 + _$jscoverage['nssocket.js'][132] = 0;
  73 + _$jscoverage['nssocket.js'][135] = 0;
  74 + _$jscoverage['nssocket.js'][136] = 0;
  75 + _$jscoverage['nssocket.js'][137] = 0;
  76 + _$jscoverage['nssocket.js'][139] = 0;
  77 + _$jscoverage['nssocket.js'][142] = 0;
  78 + _$jscoverage['nssocket.js'][143] = 0;
  79 + _$jscoverage['nssocket.js'][144] = 0;
  80 + _$jscoverage['nssocket.js'][147] = 0;
  81 + _$jscoverage['nssocket.js'][148] = 0;
  82 + _$jscoverage['nssocket.js'][150] = 0;
  83 + _$jscoverage['nssocket.js'][151] = 0;
  84 + _$jscoverage['nssocket.js'][152] = 0;
  85 + _$jscoverage['nssocket.js'][155] = 0;
  86 + _$jscoverage['nssocket.js'][158] = 0;
  87 + _$jscoverage['nssocket.js'][159] = 0;
  88 + _$jscoverage['nssocket.js'][160] = 0;
  89 + _$jscoverage['nssocket.js'][162] = 0;
  90 + _$jscoverage['nssocket.js'][163] = 0;
  91 + _$jscoverage['nssocket.js'][165] = 0;
  92 + _$jscoverage['nssocket.js'][166] = 0;
  93 + _$jscoverage['nssocket.js'][169] = 0;
  94 + _$jscoverage['nssocket.js'][172] = 0;
  95 + _$jscoverage['nssocket.js'][173] = 0;
  96 + _$jscoverage['nssocket.js'][175] = 0;
  97 + _$jscoverage['nssocket.js'][176] = 0;
  98 + _$jscoverage['nssocket.js'][177] = 0;
  99 + _$jscoverage['nssocket.js'][180] = 0;
  100 + _$jscoverage['nssocket.js'][181] = 0;
  101 + _$jscoverage['nssocket.js'][183] = 0;
  102 + _$jscoverage['nssocket.js'][184] = 0;
  103 + _$jscoverage['nssocket.js'][185] = 0;
  104 + _$jscoverage['nssocket.js'][188] = 0;
  105 + _$jscoverage['nssocket.js'][191] = 0;
  106 + _$jscoverage['nssocket.js'][192] = 0;
  107 + _$jscoverage['nssocket.js'][194] = 0;
  108 + _$jscoverage['nssocket.js'][195] = 0;
  109 + _$jscoverage['nssocket.js'][197] = 0;
  110 + _$jscoverage['nssocket.js'][200] = 0;
  111 + _$jscoverage['nssocket.js'][201] = 0;
  112 + _$jscoverage['nssocket.js'][204] = 0;
  113 + _$jscoverage['nssocket.js'][206] = 0;
  114 + _$jscoverage['nssocket.js'][207] = 0;
  115 + _$jscoverage['nssocket.js'][208] = 0;
  116 + _$jscoverage['nssocket.js'][209] = 0;
  117 + _$jscoverage['nssocket.js'][211] = 0;
  118 + _$jscoverage['nssocket.js'][212] = 0;
  119 + _$jscoverage['nssocket.js'][214] = 0;
  120 + _$jscoverage['nssocket.js'][217] = 0;
  121 + _$jscoverage['nssocket.js'][218] = 0;
  122 + _$jscoverage['nssocket.js'][219] = 0;
  123 + _$jscoverage['nssocket.js'][222] = 0;
  124 + _$jscoverage['nssocket.js'][223] = 0;
  125 + _$jscoverage['nssocket.js'][228] = 0;
  126 + _$jscoverage['nssocket.js'][229] = 0;
  127 + _$jscoverage['nssocket.js'][230] = 0;
  128 + _$jscoverage['nssocket.js'][231] = 0;
  129 + _$jscoverage['nssocket.js'][232] = 0;
  130 + _$jscoverage['nssocket.js'][233] = 0;
  131 + _$jscoverage['nssocket.js'][234] = 0;
  132 + _$jscoverage['nssocket.js'][236] = 0;
  133 + _$jscoverage['nssocket.js'][240] = 0;
  134 + _$jscoverage['nssocket.js'][241] = 0;
  135 + _$jscoverage['nssocket.js'][242] = 0;
  136 + _$jscoverage['nssocket.js'][243] = 0;
  137 + _$jscoverage['nssocket.js'][245] = 0;
  138 + _$jscoverage['nssocket.js'][246] = 0;
  139 + _$jscoverage['nssocket.js'][247] = 0;
  140 + _$jscoverage['nssocket.js'][248] = 0;
  141 + _$jscoverage['nssocket.js'][250] = 0;
  142 + _$jscoverage['nssocket.js'][251] = 0;
  143 + _$jscoverage['nssocket.js'][253] = 0;
  144 + _$jscoverage['nssocket.js'][255] = 0;
  145 + _$jscoverage['nssocket.js'][256] = 0;
  146 + _$jscoverage['nssocket.js'][259] = 0;
  147 + _$jscoverage['nssocket.js'][262] = 0;
  148 + _$jscoverage['nssocket.js'][265] = 0;
  149 + _$jscoverage['nssocket.js'][266] = 0;
  150 + _$jscoverage['nssocket.js'][267] = 0;
  151 + _$jscoverage['nssocket.js'][269] = 0;
  152 + _$jscoverage['nssocket.js'][270] = 0;
  153 + _$jscoverage['nssocket.js'][272] = 0;
  154 + _$jscoverage['nssocket.js'][275] = 0;
  155 + _$jscoverage['nssocket.js'][278] = 0;
  156 + _$jscoverage['nssocket.js'][279] = 0;
  157 + _$jscoverage['nssocket.js'][282] = 0;
  158 + _$jscoverage['nssocket.js'][283] = 0;
  159 + _$jscoverage['nssocket.js'][284] = 0;
  160 +}
  161 +_$jscoverage['nssocket.js'][1]++;
  162 +var net = require("net"), tls = require("tls"), util = require("util"), assert = require("chai").assert, EventEmitter2 = require("eventemitter2").EventEmitter2, bufferjoiner = require("bufferjoiner");
  163 +_$jscoverage['nssocket.js'][8]++;
  164 +module.exports = NsSocket;
  165 +_$jscoverage['nssocket.js'][9]++;
  166 +module.exports.createServer = (function createServer(options, connectionListener) {
  167 + _$jscoverage['nssocket.js'][10]++;
  168 + if (! connectionListener && typeof options === "function") {
  169 + _$jscoverage['nssocket.js'][11]++;
  170 + connectionListener = options;
  171 + _$jscoverage['nssocket.js'][12]++;
  172 + options = {};
  173 + }
  174 + _$jscoverage['nssocket.js'][15]++;
  175 + options.type = options.type || "tcp4";
  176 + _$jscoverage['nssocket.js'][16]++;
  177 + options.delimiter = options.delimiter || "::";
  178 + _$jscoverage['nssocket.js'][18]++;
  179 + function onConnection(socket) {
  180 + _$jscoverage['nssocket.js'][19]++;
  181 + options.reconnect = false;
  182 + _$jscoverage['nssocket.js'][20]++;
  183 + connectionListener(new NsSocket(options, socket));
  184 +}
  185 + _$jscoverage['nssocket.js'][23]++;
  186 + return options.type === "tls"? tls.createServer(options, onConnection): net.createServer(options, onConnection);
  187 +});
  188 +_$jscoverage['nssocket.js'][29]++;
  189 +module.exports.data = module.exports.ondata;
  190 +_$jscoverage['nssocket.js'][30]++;
  191 +module.exports.unData = module.exports.offdata;
  192 +_$jscoverage['nssocket.js'][31]++;
  193 +module.exports.dataOnce = module.exports.oncedata;
  194 +_$jscoverage['nssocket.js'][33]++;
  195 +function NsSocket(options, socket) {
  196 + _$jscoverage['nssocket.js'][34]++;
  197 + if (! (this instanceof NsSocket)) {
  198 + _$jscoverage['nssocket.js'][35]++;
  199 + return new NsSocket(options, socket);
  200 + }
  201 + _$jscoverage['nssocket.js'][38]++;
  202 + if (! options) {
  203 + _$jscoverage['nssocket.js'][39]++;
  204 + options = socket || {};
  205 + }
  206 + _$jscoverage['nssocket.js'][42]++;
  207 + this.connected = false;
  208 + _$jscoverage['nssocket.js'][43]++;
  209 + this.type = options.type || "tcp4";
  210 + _$jscoverage['nssocket.js'][44]++;
  211 + this.retry = options.reconnect? {retries: 0, max: options.maxRetries || 10, interval: options.retryInterval || 5000, wait: options.retryInterval || 5000}: false;
  212 + _$jscoverage['nssocket.js'][51]++;
  213 + EventEmitter2.call(this, {delimiter: options.delimiter || "::", wildcard: true, maxListeners: options.maxListeners || 10});
  214 + _$jscoverage['nssocket.js'][57]++;
  215 + if (socket) {
  216 + _$jscoverage['nssocket.js'][58]++;
  217 + this.stream = socket;
  218 + _$jscoverage['nssocket.js'][59]++;
  219 + this.socket = this.stream instanceof net.Socket? this.stream: this.stream.socket;
  220 + _$jscoverage['nssocket.js'][60]++;
  221 + this.connected = this.socket.writable && this.socket.readable || false;
  222 + _$jscoverage['nssocket.js'][61]++;
  223 + configureEvents(this);
  224 + }
  225 +}
  226 +_$jscoverage['nssocket.js'][65]++;
  227 +util.inherits(NsSocket, EventEmitter2);
  228 +_$jscoverage['nssocket.js'][67]++;
  229 +NsSocket.prototype.connect = (function connect(port) {
  230 + _$jscoverage['nssocket.js'][68]++;
  231 + if (! this.socket) {
  232 + _$jscoverage['nssocket.js'][69]++;
  233 + var module = this.type === "tls"? tls: net;
  234 + _$jscoverage['nssocket.js'][71]++;
  235 + this.stream = module.connect.apply(null, arguments);
  236 + _$jscoverage['nssocket.js'][72]++;
  237 + this.socket = this.stream instanceof net.Socket? this.stream: this.stream.socket;
  238 + _$jscoverage['nssocket.js'][73]++;
  239 + this.connected = this.socket.writable && this.socket.readable || false;
  240 + _$jscoverage['nssocket.js'][74]++;
  241 + this.connectionArgs = arguments;
  242 + _$jscoverage['nssocket.js'][76]++;
  243 + configureEvents(this);
  244 + }
  245 + else {
  246 + _$jscoverage['nssocket.js'][78]++;
  247 + this.socket.connect.apply(this.socket, arguments);
  248 + }
  249 + _$jscoverage['nssocket.js'][80]++;
  250 + return this;
  251 +});
  252 +_$jscoverage['nssocket.js'][83]++;
  253 +NsSocket.prototype.write = (function write(buff) {
  254 + _$jscoverage['nssocket.js'][84]++;
  255 + this.stream.write(buff);
  256 +});
  257 +_$jscoverage['nssocket.js'][87]++;
  258 +NsSocket.prototype.send = (function send(event, data, callback) {
  259 + _$jscoverage['nssocket.js'][89]++;
  260 + if (! this.socket || ! this.connected) {
  261 + _$jscoverage['nssocket.js'][90]++;
  262 + return this.emit("error", new Error("NsSocket: sending on a bad socket"));
  263 + }
  264 + _$jscoverage['nssocket.js'][93]++;
  265 + var dataType = typeof data;
  266 + _$jscoverage['nssocket.js'][94]++;
  267 + if (dataType === "undefined" || dataType === "function") {
  268 + _$jscoverage['nssocket.js'][95]++;
  269 + callback = data;
  270 + _$jscoverage['nssocket.js'][96]++;
  271 + data = null;
  272 + }
  273 + _$jscoverage['nssocket.js'][99]++;
  274 + this.stream.write(this.createMessage(event, data), callback);
  275 +});
  276 +_$jscoverage['nssocket.js'][102]++;
  277 +NsSocket.prototype.createMessage = (function createMessage(event, data) {
  278 + _$jscoverage['nssocket.js'][103]++;
  279 + var header = new Buffer(9);
  280 + _$jscoverage['nssocket.js'][105]++;
  281 + if (typeof event === "string") {
  282 + _$jscoverage['nssocket.js'][106]++;
  283 + event = event.split(this.delimiter);
  284 + }
  285 + _$jscoverage['nssocket.js'][109]++;
  286 + event = Buffer(JSON.stringify(event));
  287 + _$jscoverage['nssocket.js'][111]++;
  288 + if (Buffer.isBuffer(data)) {
  289 + _$jscoverage['nssocket.js'][112]++;
  290 + header.writeInt8(1, 8);
  291 + }
  292 + else {
  293 + _$jscoverage['nssocket.js'][114]++;
  294 + data = Buffer(JSON.stringify(data));
  295 + _$jscoverage['nssocket.js'][115]++;
  296 + header.writeInt8(0, 8);
  297 + }
  298 + _$jscoverage['nssocket.js'][118]++;
  299 + header.writeUInt32BE(event.length, 0);
  300 + _$jscoverage['nssocket.js'][119]++;
  301 + header.writeUInt32BE(data.length, 4);
  302 + _$jscoverage['nssocket.js'][121]++;
  303 + return Buffer.concat([header, event, data], 9 + event.length + data.length);
  304 +});
  305 +_$jscoverage['nssocket.js'][124]++;
  306 +NsSocket.prototype.ondata = (function (event, listener) {
  307 + _$jscoverage['nssocket.js'][125]++;
  308 + if (typeof event === "string") {
  309 + _$jscoverage['nssocket.js'][126]++;
  310 + event = event.split(this.delimiter);
  311 + }
  312 + _$jscoverage['nssocket.js'][128]++;
  313 + return this.on(["data"].concat(event), listener);
  314 +});
  315 +_$jscoverage['nssocket.js'][131]++;
  316 +NsSocket.prototype.offdata = (function (event, listener) {
  317 + _$jscoverage['nssocket.js'][132]++;
  318 + return this.off(["data"].concat(event), listener);
  319 +});
  320 +_$jscoverage['nssocket.js'][135]++;
  321 +NsSocket.prototype.oncedata = (function (event, listener) {
  322 + _$jscoverage['nssocket.js'][136]++;
  323 + if (typeof event === "string") {
  324 + _$jscoverage['nssocket.js'][137]++;
  325 + event = event.split(this.delimiter);
  326 + }
  327 + _$jscoverage['nssocket.js'][139]++;
  328 + return this.once(["data"].concat(event), listener);
  329 +});
  330 +_$jscoverage['nssocket.js'][142]++;
  331 +NsSocket.prototype.setIdle = (function setIdle(timeout) {
  332 + _$jscoverage['nssocket.js'][143]++;
  333 + this.socket.setTimeout(timeout);
  334 + _$jscoverage['nssocket.js'][144]++;
  335 + this.timeout = timeout;
  336 +});
  337 +_$jscoverage['nssocket.js'][147]++;
  338 +NsSocket.prototype.destroy = (function destroy() {
  339 + _$jscoverage['nssocket.js'][148]++;
  340 + this.removeAllListeners();
  341 + _$jscoverage['nssocket.js'][150]++;
  342 + try {
  343 + _$jscoverage['nssocket.js'][151]++;
  344 + this.socket.end();
  345 + _$jscoverage['nssocket.js'][152]++;
  346 + this.socket.destroy();
  347 + }
  348 + catch (err) {
  349 + }
  350 + _$jscoverage['nssocket.js'][155]++;
  351 + this.emit("destroy");
  352 +});
  353 +_$jscoverage['nssocket.js'][158]++;
  354 +NsSocket.prototype.end = (function end() {
  355 + _$jscoverage['nssocket.js'][159]++;
  356 + var hadErr;
  357 + _$jscoverage['nssocket.js'][160]++;
  358 + this.connected = false;
  359 + _$jscoverage['nssocket.js'][162]++;
  360 + try {
  361 + _$jscoverage['nssocket.js'][163]++;
  362 + this.socket.end();
  363 + }
  364 + catch (err) {
  365 + _$jscoverage['nssocket.js'][165]++;
  366 + hadErr = true;
  367 + _$jscoverage['nssocket.js'][166]++;
  368 + this.emit("error", err);
  369 + }
  370 + _$jscoverage['nssocket.js'][169]++;
  371 + this.emit("close", hadErr);
  372 +});
  373 +_$jscoverage['nssocket.js'][172]++;
  374 +NsSocket.prototype.reconnect = (function reconnect() {
  375 + _$jscoverage['nssocket.js'][173]++;
  376 + var self = this;
  377 + _$jscoverage['nssocket.js'][175]++;
  378 + function doReconnect() {
  379 + _$jscoverage['nssocket.js'][176]++;
  380 + self.retry.waiting = true;
  381 + _$jscoverage['nssocket.js'][177]++;
  382 + self.socket && self.socket.destroy();
  383 + _$jscoverage['nssocket.js'][180]++;
  384 + assert.isFalse(self.connected, "before actually reconnect connected must be false");
  385 + _$jscoverage['nssocket.js'][181]++;
  386 + assert.isUndefined(self.socket, "before actually reconnect socket must be destroied");
  387 + _$jscoverage['nssocket.js'][183]++;
  388 + self.once("start", (function () {
  389 + _$jscoverage['nssocket.js'][184]++;
  390 + self.retry.waiting = false;
  391 + _$jscoverage['nssocket.js'][185]++;
  392 + self.retry.retries = 0;
  393 +}));
  394 + _$jscoverage['nssocket.js'][188]++;
  395 + self.connect.apply(self, self.connectionArgs);
  396 +}
  397 + _$jscoverage['nssocket.js'][191]++;
  398 + function tryReconnect() {
  399 + _$jscoverage['nssocket.js'][192]++;
  400 + self.retry.retries++;
  401 + _$jscoverage['nssocket.js'][194]++;
  402 + if (self.retry.retries >= self.retry.max) {
  403 + _$jscoverage['nssocket.js'][195]++;
  404 + return self.emit("error", new Error("Did not reconnect after maximum retries: " + self.retry.max));
  405 + }
  406 + _$jscoverage['nssocket.js'][197]++;
  407 + doReconnect();
  408 +}
  409 + _$jscoverage['nssocket.js'][200]++;
  410 + this.retry.wait = this.retry.interval * Math.pow(10, this.retry.retries);
  411 + _$jscoverage['nssocket.js'][201]++;
  412 + setTimeout(tryReconnect, this.retry.wait);
  413 +});
  414 +_$jscoverage['nssocket.js'][204]++;
  415 +function configureEvents(self) {
  416 + _$jscoverage['nssocket.js'][206]++;
  417 + var eventLength = -1;
  418 + _$jscoverage['nssocket.js'][207]++;
  419 + var messageLength = -1;
  420 + _$jscoverage['nssocket.js'][208]++;
  421 + var messagetype = 0;
  422 + _$jscoverage['nssocket.js'][209]++;
  423 + var bufferJoiner = bufferjoiner();
  424 + _$jscoverage['nssocket.js'][211]++;
  425 + if (self.type === "tls") {
  426 + _$jscoverage['nssocket.js'][212]++;
  427 + self.stream.on("secureConnect", onStart);
  428 + }
  429 + else {
  430 + _$jscoverage['nssocket.js'][214]++;
  431 + self.socket.on("connect", onStart);
  432 + }
  433 + _$jscoverage['nssocket.js'][217]++;
  434 + function onStart() {
  435 + _$jscoverage['nssocket.js'][218]++;
  436 + self.connected = true;
  437 + _$jscoverage['nssocket.js'][219]++;
  438 + self.emit("start");
  439 +}
  440 + _$jscoverage['nssocket.js'][222]++;
  441 + self.stream.on("data", (function onData(chunk) {
  442 + _$jscoverage['nssocket.js'][223]++;
  443 + ~ messageLength? fetchBody(chunk): fetchHeader(chunk);
  444 +}));
  445 + _$jscoverage['nssocket.js'][228]++;
  446 + function fetchHeader(chunk) {
  447 + _$jscoverage['nssocket.js'][229]++;
  448 + if (bufferJoiner.length + chunk.length >= 9) {
  449 + _$jscoverage['nssocket.js'][230]++;
  450 + var header = bufferJoiner.add(chunk).join();
  451 + _$jscoverage['nssocket.js'][231]++;
  452 + eventLength = header.readUInt32BE(0);
  453 + _$jscoverage['nssocket.js'][232]++;
  454 + messageLength = header.readUInt32BE(4);
  455 + _$jscoverage['nssocket.js'][233]++;
  456 + messagetype = header.readInt8(8);
  457 + _$jscoverage['nssocket.js'][234]++;
  458 + fetchBody(chunk.slice(9));
  459 + }
  460 + else {
  461 + _$jscoverage['nssocket.js'][236]++;
  462 + bufferJoiner.add(chunk);
  463 + }
  464 +}
  465 + _$jscoverage['nssocket.js'][240]++;
  466 + function fetchBody(chunk) {
  467 + _$jscoverage['nssocket.js'][241]++;
  468 + var raw, event, data;
  469 + _$jscoverage['nssocket.js'][242]++;
  470 + var chunkLength = chunk.length;
  471 + _$jscoverage['nssocket.js'][243]++;
  472 + var bytesLeft = (eventLength + messageLength) - bufferJoiner.length;
  473 + _$jscoverage['nssocket.js'][245]++;
  474 + if (chunkLength >= bytesLeft) {
  475 + _$jscoverage['nssocket.js'][246]++;
  476 + raw = bufferJoiner.add(chunk.slice(0, bytesLeft)).join();
  477 + _$jscoverage['nssocket.js'][247]++;
  478 + event = JSON.parse(raw.slice(0, eventLength));
  479 + _$jscoverage['nssocket.js'][248]++;
  480 + data = messagetype? raw.slice(eventLength): JSON.parse(raw.slice(eventLength).toString());
  481 + _$jscoverage['nssocket.js'][250]++;
  482 + eventLength = -1;
  483 + _$jscoverage['nssocket.js'][251]++;
  484 + messageLength = -1;
  485 + _$jscoverage['nssocket.js'][253]++;
  486 + self.emit(["data"].concat(event), data);
  487 + _$jscoverage['nssocket.js'][255]++;
  488 + if (chunkLength - bytesLeft) {
  489 + _$jscoverage['nssocket.js'][256]++;
  490 + fetchHeader(chunk.slice(bytesLeft));
  491 + }
  492 + _$jscoverage['nssocket.js'][259]++;
  493 + return;
  494 + }
  495 + _$jscoverage['nssocket.js'][262]++;
  496 + bufferJoiner.add(chunk);
  497 +}
  498 + _$jscoverage['nssocket.js'][265]++;
  499 + self.socket.on("close", (function onClose(hadError) {
  500 + _$jscoverage['nssocket.js'][266]++;
  501 + self.socket = undefined;
  502 + _$jscoverage['nssocket.js'][267]++;
  503 + self.connected = false;
  504 + _$jscoverage['nssocket.js'][269]++;
  505 + if (hadError) {
  506 + _$jscoverage['nssocket.js'][270]++;
  507 + self.emit("close", hadError, arguments[1]);
  508 + }
  509 + else {
  510 + _$jscoverage['nssocket.js'][272]++;
  511 + self.emit("close");
  512 + }
  513 + _$jscoverage['nssocket.js'][275]++;
  514 + self.retry && self.reconnect();
  515 +}));
  516 + _$jscoverage['nssocket.js'][278]++;
  517 + self.socket.on("error", (function (err) {
  518 + _$jscoverage['nssocket.js'][279]++;
  519 + ! self.retry && self.emit("error", err || new Error("An Unknown Error occured"));
  520 +}));
  521 + _$jscoverage['nssocket.js'][282]++;
  522 + self.socket.on("timeout", (function onIdle() {
  523 + _$jscoverage['nssocket.js'][283]++;
  524 + self.emit("idle");
  525 + _$jscoverage['nssocket.js'][284]++;
  526 + self.timeout && self.socket.setTimeout(this.timeout);
  527 +}));
  528 +}
  529 +_$jscoverage['nssocket.js'].source = ["var net = require('net'),"," tls = require('tls'),"," util = require('util'),"," assert = require('chai').assert,"," EventEmitter2 = require('eventemitter2').EventEmitter2,"," bufferjoiner = require('bufferjoiner')","","module.exports = NsSocket","module.exports.createServer = function createServer(options, connectionListener) {"," if (!connectionListener &amp;&amp; typeof options === 'function') {"," connectionListener = options"," options = {}"," }",""," options.type = options.type || 'tcp4'"," options.delimiter = options.delimiter || '::'",""," function onConnection (socket) {"," options.reconnect = false"," connectionListener(new NsSocket(options, socket))"," }",""," return options.type === 'tls'"," ? tls.createServer(options, onConnection)"," : net.createServer(options, onConnection)","}","","// retro compatibility fixes","module.exports.data = module.exports.ondata","module.exports.unData = module.exports.offdata","module.exports.dataOnce = module.exports.oncedata","","function NsSocket(options, socket) {"," if (!(this instanceof NsSocket)) {"," return new NsSocket(options, socket)"," }",""," if (!options) {"," options = socket || {}"," }",""," this.connected = false"," this.type = options.type || 'tcp4'"," this.retry = options.reconnect ? {"," retries: 0,"," max: options.maxRetries || 10,"," interval: options.retryInterval || 5000,"," wait: options.retryInterval || 5000"," } : false",""," EventEmitter2.call(this, {"," delimiter: options.delimiter || '::',"," wildcard: true,"," maxListeners: options.maxListeners || 10"," })",""," if (socket) {"," this.stream = socket"," this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket"," this.connected = this.socket.writable &amp;&amp; this.socket.readable || false"," configureEvents(this)"," }","}","","util.inherits(NsSocket, EventEmitter2)","","NsSocket.prototype.connect = function connect(port) {"," if (!this.socket) {"," var module = this.type === 'tls' ? tls : net",""," this.stream = module.connect.apply(null, arguments)"," this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket"," this.connected = this.socket.writable &amp;&amp; this.socket.readable || false"," this.connectionArgs = arguments",""," configureEvents(this)"," } else {"," this.socket.connect.apply(this.socket, arguments)"," }"," return this","}","","NsSocket.prototype.write = function write(buff) {"," this.stream.write(buff)","}","","NsSocket.prototype.send = function send(event, data, callback) {"," // if we aren't connected/socketed, then error"," if (!this.socket || !this.connected) {"," return this.emit('error', new Error('NsSocket: sending on a bad socket'))"," }",""," var dataType = typeof data"," if (dataType === 'undefined' || dataType === 'function') {"," callback = data"," data = null"," }",""," this.stream.write(this.createMessage(event, data), callback)","}","","NsSocket.prototype.createMessage = function createMessage(event, data) {"," var header = new Buffer(9)",""," if (typeof event === 'string') {"," event = event.split(this.delimiter)"," }",""," event = Buffer(JSON.stringify(event))",""," if (Buffer.isBuffer(data)) {"," header.writeInt8(1, 8)"," } else {"," data = Buffer(JSON.stringify(data))"," header.writeInt8(0, 8)"," }",""," header.writeUInt32BE(event.length, 0)"," header.writeUInt32BE(data.length, 4)",""," return Buffer.concat([header, event, data], 9 + event.length + data.length)","}","","NsSocket.prototype.ondata = function (event, listener) {"," if (typeof event === 'string') {"," event = event.split(this.delimiter)"," }"," return this.on(['data'].concat(event), listener)","}","","NsSocket.prototype.offdata = function (event, listener) {"," return this.off(['data'].concat(event), listener)","}","","NsSocket.prototype.oncedata = function (event, listener) {"," if (typeof event === 'string') {"," event = event.split(this.delimiter)"," }"," return this.once(['data'].concat(event), listener)","}","","NsSocket.prototype.setIdle = function setIdle(timeout) {"," this.socket.setTimeout(timeout)"," this.timeout = timeout","}","","NsSocket.prototype.destroy = function destroy() {"," this.removeAllListeners()",""," try {"," this.socket.end()"," this.socket.destroy()"," } catch (err) {}",""," this.emit('destroy')","}","","NsSocket.prototype.end = function end() {"," var hadErr"," this.connected = false",""," try {"," this.socket.end()"," } catch (err) {"," hadErr = true"," this.emit('error', err)"," }",""," this.emit('close', hadErr)","}","","NsSocket.prototype.reconnect = function reconnect() {"," var self = this",""," function doReconnect() {"," self.retry.waiting = true"," self.socket &amp;&amp; self.socket.destroy()",""," // here for debugging reasons"," assert.isFalse(self.connected, 'before actually reconnect connected must be false')"," assert.isUndefined(self.socket, 'before actually reconnect socket must be destroied')",""," self.once('start', function () {"," self.retry.waiting = false"," self.retry.retries = 0"," })",""," self.connect.apply(self, self.connectionArgs)"," }",""," function tryReconnect() {"," self.retry.retries ++",""," if (self.retry.retries &gt;= self.retry.max) {"," return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max))"," }"," doReconnect()"," }",""," this.retry.wait = this.retry.interval * Math.pow(10, this.retry.retries)"," setTimeout(tryReconnect, this.retry.wait)","}","","function configureEvents(self) {"," // parsing holders"," var eventLength = -1"," var messageLength = -1"," var messagetype = 0"," var bufferJoiner = bufferjoiner()",""," if (self.type === 'tls') {"," self.stream.on('secureConnect', onStart)"," } else {"," self.socket.on('connect', onStart)"," }",""," function onStart() {"," self.connected = true"," self.emit('start')"," }",""," self.stream.on('data', function onData(chunk) {"," ~messageLength"," ? fetchBody(chunk)"," : fetchHeader(chunk)"," })",""," function fetchHeader(chunk) {"," if (bufferJoiner.length + chunk.length &gt;= 9) {"," var header = bufferJoiner.add(chunk).join()"," eventLength = header.readUInt32BE(0)"," messageLength = header.readUInt32BE(4)"," messagetype = header.readInt8(8)"," fetchBody(chunk.slice(9))"," } else {"," bufferJoiner.add(chunk)"," }"," }",""," function fetchBody(chunk) {"," var raw, event, data"," var chunkLength = chunk.length"," var bytesLeft = (eventLength + messageLength) - bufferJoiner.length",""," if (chunkLength &gt;= bytesLeft) {"," raw = bufferJoiner.add(chunk.slice(0, bytesLeft)).join()"," event = JSON.parse(raw.slice(0, eventLength))"," data = messagetype ? raw.slice(eventLength) : JSON.parse(raw.slice(eventLength).toString())",""," eventLength = -1"," messageLength = -1",""," self.emit(['data'].concat(event), data)",""," if (chunkLength - bytesLeft) {"," fetchHeader(chunk.slice(bytesLeft))"," }",""," return"," }",""," bufferJoiner.add(chunk)"," }",""," self.socket.on('close', function onClose(hadError) {"," self.socket = undefined"," self.connected = false",""," if (hadError) {"," self.emit('close', hadError, arguments[1])"," } else {"," self.emit('close')"," }",""," self.retry &amp;&amp; self.reconnect()"," })",""," self.socket.on('error', function (err) {"," !self.retry &amp;&amp; self.emit('error', err || new Error('An Unknown Error occured'))"," })",""," self.socket.on('timeout', function onIdle() {"," self.emit('idle')"," self.timeout &amp;&amp; self.socket.setTimeout(this.timeout)"," })","}"];
105 lib/common.js
... ... @@ -1,105 +0,0 @@
1   -/*
2   - * common.js
3   - *
4   - * (C) 2011, Nodejitsu Inc.
5   - */
6   -
7   -var fs = require('fs'),
8   - tls = require('tls'),
9   - net = require('net'),
10   - crypto = require('crypto');
11   -
12   -exports.createSocket = function (options) {
13   - options = options || {};
14   - options.type = options.type || 'tcp4';
15   -
16   - return options.type === 'tls'
17   - ? exports.createTlsSocket(options)
18   - : new net.Socket(options);
19   -};
20   -
21   -//
22   -// ### function createTlsSocket (options)
23   -// #### @options {Object} Tls options like in tls.js
24   -// #### Should behave like tls.connect, except it just creates the socket like net.Socket
25   -// #### Also has a function called 'connect' that will allow` it to connect to a remote host
26   -// this is a rip of tls.js's connect
27   -//
28   -exports.createTlsSocket = function(options) {
29   - var self = this;
30   -
31   - //
32   - // Setup the TLS connection over the existing TCP connection:
33   - //
34   - // 1. Create a new instance of `net.Socket`.
35   - // 2. Create a new set of credentials with `options`.
36   - // 3. Create the TLS pair
37   - // 4. Pipe the TLS pair to the TCP socket
38   - //
39   - var socket = new net.Stream({ type: 'tcp4' });
40   -
41   - function setupTlsPipe () {
42   - var sslcontext = crypto.createCredentials(options),
43   - pair = tls.createSecurePair(sslcontext, false),
44   - cleartext = pipe(pair, socket);
45   -
46   - pair.on('secure', function() {
47   - var verifyError = pair.ssl.verifyError();
48   -
49   - if (verifyError) {
50   - cleartext.authorized = false;
51   - cleartext.authorizationError = verifyError;
52   - }
53   - else {
54   - cleartext.authorized = true;
55   - }
56   - });
57   -
58   - //
59   - // Setup the cleartext stream to have a `.connect()` method
60   - // which passes through to the underlying TCP socket.
61   - //
62   - socket.cleartext = cleartext;
63   - cleartext._controlReleased = true;
64   - }
65   -
66   - socket.on('connect', setupTlsPipe);
67   -
68   - return socket;
69   -};
70   -
71   -//
72   -// helper function for createTlsSocket
73   -//
74   -function pipe(pair, socket) {
75   - pair.encrypted.pipe(socket);
76   - socket.pipe(pair.encrypted);
77   -
78   - pair.fd = socket.fd;
79   - var cleartext = pair.cleartext;
80   - cleartext.socket = socket;
81   - cleartext.encrypted = pair.encrypted;
82   - cleartext.authorized = false;
83   -
84   - function onerror(e) {
85   - if (cleartext._controlReleased) {
86   - cleartext.emit('error', e);
87   - }
88   - }
89   -
90   - function onclose() {
91   - socket.removeListener('error', onerror);
92   - socket.removeListener('close', onclose);
93   - socket.removeListener('timeout', ontimeout);
94   - }
95   -
96   - function ontimeout() {
97   - cleartext.emit('timeout');
98   - }
99   -
100   - socket.on('error', onerror);
101   - socket.on('close', onclose);
102   - socket.on('timeout', ontimeout);
103   -
104   - return cleartext;
105   -}
687 lib/nssocket.js
... ... @@ -1,553 +1,286 @@
1   -/*
2   - * nssocket.js - Wraps a TLS/TCP socket to emit namespace events also auto-buffers.
3   - *
4   - * (C) 2011, Nodejitsu Inc.
5   - *
6   - */
7   -
8 1 var net = require('net'),
9 2 tls = require('tls'),
10 3 util = require('util'),
11   - events2 = require('eventemitter2'),
12   - BufferJoiner = require('bufferjoiner'),
13   - common = require('./common');
14   -
15   -//
16   -// ### function NsSocket (socket, options)
17   -// #### @socket {Object} TCP or TLS 'socket' either from a 'connect' 'new' or from a server
18   -// #### @options {Object} Options for this NsSocket
19   -// NameSpace Socket, NsSocket, is a thin wrapper above TLS/TCP.
20   -// It provides automatic buffering and name space based data emits.
21   -//
22   -var NsSocket = exports.NsSocket = function (socket, options) {
  4 + assert = require('chai').assert,
  5 + EventEmitter2 = require('eventemitter2').EventEmitter2,
  6 + bufferjoiner = require('bufferjoiner')
  7 +
  8 +module.exports = NsSocket
  9 +module.exports.createServer = function createServer(options, connectionListener) {
  10 + if (!connectionListener && typeof options === 'function') {
  11 + connectionListener = options
  12 + options = {}
  13 + }
  14 +
  15 + options.type = options.type || 'tcp4'
  16 + options.delimiter = options.delimiter || '::'
  17 +
  18 + function onConnection (socket) {
  19 + options.reconnect = false
  20 + connectionListener(new NsSocket(options, socket))
  21 + }
  22 +
  23 + return options.type === 'tls'
  24 + ? tls.createServer(options, onConnection)
  25 + : net.createServer(options, onConnection)
  26 +}
  27 +
  28 +// retro compatibility fixes
  29 +module.exports.data = module.exports.ondata
  30 +module.exports.unData = module.exports.offdata
  31 +module.exports.dataOnce = module.exports.oncedata
  32 +
  33 +function NsSocket(options, socket) {
23 34 if (!(this instanceof NsSocket)) {
24   - return new NsSocket(socket, options);
  35 + return new NsSocket(options, socket)
25 36 }
26 37
27   - //
28   - // If there is no Socket instnace to wrap,
29   - // create one.
30   - //
31 38 if (!options) {
32   - options = socket;
33   - socket = common.createSocket(options);
  39 + options = socket || {}
34 40 }
35 41
36   - //
37   - // Options should be
38   - //
39   - // {
40   - // type : 'tcp' or 'tls',
41   - // delimiter : '::', delimiter that separates between segments
42   - // msgLength : 3 //number of segments in a complete message
43   - // }
44   - //
45   - options = options || {};
46   -
47   - var self = this,
48   - startName;
49   -
50   - //
51   - // Setup underlying socket state.
52   - //
53   - this.socket = socket;
54   - this.connected = options.connected || socket.writable && socket.readable || false;
55   -
56   - //
57   - // Setup reconnect options.
58   - //
59   - this._reconnect = options.reconnect || false;
60   - this.retry = {
61   - retries: 0,
62   - max: options.maxRetries || 10,
  42 + this.connected = false
  43 + this.type = options.type || 'tcp4'
  44 + this.retry = options.reconnect ? {
  45 + retries: 0,
  46 + max: options.maxRetries || 10,
63 47 interval: options.retryInterval || 5000,
64   - wait: options.retryInterval || 5000
65   - };
66   -
67   - //
68   - // Setup default instance variables.
69   - //
70   - this._options = options;
71   - this._type = options.type || 'tcp4',
72   - this._delimiter = options.delimiter || '::';
73   -
74   - events2.EventEmitter2.call(this, {
75   - delimiter: this._delimiter,
  48 + wait: options.retryInterval || 5000
  49 + } : false
  50 +
  51 + EventEmitter2.call(this, {
  52 + delimiter: options.delimiter || '::',
76 53 wildcard: true,
77 54 maxListeners: options.maxListeners || 10
78   - });
79   -
80   - // Initializing parsing holders
81   - this._eventLength = -1;
82   - this._messageLength = -1;
83   - this._messagetype = 0;
84   - this._bufferJoiner = new BufferJoiner();
85   -
86   - this._setup();
87   -};
88   -
89   -//
90   -// Inherit from `events2.EventEmitter2`.
91   -//
92   -util.inherits(NsSocket, events2.EventEmitter2);
93   -
94   -//
95   -// ### function createServer (options, connectionListener)
96   -// #### @options {Object} **Optional**
97   -// Creates a new TCP/TLS server which wraps every incoming connection
98   -// in an instance of `NsSocket`.
99   -//
100   -exports.createServer = function createServer(options, connectionListener) {
101   - if (!connectionListener && typeof options === 'function') {
102   - connectionListener = options;
103   - options = {};
  55 + })
  56 +
  57 + if (socket) {
  58 + this.stream = socket
  59 + this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket
  60 + this.connected = this.socket.writable && this.socket.readable || false
  61 + configureEvents(this)
104 62 }
  63 +}
105 64
106   - options.type = options.type || 'tcp4';
107   - options.delimiter = options.delimiter || '::';
  65 +util.inherits(NsSocket, EventEmitter2)
108 66
109   - function onConnection (socket) {
  67 +NsSocket.prototype.connect = function connect(port) {
  68 + if (!this.socket) {
  69 + var module = this.type === 'tls' ? tls : net
110 70
111   - //
112   - // Incoming socket connections cannot reconnect
113   - // by definition.
114   - //
115   - options.reconnect = false;
116   - connectionListener(new NsSocket(socket, options));
  71 + this.stream = module.connect.apply(null, arguments)
  72 + this.socket = this.stream instanceof net.Socket ? this.stream : this.stream.socket
  73 + this.connected = this.socket.writable && this.socket.readable || false
  74 + this.connectionArgs = arguments
  75 +
  76 + configureEvents(this)
  77 + } else {
  78 + this.socket.connect.apply(this.socket, arguments)
117 79 }
  80 + return this
  81 +}
  82 +
  83 +NsSocket.prototype.write = function write(buff) {
  84 + this.stream.write(buff)
  85 +}
118 86
119   - return options.type === 'tls'
120   - ? tls.createServer(options, onConnection)
121   - : net.createServer(options, onConnection);
122   -};
123   -
124   -// exports.createConnection = exports.connect = function connect(options, port, host, callback) {
125   -// return new NsSocket(options).connect(port, port, host, callback);
126   -// };
127   -
128   -//
129   -// ### function send (data, callback)
130   -// #### @event {Array|string} The array (or string) that holds the event name
131   -// #### @data {Literal|Object|Buffer} The data to be sent with the event.
132   -// #### @callback {Function} the callback function when send is done sending
133   -// The send function follows write/send rules for TCP/TLS/UDP
134   -// in that the callback is called when sending is complete, not when delivered
135   -//
136 87 NsSocket.prototype.send = function send(event, data, callback) {
137 88 // if we aren't connected/socketed, then error
138 89 if (!this.socket || !this.connected) {
139   - return this.emit('error', new Error('NsSocket: sending on a bad socket'));
140   - }
141   -
142   - // rebinds
143   - if (typeof event === 'string') {
144   - event = event.split(this._delimiter);
  90 + return this.emit('error', new Error('NsSocket: sending on a bad socket'))
145 91 }
146 92
147 93 var dataType = typeof data
148 94 if (dataType === 'undefined' || dataType === 'function') {
149   - callback = data;
150   - data = null;
  95 + callback = data
  96 + data = null
151 97 }
152 98
153   - var message = this.createMessage(event, data);
  99 + this.stream.write(this.createMessage(event, data), callback)
  100 +}
154 101
155   - // now actually write to the socket
156   - if (this.socket.cleartext) {
157   - this.socket.cleartext.write(message, callback);
158   - } else {
159   - this.socket.write(message, callback);
160   - }
161   -};
  102 +NsSocket.prototype.createMessage = function createMessage(event, data) {
  103 + var header = new Buffer(9)
162 104
163   -//
164   -// ### function _createMessage (event, data)
165   -// #### @event {Array|string} The array (or string) that holds the event name
166   -// #### @data {Literal|Object|Buffer} The data to be sent with the event.
167   -// Returns a packaged binary message ready to be written to the socket.
168   -//
169   -NsSocket.prototype.createMessage = function _createMessage(event, data) {
170   - var header = new Buffer(9);
  105 + if (typeof event === 'string') {
  106 + event = event.split(this.delimiter)
  107 + }
171 108
172   - event = Buffer(JSON.stringify(event));
  109 + event = Buffer(JSON.stringify(event))
173 110
174 111 if (Buffer.isBuffer(data)) {
175   - header.writeInt8(1, 8);
  112 + header.writeInt8(1, 8)
176 113 } else {
177   - data = Buffer(JSON.stringify(data));
178   - header.writeInt8(0, 8);
  114 + data = Buffer(JSON.stringify(data))
  115 + header.writeInt8(0, 8)
179 116 }
180 117
181   - header.writeUInt32BE(event.length, 0);
182   - header.writeUInt32BE(data.length, 4);
  118 + header.writeUInt32BE(event.length, 0)
  119 + header.writeUInt32BE(data.length, 4)
183 120
184   - return Buffer.concat([header, event, data], 9 + event.length + data.length);
  121 + return Buffer.concat([header, event, data], 9 + event.length + data.length)
185 122 }
186 123
187   -//
188   -// ### function data (event, callback)
189   -// #### @event {Array|string} Namespaced `data` event to listen to.
190   -// #### @callback {function} Continuation to call when the event is raised.
191   -// Shorthand function for listening to `['data', '*']` events.
192   -//
193   -NsSocket.prototype.data = function (event, callback) {
  124 +NsSocket.prototype.ondata = function (event, listener) {
194 125 if (typeof event === 'string') {
195   - event = event.split(this._delimiter);
  126 + event = event.split(this.delimiter)
196 127 }
  128 + return this.on(['data'].concat(event), listener)
  129 +}
197 130
198   - this.on(['data'].concat(event), callback);
199   -};
200   -
201   -NsSocket.prototype.undata = function (event, listener) {
202   - this.off(['data'].concat(event), listener);
203   -};
  131 +NsSocket.prototype.offdata = function (event, listener) {
  132 + return this.off(['data'].concat(event), listener)
  133 +}
204 134
205   -//
206   -// ### function data (event, callback)
207   -// #### @event {Array|string} Namespaced `data` event to listen to once.
208   -// #### @callback {function} Continuation to call when the event is raised.
209   -// Shorthand function for listening to `['data', '*']` events once.
210   -//
211   -NsSocket.prototype.dataOnce = function (event, callback) {
  135 +NsSocket.prototype.oncedata = function (event, listener) {
212 136 if (typeof event === 'string') {
213   - event = event.split(this._delimiter);
  137 + event = event.split(this.delimiter)
214 138 }
  139 + return this.once(['data'].concat(event), listener)
  140 +}
  141 +
  142 +NsSocket.prototype.setIdle = function setIdle(timeout) {
  143 + this.socket.setTimeout(timeout)
  144 + this.timeout = timeout
  145 +}
215 146
216   - this.once(['data'].concat(event), callback);
217   -};
218   -
219   -//
220   -// ### function setIdle (time, callback)
221   -// #### @time {Integer} how often to emit idle
222   -// Set the idle/timeout timer
223   -//
224   -NsSocket.prototype.setIdle = function setIdle(time) {
225   - this.socket.setTimeout(time);
226   - this._timeout = time;
227   -};
228   -
229   -//
230   -// ### function destroy (void)
231   -// #### forcibly destroys this nsSocket, unregister socket, remove all callbacks
232   -//
233 147 NsSocket.prototype.destroy = function destroy() {
234   - // this should be forcibly remove EVERY listener
235   - this.removeAllListeners();