Initial commit
[yaffs-website] / node_modules / tiny-lr / lib / client.js
1
2 var util      = require('util');
3 var events    = require('events');
4 var WebSocket = require('faye-websocket');
5
6 module.exports = Client;
7
8 function 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
16 util.inherits(Client, events.EventEmitter);
17
18 Client.prototype.message = function message(event) {
19   var data = this.data(event);
20   if(this[data.command]) return this[data.command](data);
21 };
22
23 Client.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
34 Client.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
44 Client.prototype.info = function info(data) {
45   this.plugins = data.plugins;
46   this.url = data.url;
47 };
48
49 // Server commands
50
51 Client.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
65 Client.prototype.data = function _data(event) {
66   var data = {};
67   try {
68     data = JSON.parse(event.data);
69   } catch (e) {}
70   return data;
71 };
72
73 Client.prototype.send = function send(data) {
74   this.ws.send(JSON.stringify(data));
75 };
76
77 var idCounter = 0;
78 Client.prototype.uniqueId = function uniqueId(prefix) {
79   var id = idCounter++;
80   return prefix ? prefix + id : id;
81 };