-
Notifications
You must be signed in to change notification settings - Fork 0
/
zapp.js
executable file
·331 lines (269 loc) · 7.09 KB
/
zapp.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
#!/usr/bin/env node
"use strict";
const ascii = [
'_____________ ______ ______',
'\\___ /\\__ \\ \\____ \\\\____ \\',
' / / / __ \\| |_> > |_> >',
'/_____ \\(____ / __/| __/',
' \\/ \\/|__| |__| ',
''
].join('\n');
// node modules
const http = require('http');
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
// libs
const chokidar = require('chokidar');
const debounce = require('debounce');
const express = require('express');
const mime = require('mime');
const wsserver = require('ws').Server;
// templating and stuff
const jade = require('jade');
// css
const less = require('less');
const stylus = require('stylus');
// javascript/coffeescript
const Snockets = require('snockets');
const snockets = new Snockets();
// misc
const markdown = require('markdown').markdown;
// arguments
const args = require('minimist')(process.argv.slice(2));
if (args.h) {
console.log([
'Usage: zapp [options] <dir>',
'',
'Arguments:',
' dir The directory zapp serves. Defaults to CWD.',
'',
'Options:',
' -p <port> Port zapp will serve on',
' -u Ugly mode, uglifies JS and Jade.',
' -h Show help'
].join('\n'));
process.exit(0);
}
// config
const port = args.p || 8080;
const serv = args._[0] || process.cwd();
const ugly = args.u || false;
let ignores = [
'**/*.swp',
'**/*.swo'
];
const zappignore = serv + '/.zappignore';
if (fs.existsSync(zappignore)) {
const contents = fs.readFileSync(zappignore, 'utf8');
ignores = contents
.split('\n')
.map(function(line) { return line.trim() })
.filter(function(line) { return line[0] != '#'})
.filter(function(line) { return line != false});
}
// index files
const indexes = [
'index.html',
'index.htm',
'index.jade',
'index.md',
];
// extensions
const extensions = [
'.html',
'.htm',
'.jade',
'.md',
];
// serve a file or return false
function serveFile(filePath, req, res) {
// get the extension
const index = filePath.lastIndexOf('.')
const ext = (index < 0) ? '' : filePath.substr(index).toLowerCase();
// unify common exts
switch(ext) {
case '.markdown':
ext = '.md';
break;
}
// do something based on the extension
switch (ext) {
// jade
case '.jade':
const data = jade.renderFile(filePath, {
pretty: !ugly
});
sendData(data, 'text/html', res);
break;
// markdown
case '.md':
readFile(filePath, res, function(data, mimetype) {
data = markdown.toHTML(data);
data = jade.renderFile(__dirname + '/res/markdown.jade', {rendered: data});
sendData(data, 'text/html', res);
});
break;
// less
case '.less':
readFile(filePath, res, function(data, mimetype) {
less.render(data, function(err, css) {
if (err)
res.send(500);
else
sendData(css, 'text/css', res);
});
});
break;
// stylus
case '.styl':
readFile(filePath, res, function(data, mimetype) {
stylus.render(data, function(err, css) {
if (err) {
res.send(500);
} else {
sendData(css, 'text/css', res);
}
});
});
break;
// javascript
case '.js':
snockets.getConcatenation(filePath, {
minify: ugly
}, function(err, js) {
if (err) {
res.send(500);
} else {
sendData(js, 'text/javascript', res);
}
});
break;
default:
const mimetype = mime.lookup(filePath);
if (mimetype == 'text/html') {
readFile(filePath, res, function(data, mimetype) {
sendData(data, mimetype, res);
});
} else {
res.set('Content-Type', mimetype);
res.sendFile(filePath);
}
break;
}
}
// read a file, respond 500 on failure, otherwise execute a callback
function readFile(path, res, callback) {
fs.readFile(path, { encoding: 'utf-8' }, function(err, data) {
if (err || data === undefined) {
res.send(500);
} else {
// get mimetype
const mimetype = mime.lookup(path);
// hand back read data
callback(data, mimetype);
}
});
}
// respond with some data
function sendData(data, mimetype, res) {
// set important header
res.set('Content-Type', mimetype);
// send response, inject sockjs if it's html
res.send(
(mimetype == 'text/html') ? inject(data) : data
);
}
// inject zapp client into html just before body tag
function inject(data) {
return data.replace(
'<\/body>',
' <script src="/zapp/client"></script>\n </body>'
);
}
// serve a resource
function zappResource(file, res) {
readFile(__dirname + '/res/' + file, res, function(data, mimetype) {
sendData(data, mimetype, res);
});
}
// serve files
function zapp(req, res, next) {
// get path
const filePath = path.resolve(serv + '/' + req.path);
console.log(req.method + ' ' + req.path);
switch(req.path) {
case '/zapp/client':
zappResource('client.js', res);
break;
default:
fs.stat(filePath, function(err, stats) {
if (err || !stats || stats === undefined) {
let served = false;
extensions.forEach(function(extension) {
const newPath = filePath + extension;
if (fs.existsSync(newPath) && !served) {
serveFile(newPath, req, res);
served = true;
}
});
if (! served) {
res.send(404);
}
} else {
if (stats.isFile()) {
serveFile(filePath, req, res);
} else {
let served = false;
indexes.forEach(function(file) {
const newPath = filePath + '/' + file;
if (fs.existsSync(newPath) && !served) {
serveFile(newPath, req, res);
served = true;
}
});
if (! served) {
res.send(404);
}
}
}
});
break;
}
}
// setup server
const app = express();
const server = http.createServer(app);
// middleware
app.use(zapp);
// start server
server.listen(port);
// web socket server
const wss = new wsserver({ server: server });
// connection stack
let connections = {};
wss.on('connection', function(ws) {
const id = crypto.randomBytes(4).toString('hex');
console.log('CLIENT CONNECTED - ' + id);
connections[id] = ws;
ws.on('close', function(ws) {
console.log('CLIENT DISCONNECTED - ' + id);
delete connections[id];
});
});
// setup watcher
const watcher = chokidar.watch(serv, {ignored: ignores});
watcher.on('all', debounce(function(type, p) {
const stats = fs.lstatSync(p);
console.log('CHANGES DETECTED - notifying clients...');
if (stats.isFile()) {
for (const id in connections) {
const ws = connections[id];
if (ws.readyState == ws.OPEN) {
ws.send('refresh');
}
}
}
}, 500));
console.log(ascii);
console.log('[zapp] serving', path.resolve(serv), 'on port', port);