forked from cloudflare/netjet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
130 lines (108 loc) · 2.92 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
'use strict';
var posthtml = require('posthtml');
var unescape = require('lodash.unescape');
var defaults = require('lodash.defaults');
var hijackresponse = require('hijackresponse');
var bl = require('bl');
var LRU = require('lru-cache');
var posthtmlPreload = require('./posthtml-preload');
function encodeRFC5987(str) {
return encodeURI(str)
.replace(/['()]/g, escape)
.replace(/\*/g, '%2A')
.replace(/%(?:7C|60|5E)/g, unescape);
}
module.exports = function netjet(options) {
options = defaults(options, {
images: true,
scripts: true,
styles: true,
cache: {},
attributes: [],
});
var cache = new LRU(options.cache);
var attributes = [''].concat(options.attributes).join('; ');
return function netjetMiddleware(req, res, next) {
function appendHeader(field, value) {
var prev = res.getHeader(field);
if (prev) {
value = [].concat(prev, value);
}
res.setHeader(field, value);
}
function insertLinkArray(entries) {
var baseTag;
entries.forEach(function(entry) {
if (entry[1] === 'base') {
baseTag = entry;
}
});
entries
.filter(function(entry) {
return entry[1] !== 'base';
})
.forEach(function(entry) {
var url = entry[0];
var asType = entry[1];
var addBaseHref =
baseTag !== undefined &&
!new RegExp('^([a-z]+://|/)', 'i').test(url);
appendHeader(
'Link',
'<' +
(addBaseHref ? baseTag[0] : '') +
encodeRFC5987(unescape(url)) +
'>; rel=preload; as=' +
asType +
attributes
);
});
}
function processBody(body) {
var foundEntries = [];
posthtml()
.use(posthtmlPreload(options, foundEntries))
.process(body, {sync: true});
return foundEntries;
}
hijackresponse(res, function(err, res) {
/* istanbul ignore next */
// `err` from hijackresponse is currently hardcoded to "null"
if (err) {
res.unhijack();
next(err);
return;
}
// Only hijack HTML responses
if (!/^text\/html(?:;|\s|$)/.test(res.getHeader('Content-Type'))) {
res.unhijack();
return;
}
var etag = res.getHeader('etag');
var entries;
// reuse previous parse if the etag already exists in cache
if (etag) {
entries = cache.get(etag);
if (entries) {
insertLinkArray(entries);
res.pipe(res);
return;
}
}
res.pipe(
bl(function(err, data) {
if (err) {
res.unhijack();
next(err);
return;
}
entries = processBody(data.toString());
insertLinkArray(entries);
cache.set(etag, entries);
res.end(data);
})
);
});
next();
};
};