-
-
Notifications
You must be signed in to change notification settings - Fork 194
/
utils.js
287 lines (225 loc) · 7.79 KB
/
utils.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
import path from "path";
/* eslint-disable class-methods-use-this */
const trailingSlash = /[/\\]$/;
// This somewhat changed in Less 3.x. Now the file name comes without the
// automatically added extension whereas the extension is passed in as `options.ext`.
// So, if the file name matches this regexp, we simply ignore the proposed extension.
const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/;
// `[drive_letter]:\` + `\\[server]\[share_name]\`
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
// Examples:
// - ~package
// - ~package/
// - ~@org
// - ~@org/
// - ~@org/package
// - ~@org/package/
const IS_MODULE_IMPORT =
/^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
const MODULE_REQUEST_REGEX = /^[^?]*~/;
/**
* Creates a Less plugin that uses webpack's resolving engine that is provided by the loaderContext.
*
* @param {LoaderContext} loaderContext
* @param {object} implementation
* @returns {LessPlugin}
*/
function createWebpackLessPlugin(loaderContext, implementation) {
const resolve = loaderContext.getResolve({
dependencyType: "less",
conditionNames: ["less", "style", "..."],
mainFields: ["less", "style", "main", "..."],
mainFiles: ["index", "..."],
extensions: [".less", ".css"],
preferRelative: true,
});
class WebpackFileManager extends implementation.FileManager {
supports(filename) {
if (filename[0] === "/" || IS_NATIVE_WIN32_PATH.test(filename)) {
return true;
}
if (this.isPathAbsolute(filename)) {
return false;
}
return true;
}
// Sync resolving is used at least by the `data-uri` function.
// This file manager doesn't know how to do it, so let's delegate it
// to the default file manager of Less.
// We could probably use loaderContext.resolveSync, but it's deprecated,
// see https://webpack.js.org/api/loaders/#this-resolvesync
supportsSync() {
return false;
}
async resolveFilename(filename, currentDirectory) {
// Less is giving us trailing slashes, but the context should have no trailing slash
const context = currentDirectory.replace(trailingSlash, "");
let request = filename;
// A `~` makes the url an module
if (MODULE_REQUEST_REGEX.test(filename)) {
request = request.replace(MODULE_REQUEST_REGEX, "");
}
if (IS_MODULE_IMPORT.test(filename)) {
request = request[request.length - 1] === "/" ? request : `${request}/`;
}
return this.resolveRequests(context, [...new Set([request, filename])]);
}
async resolveRequests(context, possibleRequests) {
if (possibleRequests.length === 0) {
return Promise.reject();
}
let result;
try {
result = await resolve(context, possibleRequests[0]);
} catch (error) {
const [, ...tailPossibleRequests] = possibleRequests;
if (tailPossibleRequests.length === 0) {
throw error;
}
result = await this.resolveRequests(context, tailPossibleRequests);
}
return result;
}
async loadFile(filename, ...args) {
let result;
try {
if (IS_SPECIAL_MODULE_IMPORT.test(filename)) {
const error = new Error();
error.type = "Next";
throw error;
}
result = await super.loadFile(filename, ...args);
} catch (error) {
if (error.type !== "File" && error.type !== "Next") {
return Promise.reject(error);
}
try {
result = await this.resolveFilename(filename, ...args);
} catch (webpackResolveError) {
error.message =
`Less resolver error:\n${error.message}\n\n` +
`Webpack resolver error details:\n${webpackResolveError.details}\n\n` +
`Webpack resolver error missing:\n${webpackResolveError.missing}\n\n`;
return Promise.reject(error);
}
loaderContext.addDependency(result);
return super.loadFile(result, ...args);
}
const absoluteFilename = path.isAbsolute(result.filename)
? result.filename
: path.resolve(".", result.filename);
loaderContext.addDependency(path.normalize(absoluteFilename));
return result;
}
}
return {
install(lessInstance, pluginManager) {
pluginManager.addFileManager(new WebpackFileManager());
},
minVersion: [3, 0, 0],
};
}
/**
* Get the `less` options from the loader context and normalizes its values
*
* @param {object} loaderContext
* @param {object} loaderOptions
* @param {object} implementation
* @returns {Object}
*/
function getLessOptions(loaderContext, loaderOptions, implementation) {
const options =
typeof loaderOptions.lessOptions === "function"
? loaderOptions.lessOptions(loaderContext) || {}
: loaderOptions.lessOptions || {};
const lessOptions = {
plugins: [],
relativeUrls: true,
// We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
filename: loaderContext.resourcePath,
...options,
};
const plugins = lessOptions.plugins.slice();
const shouldUseWebpackImporter =
typeof loaderOptions.webpackImporter === "boolean"
? loaderOptions.webpackImporter
: true;
if (shouldUseWebpackImporter) {
plugins.unshift(createWebpackLessPlugin(loaderContext, implementation));
}
plugins.unshift({
install(lessProcessor, pluginManager) {
// eslint-disable-next-line no-param-reassign
pluginManager.webpackLoaderContext = loaderContext;
lessOptions.pluginManager = pluginManager;
},
});
lessOptions.plugins = plugins;
return lessOptions;
}
function isUnsupportedUrl(url) {
// Is Windows path
if (IS_NATIVE_WIN32_PATH.test(url)) {
return false;
}
// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url);
}
function normalizeSourceMap(map) {
const newMap = map;
// map.file is an optional property that provides the output filename.
// Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
// eslint-disable-next-line no-param-reassign
delete newMap.file;
// eslint-disable-next-line no-param-reassign
newMap.sourceRoot = "";
// `less` returns POSIX paths, that's why we need to transform them back to native paths.
// eslint-disable-next-line no-param-reassign
newMap.sources = newMap.sources.map((source) => path.normalize(source));
return newMap;
}
function getLessImplementation(loaderContext, implementation) {
let resolvedImplementation = implementation;
if (!implementation || typeof implementation === "string") {
const lessImplPkg = implementation || "less";
// eslint-disable-next-line import/no-dynamic-require, global-require
resolvedImplementation = require(lessImplPkg);
}
// eslint-disable-next-line consistent-return
return resolvedImplementation;
}
function getFileExcerptIfPossible(error) {
if (typeof error.extract === "undefined") {
return [];
}
const excerpt = error.extract.slice(0, 2);
const column = Math.max(error.column - 1, 0);
if (typeof excerpt[0] === "undefined") {
excerpt.shift();
}
excerpt.push(`${new Array(column).join(" ")}^`);
return excerpt;
}
function errorFactory(error) {
const message = [
"\n",
...getFileExcerptIfPossible(error),
error.message.charAt(0).toUpperCase() + error.message.slice(1),
error.filename
? ` Error in ${path.normalize(error.filename)} (line ${
error.line
}, column ${error.column})`
: "",
].join("\n");
const obj = new Error(message, { cause: error });
obj.stack = null;
return obj;
}
export {
getLessOptions,
isUnsupportedUrl,
normalizeSourceMap,
getLessImplementation,
errorFactory,
};