forked from kriskowal/q-connection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapt.js
83 lines (76 loc) · 2.36 KB
/
adapt.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
var Q = require("q");
var Queue = require("q/queue");
// Coerces a Worker to a Connection
// Idempotent: Passes Connections through unaltered
module.exports = adapt;
function adapt(port, origin) {
var send;
// Adapt the sender side
// ---------------------
if (port.postMessage) {
// MessagePorts
send = function (message) {
// some message ports require an "origin"
port.postMessage(message, origin);
};
} else if (port.send) {
// WebSockets have a "send" method, indicating
// that we cannot send until the connection has
// opened. We change the send method into a
// promise for the send method, resolved after
// the connection opens, rejected if it closes
// before it opens.
var deferred = Q.defer();
send = deferred.promise;
if (port.on) {
deferred.resolve(port.send);
} else if (port.addEventListener) {
port.addEventListener("open", function () {
deferred.resolve(port.send);
});
port.addEventListener("close", function () {
queue.close();
deferred.reject("Connection closed.");
});
}
} else if (port.get && port.put) {
return port;
} else {
throw new Error("An adaptable message port required");
}
// Adapt the receiver side
// -----------------------
// onmessage is one thing common between WebSocket and
// WebWorker message ports.
var queue = Queue();
if (port.on) {
port.on("message", function (data) {
queue.put(data);
}, false);
} else if (port.addEventListener) {
port.addEventListener("message", function (event) {
queue.put(event.data);
}, false);
} else {
port.onmessage = function (event) {
queue.put(event.data);
};
}
// Message ports have a start method; call it to make sure
// that messages get sent.
if (port.start) {
port.start();
}
var close = function () {
port.close && port.close();
return queue.close();
};
return {
"get": queue.get,
"put": function (message) {
return Q.invoke(send, "call", port, message);
},
"close": close,
"closed": queue.closed
};
}