-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
197 lines (176 loc) · 6.56 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
const fp = require("fastify-plugin");
const htmlMinifier = require("html-minifier-terser");
const terser = require("terser");
const csso = require("csso");
const LRU = require("tiny-lru");
const getStream = require("get-stream");
require("array-flat-polyfill");
const DEFAULT_JS_OPTIONS = {
sourceMap: false,
compress: true,
mangle: true
};
const DEFAULT_CSS_OPTIONS = {};
const DEFAULT_HTML_OPTIONS = {
removeComments: true,
collapseWhitespace: true,
minifyCSS: true,
minifyJS: DEFAULT_JS_OPTIONS
};
const PLUGIN_SYMBOL = Symbol.for("registered-plugin");
function plugin(instance, opts, done) {
opts = opts || {};
const htmlOptions = Object.assign({}, DEFAULT_HTML_OPTIONS, opts.htmlOptions);
const jsOptions = Object.assign({}, DEFAULT_JS_OPTIONS, opts.jsOptions);
const cssOptions = Object.assign({}, DEFAULT_CSS_OPTIONS, opts.cssOptions);
const lru = typeof opts.cache === "number" ? LRU(opts.cache)
: opts.cache && typeof opts.cache.get === "function" && typeof opts.cache.set === "function"
? opts.cache : null;
const validate = typeof opts.validate === "function" ? opts.validate : () => true;
const minInfixFunction = typeof opts.minInfix === "function" ? opts.minInfix : opts.minInfix ? () => true : null;
const defaultTransformers = [
{
suffix: "js",
contentType: ["application/javascript", "text/javascript"],
decorate: "minifyJS",
func: value => terser.minify(value, jsOptions).then(r => r.code),
},
{
suffix: "css",
contentType: "text/css",
decorate: "minifyCSS",
func: value => csso.minify(value, cssOptions).css,
},
{
suffix: "html",
contentType: "text/html",
decorate: "minifyHTML",
func: value => htmlMinifier.minify(value, htmlOptions),
},
{
suffix: "json",
contentType: "application/json",
func: value => JSON.stringify(JSON.parse(value), null, 0)
}
];
let transformers = defaultTransformers.slice();
if (Array.isArray(opts.transformers)) {
for (const t of opts.transformers) {
const oldTransformer = getTransformerForSuffix(t.suffix || "");
if (oldTransformer) {
Object.assign(oldTransformer, t);
} else {
transformers.push(t);
}
}
}
transformers = transformers.filter(t => t.func);
transformers.forEach(t => {
t.suffix = wrap(t.suffix).map(s => s.toLowerCase());
t.contentType = wrap(t.contentType).map(s => s.toLowerCase());
enhanceFunction(t);
if (t.decorate && typeof t.decorate === "string") {
instance.decorate(t.decorate, t.func)
}
});
function enhanceFunction(transformer) {
const prefix = transformer.suffix.toString();
const oldFunc = transformer.func;
const promisedFunc = async v => oldFunc(v);
const useCache = "useCache" in transformer ? transformer.useCache : true;
transformer.func = async value => {
if (useCache) {
const cachedValue = await getCachedValue(prefix, value);
if (cachedValue != null) {
return cachedValue;
}
}
const result = await promisedFunc(value);
if (useCache) {
setCachedValue(prefix, value, result);
}
return result;
}
}
function getCachedValue(prefix, key) {
if (!lru) { return; }
return lru.get(prefix + key);
}
function setCachedValue(prefix, key, value) {
if (!lru) { return value; }
lru.set(prefix + key, value);
return value;
}
if (opts.global || minInfixFunction) {
instance.addHook("onSend", (req, rep, payload, done) => {
if (payload && (opts.global || req.mini)) {
const contentType = rep.getHeader("content-type") || "";
const transformer = getTransformerForContentType(contentType);
if (transformer && validate(req, rep, payload)) {
rep.header("content-length", null);
toStringPromise(payload)
.then(transformer.func)
.then(pl => done(null, pl))
.catch(err => done(err));
return;
}
}
done(null, payload);
})
}
function getTransformerForContentType(contentType) {
contentType = contentType.toLowerCase();
return transformers.filter(t => t.contentType.some(ct => contentType.includes(ct)))[0];
}
const suffixes = transformers.flatMap(t => t.suffix);
if (minInfixFunction) {
instance.decorateRequest("mini", false);
instance.addHook("onRequest", (req, rep, done) => {
const filePath = req.params["*"];
if (req.method === "GET"
&& typeof filePath === "string"
&& typeof req.context.config.url === "string"
&& req.context.config.url.endsWith("/*")
&& suffixes.some(s => filePath.toLowerCase().endsWith(".min." + s))
&& getTransformerForSuffix(filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase())
&& minInfixFunction(req, filePath)
) {
req.mini = true;
req.params["*"] = req.params["*"].replace(/\.min\./, ".");
}
done();
})
}
function getTransformerForSuffix(suffix) {
suffix = suffix.toLowerCase();
return transformers.filter(t => t.suffix.includes(suffix))[0];
}
instance.addHook("onReady", done => {
if (minInfixFunction && instance[PLUGIN_SYMBOL].indexOf("fastify-static") === -1)
done(new Error("fastify-static is not present. Either register it or disable minInfix."));
else
done();
})
done();
}
function toStringPromise(value) {
const type = typeof value;
if (type === "string") {
return Promise.resolve(value);
}
if (Buffer.isBuffer(value)) {
return Promise.resolve(value.toString());
}
if (typeof value === "object" && typeof value.pipe === "function") {
return getStream(value);
}
throw new Error("unsupported type");
}
function wrap(value) {
if (!value) return [];
return Array.isArray(value) ? value : [value];
}
module.exports = fp(plugin, {
fastify: ">=3.x.x",
name: "fastify-minify",
});