utils.js 7.2 KB

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