client.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import events from 'events';
  2. import WebSocket from 'faye-websocket';
  3. import objectAssign from 'object-assign';
  4. const debug = require('debug')('tinylr:client');
  5. let idCounter = 0;
  6. export default class Client extends events.EventEmitter {
  7. constructor (req, socket, head, options = {}) {
  8. super();
  9. 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. message (event) {
  16. let data = this.data(event);
  17. if (this[data.command]) return this[data.command](data);
  18. }
  19. close (event) {
  20. if (this.ws) {
  21. this.ws.close();
  22. this.ws = null;
  23. }
  24. this.emit('end', event);
  25. }
  26. // Commands
  27. hello () {
  28. this.send({
  29. command: 'hello',
  30. protocols: [
  31. 'http://livereload.com/protocols/official-7'
  32. ],
  33. serverName: 'tiny-lr'
  34. });
  35. }
  36. info (data) {
  37. if (data) {
  38. debug('Info', data);
  39. this.emit('info', objectAssign({}, data, { id: this.id }));
  40. this.plugins = data.plugins;
  41. this.url = data.url;
  42. }
  43. return objectAssign({}, data || {}, { id: this.id, url: this.url });
  44. }
  45. // Server commands
  46. reload (files) {
  47. files.forEach(function (file) {
  48. this.send({
  49. command: 'reload',
  50. path: file,
  51. liveCSS: this.options.liveCSS !== false,
  52. reloadMissingCSS: this.options.reloadMissingCSS !== false,
  53. liveImg: this.options.liveImg !== false
  54. });
  55. }, this);
  56. }
  57. alert (message) {
  58. this.send({
  59. command: 'alert',
  60. message: message
  61. });
  62. }
  63. // Utilities
  64. data (event) {
  65. let data = {};
  66. try {
  67. data = JSON.parse(event.data);
  68. } catch (e) {}
  69. return data;
  70. }
  71. send (data) {
  72. if (!this.ws) return;
  73. this.ws.send(JSON.stringify(data));
  74. }
  75. uniqueId (prefix) {
  76. let id = idCounter++;
  77. return prefix ? prefix + id : id;
  78. }
  79. }