forked from remy/inliner
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
439 lines (368 loc) · 11.2 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
module.exports = Inliner;
var debug = require('debug')('inliner');
var events = require('events');
var path = require('path');
var util = require('util');
var fs = require('then-fs');
var assign = require('lodash.assign');
var forEach = require('lodash.foreach');
var Promise = require('es6-promise').Promise; // jshint ignore:line
var findAssets = require('./find-assets');
var iconv = require('iconv-lite');
var charset = require('charset');
var jschardet = require('jschardet');
var querystring = require('querystring');
// note: these tasks (excluding HTML), match up to files in lib/tasks/*.js
var tasks = {
html: 'html', // this is abritrary since it's manually processed
js: 'script',
svg: 'svg',
links: 'link[rel=stylesheet]',
favicon: 'link[rel=icon],link[rel="shortcut icon"],' +
'link[rel="apple-touch-icon"],link[rel="apple-touch-startup-image"]',
styles: 'style',
'style-attrs': '[style]:not(svg *)', // only style attrs in HTML, not SVG
images: 'img',
videos: 'video',
};
var taskRunner = Object.keys(tasks).reduce(function (acc, curr) {
if (curr !== 'html') {
acc[curr] = require('./tasks/' + curr);
}
return acc;
}, {});
// source is typicaly a URL, but can be a file location OR an HTML string
function Inliner(source, options, callback) {
var inliner = this;
events.EventEmitter.call(this);
// allow for source to be optional
if (typeof source !== 'string') {
callback = options;
options = source;
}
if (typeof options === 'function') {
callback = options;
options = {};
}
if (!options) {
options = {};
}
if (options.url) {
this.url = options.url;
}
if (options.filename) {
this.filename = options.filename;
}
if (options.source) {
this.source = options.source;
} else {
this.source = source;
}
// this is an intentioal change. `.headers` is compatible with the request
// module, but -H and --header is compatible (i.e. the same as) cURL
if (options.header) {
options.headers = options.header;
delete options.header;
}
if (options.headers && !Array.isArray(options.headers)) {
options.headers = [options.headers];
}
if (options.headers && Array.isArray(options.headers)) {
options.headers = options.headers.reduce(function (acc, curr) {
if (typeof curr === 'string') {
var parts = curr.split(':').map(function (s) {
return s.trim();
});
acc[parts[0]] = parts[1];
} else {
var key = Object.keys(curr);
acc[key] = curr[key];
}
return acc;
}, {});
}
if (options.headers && typeof options.headers[0] === 'string') {
// convert to an object of key/value pairs
options.headers = options.headers.reduce(function (acc, curr) {
var pair = querystring.parse(curr);
var key = Object.keys(pair).shift();
acc[key] = pair[key];
return acc;
}, {});
}
this.headers = options.headers || {};
this.callback = function wrapper(error, res) {
// noop the callback once it's fired
inliner.callback = function noop() {
inliner.emit('error', 'callback fired again');
};
callback(error, res);
};
this.options = assign({}, Inliner.defaults(), options);
this.jobs = {
total: 0,
todo: 0,
tasks: tasks,
add: this.addJob.bind(this),
breakdown: {},
done: {},
};
Object.keys(this.jobs.tasks).forEach(function (key) {
this.jobs.breakdown[key] = 0;
this.jobs.done[key] = this.completeJob.bind(this, key);
}.bind(this));
this.isFile = options.useStdin || false;
this.on('error', function localErrorHandler(event) {
inliner.callback(event);
});
// this allows the user code to get the object back before
// it starts firing events
if (this.source) {
if (typeof setImmediate === 'undefined') {
global.setImmediate = function setImmediatePolyfill(fn) {
// :-/
setTimeout(fn, 0);
};
}
this.promise = new Promise(function (resolve) {
global.setImmediate(function () {
resolve(inliner.main());
});
});
} else {
this.promise = Promise.reject(new Error('No source to inline'));
}
return this;
}
util.inherits(Inliner, events.EventEmitter);
Inliner.prototype.updateTodo = updateTodo;
Inliner.prototype.addJob = addJob;
Inliner.prototype.completeJob = completeJob;
Inliner.prototype.cssImages = require('./css').getImages;
Inliner.prototype.cssImports = require('./css').getImports;
Inliner.prototype.image = require('./image');
Inliner.prototype.uglify = require('./javascript');
Inliner.prototype.resolve = resolve;
Inliner.prototype.removeComments = removeComments;
Inliner.prototype.get = require('./get');
Inliner.prototype.main = main;
Inliner.prototype.findAssets = findAssets;
// static properties and methods
Inliner.errors = require('./errors');
Inliner.defaults = require('./defaults');
// main thread of functionality that does all the inlining
function main() {
var inliner = this;
var url = this.source;
return fs.exists(this.filename || url)
.then(function exists(isFile) {
if (!isFile) {
throw new Error('Not a file - use URL parser');
}
debug('inlining file');
inliner.isFile = true;
inliner.url = url; // this is a hack for the `resolve` function later on
return inliner.get(this.filename || url, { encoding: 'binary' });
})
.catch(function isUrl() {
// make the best guess as to whether we're working with a url
if (inliner.url || url.indexOf('<') === -1) {
url = inliner.url || inliner.source;
// check for protocol on URL
if (url.indexOf('http') !== 0) {
url = 'http://' + url;
}
inliner.url = url;
debug('inlining url');
return inliner.get(url, { encoding: 'binary' });
}
// otherwise we're dealing with an inline string
debug('inlining by string: ', inliner.source);
inliner.isFile = true;
inliner.url = '.';
var res = {
body: new Buffer(inliner.source),
headers: {
'content-type': 'text/html',
},
};
return res;
})
.then(inliner.jobs.add('html'))
.then(function processHTML(res) {
inliner.jobs.done.html();
debug('processing HTML');
debug(inliner.options);
var body;
var cheerioLoadOptions = {};
var enc = inliner.options.encoding;
// try to determine the encoding from the headers and the body
if (!enc) {
enc = charset(res.headers, res.body);
enc = enc || jschardet.detect(res.body).encoding.toLowerCase();
}
// normalise to avoid any mistakes
if (enc === 'utf-8' || enc === 'utf8') {
enc = 'utf-8';
}
cheerioLoadOptions.decodeEntities = false;
if (enc !== 'utf-8') {
debug('decoding from: %s', enc);
body = iconv.encode(iconv.decode(res.body, enc), 'utf-8');
} else {
body = res.body;
}
body = body.toString();
// if we spot some SVG elements in the source,
// then we'll parse as XML to correctly get the SVG
if (body.indexOf('<?xml') !== -1 ||
body.indexOf('<?XML') !== -1) {
cheerioLoadOptions.xmlMode = true;
}
if (body.indexOf('<svg') !== -1) {
cheerioLoadOptions.lowerCaseAttributeNames = false;
}
var todo = inliner.findAssets(body, cheerioLoadOptions);
var $ = todo.$;
delete todo.$;
if (enc !== 'utf-8') {
// when transcoding remove any meta tags setting the charset
$('meta').each(function charMeta() {
var attrs = $(this).attr();
var content = attrs.content || '';
if (attrs.charset || content.toLowerCase().indexOf('charset=') !== -1) {
$(this).remove();
}
});
}
var promises = [];
forEach(todo, function forEach(todo, key) {
if (key === 'images' && !inliner.options.images) {
// skip images if the user doesn't want them
delete todo.images;
debug('skipping images');
return;
}
if (key === 'videos' && !inliner.options.videos) {
// skip videos if the user doesn't want them
delete todo.videos;
debug('skipping videos');
return;
}
if (!todo.length) {
return;
}
inliner.jobs.add(key, todo.length);
var tasks = taskRunner[key](inliner, todo.get(), $);
promises = promises.concat(tasks);
});
return Promise.all(promises).then(function then() {
var html = '';
// remove comments
if (!inliner.options.preserveComments) {
inliner.removeComments($(':root')[0], $);
}
// collapse the white space
if (inliner.options.collapseWhitespace) {
debug('collapsing whitespace');
$('pre, textarea').each(function () {
$(this).html($(this).html()
.replace(/\n/g, '~~nl~~')
.replace(/\s/g, '~~s~~'));
});
$('script').each(function () {
$(this).text($(this).text()
.replace(/\n/g, '~~nl~~')
.replace(/\s/g, '~~s~~'));
});
html = $.html()
.replace(/\s+/g, ' ')
.replace(/~~nl~~/g, '\n')
.replace(/~~s~~/g, ' ');
} else {
html = $.html();
}
debug('completed: %s bytes', html.length);
return html;
});
})
.then(function then(html) {
inliner.callback(null, html);
inliner.emit('end');
})
.catch(function errHandler(error) {
debug('fail', error.stack);
inliner.callback(error);
inliner.emit('error', error);
throw error;
});
}
function removeComments(element, $) {
if (!element || !element.childNodes) {
return;
}
var nodes = element.childNodes;
var i = nodes.length;
while (i--) {
var first = (nodes[i].nodeValue || '').charAt(0);
if (nodes[i].type === 'comment' && first !== '[' && first !== '#') {
$(nodes[i]).remove();
}
removeComments(nodes[i], $);
}
}
function resolve(from, to) {
if (!to) {
to = from;
from = this.url;
}
// don't resolve data urls (already inlined)
if (to.indexOf('data:') === 0) {
return to;
}
// always strip querystrings from requests off a local file
if (this.isFile) {
to = to.replace(/\??#.*$/, '');
}
// don't resolve http(s) urls (no need to resolve)
if (to.indexOf('http:') === 0 || to.indexOf('https:') === 0) {
return to;
}
if (!this.isFile || from.indexOf('http') === 0) {
return require('url').resolve(from, to);
}
var base = path.dirname(from);
return path.resolve(base, to);
}
function updateTodo() {
var jobs = this.jobs;
jobs.todo = Object.keys(jobs.breakdown).reduce(function (acc, key) {
return acc + jobs.breakdown[key];
}, 0);
var breakdown = Object.keys(jobs.breakdown).map(function (key) {
if (jobs.breakdown[key]) {
return key + '(' + jobs.breakdown[key] + ')';
}
return false;
}).filter(Boolean);
this.emit('jobs', {
total: jobs.total,
todo: jobs.todo,
breakdown: breakdown,
});
}
function addJob(type) {
var n = typeof arguments[1] === 'number' ? arguments[1] : 1;
this.jobs.breakdown[type] += n;
this.jobs.total += n;
this.updateTodo();
debug('%s: %s', type, n);
// this allows me to include addJob as part of a promise chain
return arguments[1];
}
function completeJob(type) {
this.jobs.breakdown[type]--;
this.updateTodo();
// this allows me to include addJob as part of a promise chain
return arguments[1];
}