postcss-url-parser.js
6.53 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
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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _util = require("util");
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-url-parser';
const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDecl = /(?:url|(?:-webkit-)?image-set)\(/i;
function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function shouldHandleRule(rule, decl, result) {
// https://www.w3.org/TR/css-syntax-3/#typedef-url-token
if (rule.url.replace(/^[\s]+|[\s]+$/g, '').length === 0) {
result.warn(`Unable to find uri in '${decl.toString()}'`, {
node: decl
});
return false;
}
if (!(0, _utils.isUrlRequestable)(rule.url)) {
return false;
}
return true;
}
function walkCss(css, result, options, callback) {
const accumulator = [];
css.walkDecls(decl => {
if (!needParseDecl.test(decl.value)) {
return;
}
const parsed = (0, _postcssValueParser.default)(decl.value);
parsed.walk(node => {
if (node.type !== 'function') {
return;
}
if (isUrlFunc.test(node.value)) {
const {
nodes
} = node;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
const rule = {
node: getNodeFromUrlFunc(node),
url,
needQuotes: false,
isStringValue
};
if (shouldHandleRule(rule, decl, result)) {
accumulator.push({
decl,
rule,
parsed
});
} // Do not traverse inside `url`
// eslint-disable-next-line consistent-return
return false;
} else if (isImageSetFunc.test(node.value)) {
for (const nNode of node.nodes) {
const {
type,
value
} = nNode;
if (type === 'function' && isUrlFunc.test(value)) {
const {
nodes
} = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
const rule = {
node: getNodeFromUrlFunc(nNode),
url,
needQuotes: false,
isStringValue
};
if (shouldHandleRule(rule, decl, result)) {
accumulator.push({
decl,
rule,
parsed
});
}
} else if (type === 'string') {
const rule = {
node: nNode,
url: value,
needQuotes: true,
isStringValue: true
};
if (shouldHandleRule(rule, decl, result)) {
accumulator.push({
decl,
rule,
parsed
});
}
}
} // Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
});
callback(null, accumulator);
}
const asyncWalkCss = (0, _util.promisify)(walkCss);
var _default = _postcss.default.plugin(pluginName, options => async (css, result) => {
const parsedResults = await asyncWalkCss(css, result, options);
if (parsedResults.length === 0) {
return Promise.resolve();
}
const tasks = [];
const imports = new Map();
const replacements = new Map();
let hasUrlImportHelper = false;
for (const parsedResult of parsedResults) {
const {
url,
isStringValue
} = parsedResult.rule;
let normalizedUrl = url;
let prefix = '';
const queryParts = normalizedUrl.split('!');
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join('!');
}
normalizedUrl = (0, _utils.normalizeUrl)(normalizedUrl, isStringValue);
if (!options.filter(normalizedUrl)) {
// eslint-disable-next-line no-continue
continue;
}
if (!hasUrlImportHelper) {
options.imports.push({
importName: '___CSS_LOADER_GET_URL_IMPORT___',
url: options.urlHandler(require.resolve('../runtime/getUrl.js')),
index: -1
});
hasUrlImportHelper = true;
}
const splittedUrl = normalizedUrl.split(/(\?)?#/);
const [pathname, query, hashOrQuery] = splittedUrl;
let hash = query ? '?' : '';
hash += hashOrQuery ? `#${hashOrQuery}` : '';
const request = (0, _utils.requestify)(pathname, options.rootContext);
tasks.push((async () => {
const {
resolver,
context
} = options;
const resolvedUrl = await (0, _utils.resolveRequests)(resolver, context, [...new Set([request, normalizedUrl])]);
return {
url: resolvedUrl,
prefix,
hash,
parsedResult
};
})());
}
const results = await Promise.all(tasks);
for (let index = 0; index <= results.length - 1; index++) {
const {
url,
prefix,
hash,
parsedResult: {
decl,
rule,
parsed
}
} = results[index];
const newUrl = prefix ? `${prefix}!${url}` : url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
importName,
url: options.urlHandler(newUrl),
index
});
}
const {
needQuotes
} = rule;
const replacementKey = JSON.stringify({
newUrl,
hash,
needQuotes
});
let replacementName = replacements.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${replacements.size}___`;
replacements.set(replacementKey, replacementName);
options.replacements.push({
replacementName,
importName,
hash,
needQuotes
});
} // eslint-disable-next-line no-param-reassign
rule.node.type = 'word'; // eslint-disable-next-line no-param-reassign
rule.node.value = replacementName; // eslint-disable-next-line no-param-reassign
decl.value = parsed.toString();
}
return Promise.resolve();
});
exports.default = _default;