UNPKG

1.75 kBJavaScriptView Raw
1
2var util = require('util');
3var events = require('events');
4var WebSocket = require('faye-websocket');
5
6module.exports = Client;
7
8function Client(req, socket, head, options) {
9 options = this.options = options || {};
10 this.ws = new WebSocket(req, socket, head);
11 this.ws.onmessage = this.message.bind(this);
12 this.ws.onclose = this.close.bind(this);
13 this.id = this.uniqueId('ws');
14}
15
16util.inherits(Client, events.EventEmitter);
17
18Client.prototype.message = function message(event) {
19 var data = this.data(event);
20 if(this[data.command]) return this[data.command](data);
21};
22
23Client.prototype.close = function close(event) {
24 if(this.ws) {
25 this.ws.close();
26 this.ws = null;
27 }
28
29 this.emit('end', event);
30};
31
32// Commands
33
34Client.prototype.hello = function hello() {
35 this.send({
36 command: 'hello',
37 protocols: [
38 'http://livereload.com/protocols/official-7'
39 ],
40 serverName: 'tiny-lr'
41 });
42};
43
44Client.prototype.info = function info(data) {
45 this.plugins = data.plugins;
46 this.url = data.url;
47};
48
49// Server commands
50
51Client.prototype.reload = function reload(files) {
52 files.forEach(function(file) {
53 this.send({
54 command: 'reload',
55 path: file,
56 liveCSS: this.options.liveCSS !== false,
57 liveJs: this.options.liveJs !== false,
58 liveImg: this.options.liveImg !== false
59 });
60 }, this);
61};
62
63// Utilities
64
65Client.prototype.data = function _data(event) {
66 var data = {};
67 try {
68 data = JSON.parse(event.data);
69 } catch (e) {}
70 return data;
71};
72
73Client.prototype.send = function send(data) {
74 this.ws.send(JSON.stringify(data));
75};
76
77var idCounter = 0;
78Client.prototype.uniqueId = function uniqueId(prefix) {
79 var id = idCounter++;
80 return prefix ? prefix + id : id;
81};