-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
305 lines (257 loc) · 10.4 KB
/
server.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
// https://github.com/nko4/website/blob/master/module/README.md#nodejs-knockout-deploy-check-ins
require('nko')('Dv-pUjLBGTI4IxU3');
var connect = require('connect'),
http = require('http'),
path = require('path'),
fs = require('fs'),
url = require('url'),
querystring = require('querystring'),
handlebars = require('handlebars'),
request = require('request'),
zombie = require('zombie'),
css = require('css'),
RSVP = require('rsvp');
var isProduction = (process.env.NODE_ENV === 'production'),
hostname = isProduction ? 'http://ally.2013.nodeknockout.com' : 'http://localhost:8000',
port = (isProduction ? 80 : 8000);
var opts = [
{
key: "display-none",
value: "Don't reset 'display: none;'"
}, {
key: "visibility-hidden",
value: "Don't reset 'visibility: hidden;'"
}
];
// Template handling using ES6 proxies for a magic-method-alike approach.
var templates = (function() {
var templatepath = path.join(__dirname,'public','templates');
var cache = {};
return Proxy.create({
get: function(proxy, template) {
// Only cache templates in production.
if (isProduction && cache[template]) return cache[template];
var templatecontents = fs.existsSync(path.join(templatepath,template+'.hbs')) ?
fs.readFileSync(path.join(templatepath,template+'.hbs'), 'utf8') : "Error";
cache[template] = handlebars.compile(templatecontents);
return cache[template];
}
});
})();
// REAL CODE GOES HERE
function parse(targeturl, options) {
var browser = new zombie();
var load = new RSVP.Promise(function(resolve, reject) {
// FIXME: Stop assuming that the zombie recovers.
browser.visit(targeturl).fin(function() {
resolve({
targeturl: targeturl,
options: options,
browser: browser
});
})
});
return load.then(function(previous) {
var options = previous.options;
var browser = previous.browser;
// Find every <link rel="stylesheet"> and <style> block, keep them in order.
var stylesheets = browser.queryAll("link[rel=stylesheet],style");
// Turn all of the stylesheets into promises.
stylesheets = stylesheets.map(function(stylesheet) {
var result = {};
if (stylesheet.tagName.toLowerCase() == 'link') {
// Request all of the CSS that was included remotely.
return new RSVP.Promise(function(resolve, reject) {
request(url.resolve(browser.location.href, stylesheet.href), function (error, res, body) {
if (error) { reject(error); }
result.location = url.resolve(browser.location.href, stylesheet.href);
result.media = !!stylesheet.media ? stylesheet.media : undefined;
result.body = body;
resolve(result);
});
});
} else {
// Snag all of the CSS that was included locally, wrpa it in a promise for safekeeping.
return new RSVP.Promise(function(resolve, reject) {
result.location = "Inline style block.";
result.media = undefined;
result.body = stylesheet.innerHTML;
resolve(result);
})
}
});
return RSVP.hash({
targeturl: previous.targeturl,
options: previous.options,
title: browser.text('title'),
stylesheets: RSVP.all(stylesheets)
});
}).then(function(previous) {
var options = previous.options;
var stylesheets = previous.stylesheets;
var preamble = "";
var parsedcss = "";
var keyOptions = [];
var englishOptions = [];
if (options.length) {
keyOptions = options.map(function(elem) { return elem.key; });
englishOptions = options.map(function(elem) { return elem.value; });
}
preamble = "/*\r\n";
preamble += "URL: " + previous.targeturl;
if (options.length) preamble += "\r\n\r\nOptions:\r\n- " + englishOptions.join("\r\n- ");
preamble += "\r\n*/\r\n";
stylesheets.forEach(function(stylesheet) {
try {
var interim = css.parse(stylesheet.body);
interim.stylesheet.rules = interim.stylesheet.rules.map(function(rule) {
if (rule.type === 'rule') {
rule.declarations = rule.declarations.map(function(declaration) {
// TODO: Properly set media queries.
// TODO: Calculate the minimum CSS needed to negate their CSS.
if (keyOptions.length && (
(~keyOptions.indexOf('display-none') && declaration.property == 'display' && declaration.value == 'none') ||
(~keyOptions.indexOf('visibility-hidden') && declaration.property == 'visibility' && declaration.value == 'hidden')
)) {
console.log('Skipping declaration.');
} else {
declaration.value = "inherit";
};
return declaration;
});
}
return rule;
});
parsedcss += css.stringify(interim, { compress: true })+"\r\n";
} catch(e) {
parsedcss += "/* Error parsing CSS: "+stylesheet.location+" */\r\n";
}
console.log(stylesheet.location);
});
return RSVP.hash({
targeturl: previous.targeturl,
title: previous.title,
options: previous.options,
parsedcss: preamble + parsedcss
});
});
}
function parseBitmask(options) {
var setOpts = [];
if (!options) return undefined;
for (var i = opts.length-1; i >= 0; i--) {
if(bitTest(options, i)) {
setOpts.push(opts[opts.length-1-i]);
}
}
return setOpts;
}
function bitTest(num, bit) {
return ((num>>bit) % 2 !== 0);
}
// Define your routes as members of the routes object.
var routes = {
"parse": function(req, res, next) {
var targeturl = req.query.url || undefined;
var contenttype = req.acceptType || "html";
var options = req.query.options || undefined;
if (contenttype !== "html" && contenttype !== "css") { return next(); }
// http://docs.jquery.com/Plugins/Validation/Methods/url
// From Scott Gonzalez: http://projects.scottsplayground.com/iri/
if (!/^(https?):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(targeturl)) {
routes["400"](req, res, next);
return;
}
// Handle previously submitted URLs.
var previousURLs = [];
if (req.cookies.previous) {
previousURLs = req.cookies.previous.split('~~~');
previousURLs = previousURLs.map(function(elem) { return querystring.escape(elem); });
}
// Only unshift this request if it isn't being repopulated.
if (req.query.exclude !== '1') {
previousURLs.unshift(querystring.escape(req.url));
previousURLs = previousURLs.filter(function (value, index, self) { return self.indexOf(value) === index; });
}
var setoptions = parseBitmask(options);
// Set scope.
var callback = (function() {
return function(results) {
if (contenttype == 'html') {
res.statusCode = 200;
res.setHeader('Set-Cookie', 'previous='+previousURLs.join('~~~'));
res.setHeader('Content-Type', 'text/'+contenttype);
res.end(templates.negate({
title: results.title,
url: targeturl,
thispage: hostname + req.url,
cssurl: hostname + req.url.replace('parse.html', 'parse.css').replace('&exclude=1', ''),
output: results.parsedcss,
options: results.options
}));
} else {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/css');
res.end(results.parsedcss);
}
}
})();
parse(targeturl, setoptions).then(callback);
},
"400": function(req, res, next) {
fs.readFile(path.join(__dirname,'public','400.html'), function (err, html) {
res.writeHead(400, {'Content-Type': 'text/html'});
res.end(html);
});
},
"404": function(req, res, next) {
fs.readFile(path.join(__dirname,'public','404.html'), function (err, html) {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end(html);
});
}
};
// Connect's boilerplate.
var app = connect()
.use(connect.favicon(path.join(__dirname,'public','favicon.ico')))
.use(connect.logger('dev'))
.use(connect.static(path.join(__dirname,'public')))
// Process the extension.
.use(function(req, res, next) {
var extension = connect.utils.parseUrl(req).pathname.match(/\.([^.]+)$/);
if (extension && extension[1]) {
req.acceptType = extension[1];
}
return next();
})
// Process the querystring and cookies.
.use(connect.query())
.use(connect.cookieParser())
// Lookup the route.
.use(function(req, res, next) {
var route = connect.utils.parseUrl(req).pathname.substring(1).replace(/\.[^.]+$/,'');
if (routes[route]) {
routes[route](req, res, next);
// When all else fails, 404
} else {
return next();
}
})
// When all else fails, 404
.use(function(req, res, next) {
routes["404"](req, res, next);
});
// HTTP Server boilerplate.
http
.createServer(app)
.listen(port, function(err) {
if (err) { console.error(err); process.exit(-1); }
// if run as root, downgrade to the owner of this file
if (process.getuid() === 0) {
require('fs').stat(__filename, function(err, stats) {
if (err) { return console.error(err); }
process.setuid(stats.uid);
});
}
console.log('Server running at http://0.0.0.0:' + port + '/');
});