index.js
4.1 KB
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
'use strict';
const valueParser = require('postcss-value-parser');
const { optimize } = require('svgo');
const { encode, decode } = require('./lib/url');
const PLUGIN = 'postcss-svgo';
const dataURI = /data:image\/svg\+xml(;((charset=)?utf-8|base64))?,/i;
const dataURIBase64 = /data:image\/svg\+xml;base64,/i;
// the following regex will globally match:
// \b([\w-]+) --> a word (a sequence of one or more [alphanumeric|underscore|dash] characters; followed by
// \s*=\s* --> an equal sign character (=) between optional whitespaces; followed by
// \\"([\S\s]+?)\\" --> any characters (including whitespaces and newlines) between literal escaped quotes (\")
const escapedQuotes = /\b([\w-]+)\s*=\s*\\"([\S\s]+?)\\"/g;
/**
* @param {string} input the SVG string
* @param {Options} opts
* @return {{result: string, isUriEncoded: boolean}} the minification result
*/
function minifySVG(input, opts) {
let svg = input;
let decodedUri, isUriEncoded;
try {
decodedUri = decode(input);
isUriEncoded = decodedUri !== input;
} catch (e) {
// Swallow exception if we cannot decode the value
isUriEncoded = false;
}
if (isUriEncoded) {
svg = /** @type {string} */ (decodedUri);
}
if (opts.encode !== undefined) {
isUriEncoded = opts.encode;
}
// normalize all escaped quote characters from svg attributes
// from <svg attr=\"value\"... /> to <svg attr="value"... />
// see: https://github.com/cssnano/cssnano/issues/1194
svg = svg.replace(escapedQuotes, '$1="$2"');
const result = optimize(svg, opts);
if (result.error) {
throw new Error(result.error);
}
return {
result: /** @type {import('svgo').OptimizedSvg}*/ (result).data,
isUriEncoded,
};
}
/**
* @param {import('postcss').Declaration} decl
* @param {Options} opts
* @param {import('postcss').Result} postcssResult
* @return {void}
*/
function minify(decl, opts, postcssResult) {
const parsed = valueParser(decl.value);
const minified = parsed.walk((node) => {
if (
node.type !== 'function' ||
node.value.toLowerCase() !== 'url' ||
!node.nodes.length
) {
return;
}
let { value, quote } = /** @type {valueParser.StringNode} */ (
node.nodes[0]
);
let optimizedValue;
try {
if (dataURIBase64.test(value)) {
const url = new URL(value);
const base64String = `${url.protocol}${url.pathname}`.replace(
dataURI,
''
);
const svg = Buffer.from(base64String, 'base64').toString('utf8');
const { result } = minifySVG(svg, opts);
const data = Buffer.from(result).toString('base64');
optimizedValue = 'data:image/svg+xml;base64,' + data + url.hash;
} else if (dataURI.test(value)) {
const svg = value.replace(dataURI, '');
const { result, isUriEncoded } = minifySVG(svg, opts);
let data = isUriEncoded ? encode(result) : result;
// Should always encode # otherwise we yield a broken SVG
// in Firefox (works in Chrome however). See this issue:
// https://github.com/cssnano/cssnano/issues/245
data = data.replace(/#/g, '%23');
optimizedValue = 'data:image/svg+xml;charset=utf-8,' + data;
quote = isUriEncoded ? '"' : "'";
} else {
return;
}
} catch (error) {
decl.warn(postcssResult, `${error}`);
return;
}
node.nodes[0] = Object.assign({}, node.nodes[0], {
value: optimizedValue,
quote: quote,
type: 'string',
before: '',
after: '',
});
return false;
});
decl.value = minified.toString();
}
/** @typedef {{encode?: boolean, plugins?: object[]} & import('svgo').OptimizeOptions} Options */
/**
* @type {import('postcss').PluginCreator<Options>}
* @param {Options} opts
* @return {import('postcss').Plugin}
*/
function pluginCreator(opts = {}) {
return {
postcssPlugin: PLUGIN,
OnceExit(css, { result }) {
css.walkDecls((decl) => {
if (!dataURI.test(decl.value)) {
return;
}
minify(decl, opts, result);
});
},
};
}
pluginCreator.postcss = true;
module.exports = pluginCreator;