UNPKG

8.15 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.errorFactory = errorFactory;
7exports.getLessImplementation = getLessImplementation;
8exports.getLessOptions = getLessOptions;
9exports.isUnsupportedUrl = isUnsupportedUrl;
10exports.normalizeSourceMap = normalizeSourceMap;
11var _path = _interopRequireDefault(require("path"));
12function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13/* eslint-disable class-methods-use-this */
14const trailingSlash = /[/\\]$/;
15
16// This somewhat changed in Less 3.x. Now the file name comes without the
17// automatically added extension whereas the extension is passed in as `options.ext`.
18// So, if the file name matches this regexp, we simply ignore the proposed extension.
19const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/;
20
21// `[drive_letter]:\` + `\\[server]\[share_name]\`
22const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
23
24// Examples:
25// - ~package
26// - ~package/
27// - ~@org
28// - ~@org/
29// - ~@org/package
30// - ~@org/package/
31const IS_MODULE_IMPORT = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
32const MODULE_REQUEST_REGEX = /^[^?]*~/;
33
34/**
35 * Creates a Less plugin that uses webpack's resolving engine that is provided by the loaderContext.
36 *
37 * @param {LoaderContext} loaderContext
38 * @param {object} implementation
39 * @returns {LessPlugin}
40 */
41function createWebpackLessPlugin(loaderContext, implementation) {
42 const resolve = loaderContext.getResolve({
43 dependencyType: "less",
44 conditionNames: ["less", "style", "..."],
45 mainFields: ["less", "style", "main", "..."],
46 mainFiles: ["index", "..."],
47 extensions: [".less", ".css"],
48 preferRelative: true
49 });
50 class WebpackFileManager extends implementation.FileManager {
51 supports(filename) {
52 if (filename[0] === "/" || IS_NATIVE_WIN32_PATH.test(filename)) {
53 return true;
54 }
55 if (this.isPathAbsolute(filename)) {
56 return false;
57 }
58 return true;
59 }
60
61 // Sync resolving is used at least by the `data-uri` function.
62 // This file manager doesn't know how to do it, so let's delegate it
63 // to the default file manager of Less.
64 // We could probably use loaderContext.resolveSync, but it's deprecated,
65 // see https://webpack.js.org/api/loaders/#this-resolvesync
66 supportsSync() {
67 return false;
68 }
69 async resolveFilename(filename, currentDirectory) {
70 // Less is giving us trailing slashes, but the context should have no trailing slash
71 const context = currentDirectory.replace(trailingSlash, "");
72 let request = filename;
73
74 // A `~` makes the url an module
75 if (MODULE_REQUEST_REGEX.test(filename)) {
76 request = request.replace(MODULE_REQUEST_REGEX, "");
77 }
78 if (IS_MODULE_IMPORT.test(filename)) {
79 request = request[request.length - 1] === "/" ? request : `${request}/`;
80 }
81 return this.resolveRequests(context, [...new Set([request, filename])]);
82 }
83 async resolveRequests(context, possibleRequests) {
84 if (possibleRequests.length === 0) {
85 return Promise.reject();
86 }
87 let result;
88 try {
89 result = await resolve(context, possibleRequests[0]);
90 } catch (error) {
91 const [, ...tailPossibleRequests] = possibleRequests;
92 if (tailPossibleRequests.length === 0) {
93 throw error;
94 }
95 result = await this.resolveRequests(context, tailPossibleRequests);
96 }
97 return result;
98 }
99 async loadFile(filename, ...args) {
100 let result;
101 try {
102 if (IS_SPECIAL_MODULE_IMPORT.test(filename)) {
103 const error = new Error();
104 error.type = "Next";
105 throw error;
106 }
107 result = await super.loadFile(filename, ...args);
108 } catch (error) {
109 if (error.type !== "File" && error.type !== "Next") {
110 return Promise.reject(error);
111 }
112 try {
113 result = await this.resolveFilename(filename, ...args);
114 } catch (webpackResolveError) {
115 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`;
116 return Promise.reject(error);
117 }
118 loaderContext.addDependency(result);
119 return super.loadFile(result, ...args);
120 }
121 const absoluteFilename = _path.default.isAbsolute(result.filename) ? result.filename : _path.default.resolve(".", result.filename);
122 loaderContext.addDependency(_path.default.normalize(absoluteFilename));
123 return result;
124 }
125 }
126 return {
127 install(lessInstance, pluginManager) {
128 pluginManager.addFileManager(new WebpackFileManager());
129 },
130 minVersion: [3, 0, 0]
131 };
132}
133
134/**
135 * Get the `less` options from the loader context and normalizes its values
136 *
137 * @param {object} loaderContext
138 * @param {object} loaderOptions
139 * @param {object} implementation
140 * @returns {Object}
141 */
142function getLessOptions(loaderContext, loaderOptions, implementation) {
143 const options = typeof loaderOptions.lessOptions === "function" ? loaderOptions.lessOptions(loaderContext) || {} : loaderOptions.lessOptions || {};
144 const lessOptions = {
145 plugins: [],
146 relativeUrls: true,
147 // We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
148 filename: loaderContext.resourcePath,
149 ...options
150 };
151 const plugins = lessOptions.plugins.slice();
152 const shouldUseWebpackImporter = typeof loaderOptions.webpackImporter === "boolean" ? loaderOptions.webpackImporter : true;
153 if (shouldUseWebpackImporter) {
154 plugins.unshift(createWebpackLessPlugin(loaderContext, implementation));
155 }
156 plugins.unshift({
157 install(lessProcessor, pluginManager) {
158 // eslint-disable-next-line no-param-reassign
159 pluginManager.webpackLoaderContext = loaderContext;
160 lessOptions.pluginManager = pluginManager;
161 }
162 });
163 lessOptions.plugins = plugins;
164 return lessOptions;
165}
166function isUnsupportedUrl(url) {
167 // Is Windows path
168 if (IS_NATIVE_WIN32_PATH.test(url)) {
169 return false;
170 }
171
172 // Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
173 // Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
174 return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url);
175}
176function normalizeSourceMap(map) {
177 const newMap = map;
178
179 // map.file is an optional property that provides the output filename.
180 // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
181 // eslint-disable-next-line no-param-reassign
182 delete newMap.file;
183
184 // eslint-disable-next-line no-param-reassign
185 newMap.sourceRoot = "";
186
187 // `less` returns POSIX paths, that's why we need to transform them back to native paths.
188 // eslint-disable-next-line no-param-reassign
189 newMap.sources = newMap.sources.map(source => _path.default.normalize(source));
190 return newMap;
191}
192function getLessImplementation(loaderContext, implementation) {
193 let resolvedImplementation = implementation;
194 if (!implementation || typeof implementation === "string") {
195 const lessImplPkg = implementation || "less";
196
197 // eslint-disable-next-line import/no-dynamic-require, global-require
198 resolvedImplementation = require(lessImplPkg);
199 }
200
201 // eslint-disable-next-line consistent-return
202 return resolvedImplementation;
203}
204function getFileExcerptIfPossible(error) {
205 if (typeof error.extract === "undefined") {
206 return [];
207 }
208 const excerpt = error.extract.slice(0, 2);
209 const column = Math.max(error.column - 1, 0);
210 if (typeof excerpt[0] === "undefined") {
211 excerpt.shift();
212 }
213 excerpt.push(`${new Array(column).join(" ")}^`);
214 return excerpt;
215}
216function errorFactory(error) {
217 const message = ["\n", ...getFileExcerptIfPossible(error), error.message.charAt(0).toUpperCase() + error.message.slice(1), error.filename ? ` Error in ${_path.default.normalize(error.filename)} (line ${error.line}, column ${error.column})` : ""].join("\n");
218 const obj = new Error(message, {
219 cause: error
220 });
221 obj.stack = null;
222 return obj;
223}
\No newline at end of file