-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.js
350 lines (290 loc) · 9.04 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"use strict";
var _ = require('lodash'),
through = require('through2'),
gutil = require('gulp-util'),
glogg = require('glogg'),
http = require('http'),
https = require('https'),
inject = require('connect-inject'),
connect = require('connect'),
proxy = require('proxy-middleware'),
watch = require('node-watch'),
fs = require('fs'),
serveIndex = require('serve-index'),
serveStatic = require('serve-static'),
path = require('path'),
open = require('open'),
enableMiddlewareShorthand = require('./enableMiddlewareShorthand'),
socket = require('socket.io'),
url = require('url'),
extend = require('node.extend');
var BROWSER_SCIPTS_DIR = path.join(__dirname, 'browser-scripts');
var levels = [
'error',
'warn',
'info',
'debug',
];
var instanceNumber = 0;
function bindLogger(logLevel, kind) {
var logger = glogg('gulp-server-livereload-' + kind + '-' + instanceNumber);
logLevel = levels.indexOf(logLevel) + 1;
if (!logLevel) {
throw 'Logging level "' + logLevel + '" does not exist!';
}
levels
.filter(function (item, i) {
return i < logLevel;
})
.forEach(function (level) {
logger.on(level, function () {
gutil.log.apply(gutil.log, arguments);
});
});
return logger;
}
module.exports = function(options) {
var defaults = {
/**
*
* BASIC DEFAULTS
*
**/
host: 'localhost',
port: 8000,
defaultFile: 'index.html',
fallback: null,
fallbackLogic: function(req, res, fallbackFile) {
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
fs.createReadStream(fallbackFile).pipe(res);
},
https: false,
open: false,
log: 'info',
clientLog: 'debug',
/**
*
* MIDDLEWARE DEFAULTS
*
* NOTE:
* All middleware should defaults should have the 'enable'
* property if you want to support shorthand syntax like:
*
* webserver({
* livereload: true
* });
*
*/
// Middleware: Livereload
livereload: {
enable: false,
markupHost: null,
port: 35729,
filter: function(filename, cb) {
cb( !(/node_modules/.test(filename)) );
},
clientConsole: false,
},
// Middleware: Directory listing
// For possible options, see:
// https://github.com/expressjs/serve-index
directoryListing: {
enable: false,
path: './',
options: undefined
},
// Middleware: Proxy
// For possible options, see:
// https://github.com/andrewrk/connect-proxy
proxies: []
};
// Deep extend user provided options over the all of the defaults
// Allow shorthand syntax, using the enable property as a flag
var config = enableMiddlewareShorthand(defaults, options, ['directoryListing', 'livereload']);
var logger = bindLogger(config.log, 'server');
var clientLogger = bindLogger(config.clientLog, 'client');
instanceNumber += 1;
var httpsOptions = {
key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
};
var openInBrowser = function () {
if (config.open === false) return;
open('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port);
openInBrowser = undefined;
};
// connect app
var app = connect();
// Disable browser cache(fix #15)
app.use(function (req, res, next) {
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", 0);
next();
});
// Proxy requests
for (var i = 0, len = config.proxies.length; i < len; i++) {
var proxyoptions = url.parse(config.proxies[i].target);
if (config.proxies[i].hasOwnProperty('options')) {
extend(proxyoptions, config.proxies[i].options);
}
proxyoptions.route = config.proxies[i].source;
app.use(proxy(proxyoptions));
logger.debug(config.proxies[i].source + ' is proxied.');
}
// directory listing
if (config.directoryListing.enable) {
app.use(serveIndex(path.resolve(config.directoryListing.path), config.directoryListing.options));
}
// socket.io
if (config.livereload.enable) {
var snippetParams = [];
if (config.livereload.clientConsole) {
snippetParams.push("extra=capture-console");
}
// If it wasn't provided, use the server host:
var markupHost = !!_.get(config.livereload.markupHost, 'length')
? "'" + config.livereload.markupHost + "'"
: null;
var snippet =
"<script type=\"text/javascript\">"
+ "var _lrscript = document.createElement('script');"
+ "_lrscript.type = 'text/javascript';"
+ "_lrscript.defer = _lrscript.async = true;"
+ "_lrscript.src = '//' + ((" + markupHost + "||location.host).split(':')[0]) + ':"+config.livereload.port+"/livereload.js?"+snippetParams.join('&')+"';"
+ "document.body.appendChild(_lrscript);"
+ "</script>";
var prepend = function(w, s) {
return s + w;
};
var append = function(w, s) {
return w + s;
}
app.use(inject({
snippet: snippet,
rules: [{
match: /<\/body>/,
fn: prepend
}, {
match: /<\/html>/,
fn: prepend
}, {
match: /<\!DOCTYPE.+>/,
fn: append
}]
}));
var io = config.livereload.io = socket();
io.serveClient(true);
io.path("");
io.on('connection', function(socket){
logger.info('Livereload client connected');
socket.on('console', function(params){
var method = params.method,
data = params.data,
methodLabel = gutil.colors.green(method.toUpperCase()),
translatedMethod = 'info';
switch (method) {
case 'error':
methodLabel = gutil.colors.red('ERROR');
translatedMethod = 'error';
break;
case 'warn':
methodLabel = gutil.colors.yellow('WARN');
translatedMethod = 'warn';
break;
case 'info':
methodLabel = gutil.colors.cyan('INFO');
translatedMethod = 'info';
break;
case 'debug':
case 'trace':
methodLabel = gutil.colors.blue('DEBUG');
translatedMethod = 'debug';
break;
}
var args = ['[Client:' + methodLabel + ']'];
for (var i in data) {
args.push(data[i]);
}
clientLogger[translatedMethod].apply(clientLogger, args);
});
});
var ioApp = connect();
ioApp.use(serveStatic(BROWSER_SCIPTS_DIR, { index: false }));
var ioServerBase = config.https
? https.createServer(httpsOptions, ioApp)
: http.createServer(ioApp);
var ioServer = config.livereload.ioServer =
ioServerBase.listen(config.livereload.port, config.host);
io.attach(ioServer, {
path: '/socket.io'
});
logger.debug('Livereload started at', gutil.colors.gray('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.livereload.port));
}
// http server
var webserver = null;
if (config.https) {
webserver = https.createServer(httpsOptions, app);
}
else {
webserver = http.createServer(app);
}
var files = [];
// Create server
var stream = through.obj(function(file, enc, callback) {
if ('debug' === config.log) {
app.use(function(req, res, next) {
logger.debug(req.method + ' ' + req.url);
next();
});
}
app.use(serveStatic(file.path, {
index: (config.directoryListing.enable ? false : config.defaultFile)
}));
if (config.livereload.enable) {
watch(file.path, function(filename) {
config.livereload.filter(filename, function(shouldReload) {
if (shouldReload) {
logger.debug('Livereload: file changed: ' + filename);
config.livereload.io.sockets.emit('reload');
// Treat changes to sourcemaps as changes to the original files.
filename = filename.replace(/\.map$/, '');
config.livereload.io.sockets.emit('file_changed', {
path: filename,
name: path.basename(filename),
ext: path.extname(filename),
});
}
});
});
}
this.push(file);
callback();
})
.on('data', function(f) {
files.push(f);
// start the web server
webserver.listen(config.port, config.host, openInBrowser);
logger.info('Webserver started at', gutil.colors.cyan('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port));
})
.on('end', function(){
if (config.fallback) {
files.forEach(function(file){
var fallbackFile = file.path + '/' + config.fallback;
if (fs.existsSync(fallbackFile)) {
app.use(function(req, res) {
return config.fallbackLogic(req, res, fallbackFile);
});
}
});
}
});
// once stream killed
stream.on('kill', function() {
webserver.close();
if (config.livereload.enable) {
config.livereload.ioServer.close();
}
});
return stream;
};