Skip to content

Commit

Permalink
improve code readability
Browse files Browse the repository at this point in the history
  • Loading branch information
smhg committed Jul 27, 2020
1 parent 7b60dcb commit f118bc9
Show file tree
Hide file tree
Showing 9 changed files with 211 additions and 91 deletions.
2 changes: 2 additions & 0 deletions src/connector.js
Expand Up @@ -121,6 +121,7 @@ class Connector {
_closeOnError () {
this._handshakeTimeout.stop();
this._disconnectionReason = 'error';

return this.socket.close();
}

Expand All @@ -130,6 +131,7 @@ class Connector {

// start handshake
const hello = { command: 'hello', protocols: [PROTOCOL_6, PROTOCOL_7] };

hello.ver = VERSION;

if (this.options.ext) {
Expand Down
11 changes: 8 additions & 3 deletions src/customevents.js
Expand Up @@ -2,21 +2,26 @@ const CustomEvents = {
bind (element, eventName, handler) {
if (element.addEventListener) {
return element.addEventListener(eventName, handler, false);
} else if (element.attachEvent) {
}

if (element.attachEvent) {
element[eventName] = 1;

return element.attachEvent('onpropertychange', function (event) {
if (event.propertyName === eventName) {
return handler();
}
});
} else {
throw new Error(`Attempt to attach custom event ${eventName} to something which isn't a DOMElement`);
}

throw new Error(`Attempt to attach custom event ${eventName} to something which isn't a DOMElement`);
},
fire (element, eventName) {
if (element.addEventListener) {
const event = document.createEvent('HTMLEvents');

event.initEvent(eventName, true, true);

return document.dispatchEvent(event);
} else if (element.attachEvent) {
if (element[eventName]) {
Expand Down
3 changes: 3 additions & 0 deletions src/less.js
Expand Up @@ -20,13 +20,16 @@ class LessPlugin {

reloadLess (path) {
let link;

const links = ((() => {
const result = [];

for (link of Array.from(document.getElementsByTagName('link'))) {
if ((link.href && link.rel.match(/^stylesheet\/less$/i)) || (link.rel.match(/stylesheet/i) && link.type.match(/^text\/(x-)?less$/i))) {
result.push(link);
}
}

return result;
})());

Expand Down
35 changes: 22 additions & 13 deletions src/livereload.js
Expand Up @@ -29,20 +29,25 @@ class LiveReload {
// i can haz sockets?
if (!(this.WebSocket = this.window.WebSocket || this.window.MozWebSocket)) {
this.console.error('LiveReload disabled because the browser does not seem to support web sockets');

return;
}

// i can haz options?
if ('LiveReloadOptions' in window) {
this.options = new Options();

for (const k of Object.keys(window.LiveReloadOptions || {})) {
const v = window.LiveReloadOptions[k];

this.options.set(k, v);
}
} else {
this.options = Options.extract(this.window.document);

if (!this.options) {
this.console.error('LiveReload disabled because it could not find its own <SCRIPT> tag');

return;
}
}
Expand Down Expand Up @@ -82,6 +87,7 @@ class LiveReload {
if (typeof this.listeners.disconnect === 'function') {
this.listeners.disconnect();
}

switch (reason) {
case 'cannot-connect':
return this.log(`LiveReload cannot connect to ${this.options.host}:${this.options.port}, will retry in ${nextDelay} sec.`);
Expand Down Expand Up @@ -144,6 +150,7 @@ class LiveReload {

this.connector.disconnect();
this.log('LiveReload disconnected.');

return (typeof this.listeners.shutdown === 'function' ? this.listeners.shutdown() : undefined);
}

Expand All @@ -162,19 +169,20 @@ class LiveReload {

this.pluginIdentifiers[PluginClass.identifier] = true;

const plugin = new PluginClass(this.window, {

// expose internal objects for those who know what they're doing
// (note that these are private APIs and subject to change at any time!)
_livereload: this,
_reloader: this.reloader,
_connector: this.connector,

// official API
console: this.console,
Timer,
generateCacheBustUrl: url => this.reloader.generateCacheBustUrl(url)
}
const plugin = new PluginClass(
this.window,
{
// expose internal objects for those who know what they're doing
// (note that these are private APIs and subject to change at any time!)
_livereload: this,
_reloader: this.reloader,
_connector: this.connector,

// official API
console: this.console,
Timer,
generateCacheBustUrl: url => this.reloader.generateCacheBustUrl(url)
}
);

// API that PluginClass can/must provide:
Expand Down Expand Up @@ -213,6 +221,7 @@ class LiveReload {

for (const plugin of this.plugins) {
var pluginData = (typeof plugin.analyze === 'function' ? plugin.analyze() : undefined) || {};

pluginsData[plugin.constructor.identifier] = pluginData;
pluginData.version = plugin.constructor.version;
}
Expand Down
11 changes: 8 additions & 3 deletions src/options.js
Expand Up @@ -13,6 +13,7 @@ class Options {
this.handshake_timeout = 5000;

var pluginOrder = [];

Object.defineProperty(this, 'pluginOrder', {
get () { return pluginOrder; },
set (v) { pluginOrder.push.apply(pluginOrder, v.split(/[,;]/)); }
Expand All @@ -34,13 +35,17 @@ class Options {

Options.extract = function (document) {
for (const element of Array.from(document.getElementsByTagName('script'))) {
var m; var mm;
var src = element.src; var srcAttr = element.getAttribute('src');
var src = element.src;
var srcAttr = element.getAttribute('src');
var lrUrlRegexp = /^([^:]+:\/\/([^/:]+)(?::(\d+))?\/|\/\/|\/)?([^/].*\/)?z?livereload\.js(?:\?(.*))?$/;
// ^proto:// ^host ^port ^// ^/ ^folder
var lrUrlRegexpAttr = /^(?:(?:([^:/]+)?:?)\/{0,2})([^:]+)(?::(\d+))?/;
// ^proto ^host/folder ^port
if ((m = src.match(lrUrlRegexp)) && (mm = srcAttr.match(lrUrlRegexpAttr))) {

var m = src.match(lrUrlRegexp);
var mm = srcAttr.match(lrUrlRegexpAttr);

This comment has been minimized.

Copy link
@caseywebdev

caseywebdev Jul 28, 2020

This introduced a bug for <script> tags without a src attribute. element.src is an empty string, but element.getAttribute('src') is null. By rearranging this, mm = srcAttr.match(...) is now run regardless of weather m = ... is truthy or not, and fails with TypeError: null is not an object (evaluating 'srcAttr.match').

This comment has been minimized.

Copy link
@smhg

smhg Jul 28, 2020

Author Contributor

You're absolutely right. I've reverted this change (released as 3.3.1).

This comment has been minimized.

Copy link
@caseywebdev

caseywebdev Jul 28, 2020

Thanks, I appreciate the quick response!


if (m && mm) {
const [, , host, port, , params] = m;
const [, , , portFromAttr] = mm;
const options = new Options();
Expand Down
20 changes: 13 additions & 7 deletions src/protocol.js
Expand Up @@ -21,6 +21,7 @@ class Parser {
process (data) {
try {
let message;

if (!this.protocol) {
if (data.match(new RegExp('^!!ver:([\\d.]+)$'))) {
this.protocol = 6;
Expand All @@ -37,12 +38,17 @@ class Parser {
}

return this.handlers.connected(this.protocol);
} else if (this.protocol === 6) {
}

if (this.protocol === 6) {
message = JSON.parse(data);

if (!message.length) {
throw new ProtocolError('protocol 6 messages must be arrays');
}

const [command, options] = Array.from(message);

if (command !== 'refresh') {
throw new ProtocolError('unknown protocol 6 command');
}
Expand All @@ -52,17 +58,17 @@ class Parser {
path: options.path,
liveCSS: options.apply_css_live != null ? options.apply_css_live : true
});
} else {
message = this._parseMessage(data, ['reload', 'alert']);

return this.handlers.message(message);
}

message = this._parseMessage(data, ['reload', 'alert']);

return this.handlers.message(message);
} catch (e) {
if (e instanceof ProtocolError) {
return this.handlers.error(e);
} else {
throw e;
}

throw e;
}
}

Expand Down

0 comments on commit f118bc9

Please sign in to comment.