-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
112 lines (87 loc) · 2.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var Stream = require('stream'),
rucksack = require('rucksack'),
Parser = require('./lib/parser'),
assemble = require('./lib/assemble');
function wrap(stream) {
var functions = [],
incoming = [],
seal = [],
parser;
function send(method, a, b) {
if (stream.writable) {
assemble(stream, method, a, b);
}
}
function pack(value) {
return rucksack.pack(value, function(val, out) {
var ref;
if (val instanceof Function) {
ref = functions.indexOf(val);
if (ref === -1) {
ref = seal.length;
functions.push(val);
}
out.writeByte(0xba);
out.writeVarint(ref);
return false;
} else if (val instanceof Stream) {
ref = seal.indexOf(val);
if (ref === -1) {
ref = seal.length;
function data(chunk) { send('data', ref, chunk); }
function end() { send('end', ref); }
val.on('data', data);
val.on('end', end);
function cleanup() {
val.removeListener('data', data);
val.removeListener('end', end);
}
seal.push(cleanup);
}
out.writeByte(0xbb);
out.writeVarint(ref);
return false;
}
});
}
function unpack(buffer) {
return rucksack.unpack(buffer, function(byte, input) {
var ref;
if (byte === 0xba) {
ref = input.readVarint();
return function() {
var args = Array.prototype.slice.call(arguments);
send('call', ref, pack(args));
};
} else if (byte === 0xbb) {
ref = input.readVarint();
return incoming[ref] = new Stream();
}
});
}
parser = new Parser(stream);
parser.on('message', function(buf) {
stream.emit('message', unpack(buf));
});
parser.on('call', function(ref, buf) {
var fn = functions[ref];
fn.apply(fn, unpack(buf));
});
parser.on('data', function(ref, buf) {
//console.log(':: ' + ref);
incoming[ref].emit('data', buf);
});
parser.on('end', function(ref, buf) {
incoming[ref].emit('end');
incoming[ref] = null;
});
parser.on('seal', function(ref, buf) {
seal[ref]();
seal[ref] = null;
});
stream.send = function(value) {
send('message', pack(value));
};
return stream;
}
module.exports = wrap;