| 1 |
let PROTOCOL_6, PROTOCOL_7; |
| 2 |
exports.PROTOCOL_6 = (PROTOCOL_6 = 'http://livereload.com/protocols/official-6'); |
| 3 |
exports.PROTOCOL_7 = (PROTOCOL_7 = 'http://livereload.com/protocols/official-7'); |
| 4 |
|
| 5 |
class ProtocolError { |
| 6 |
constructor (reason, data) { |
| 7 |
this.message = `LiveReload protocol error (${reason}) after receiving data: "${data}".`; |
| 8 |
} |
| 9 |
}; |
| 10 |
|
| 11 |
class Parser { |
| 12 |
constructor (handlers) { |
| 13 |
this.handlers = handlers; |
| 14 |
this.reset(); |
| 15 |
} |
| 16 |
|
| 17 |
reset () { |
| 18 |
this.protocol = null; |
| 19 |
} |
| 20 |
|
| 21 |
process (data) { |
| 22 |
try { |
| 23 |
let message; |
| 24 |
if (!this.protocol) { |
| 25 |
if (data.match(new RegExp(`^!!ver:([\\d.]+)$`))) { |
| 26 |
this.protocol = 6; |
| 27 |
} else if ((message = this._parseMessage(data, ['hello']))) { |
| 28 |
if (!message.protocols.length) { |
| 29 |
throw new ProtocolError('no protocols specified in handshake message'); |
| 30 |
} else if (Array.from(message.protocols).includes(PROTOCOL_7)) { |
| 31 |
this.protocol = 7; |
| 32 |
} else if (Array.from(message.protocols).includes(PROTOCOL_6)) { |
| 33 |
this.protocol = 6; |
| 34 |
} else { |
| 35 |
throw new ProtocolError('no supported protocols found'); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
return this.handlers.connected(this.protocol); |
| 40 |
} else if (this.protocol === 6) { |
| 41 |
message = JSON.parse(data); |
| 42 |
if (!message.length) { |
| 43 |
throw new ProtocolError('protocol 6 messages must be arrays'); |
| 44 |
} |
| 45 |
const [command, options] = Array.from(message); |
| 46 |
if (command !== 'refresh') { |
| 47 |
throw new ProtocolError('unknown protocol 6 command'); |
| 48 |
} |
| 49 |
|
| 50 |
return this.handlers.message({ |
| 51 |
command: 'reload', |
| 52 |
path: options.path, |
| 53 |
liveCSS: options.apply_css_live != null ? options.apply_css_live : true |
| 54 |
}); |
| 55 |
} else { |
| 56 |
message = this._parseMessage(data, ['reload', 'alert']); |
| 57 |
|
| 58 |
return this.handlers.message(message); |
| 59 |
} |
| 60 |
} catch (e) { |
| 61 |
if (e instanceof ProtocolError) { |
| 62 |
return this.handlers.error(e); |
| 63 |
} else { |
| 64 |
throw e; |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
_parseMessage (data, validCommands) { |
| 70 |
let message; |
| 71 |
|
| 72 |
try { |
| 73 |
message = JSON.parse(data); |
| 74 |
} catch (e) { |
| 75 |
throw new ProtocolError('unparsable JSON', data); |
| 76 |
} |
| 77 |
|
| 78 |
if (!message.command) { |
| 79 |
throw new ProtocolError('missing "command" key', data); |
| 80 |
} |
| 81 |
|
| 82 |
if (!validCommands.includes(message.command)) { |
| 83 |
throw new ProtocolError(`invalid command '${message.command}', only valid commands are: ${validCommands.join(', ')})`, data); |
| 84 |
} |
| 85 |
|
| 86 |
return message; |
| 87 |
} |
| 88 |
}; |
| 89 |
|
| 90 |
exports.ProtocolError = ProtocolError; |
| 91 |
exports.Parser = Parser; |