utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. "use strict";
  2. const NativeModule = require("module");
  3. const path = require("path");
  4. /** @typedef {import("webpack").Compilation} Compilation */
  5. /** @typedef {import("webpack").Module} Module */
  6. // eslint-disable-next-line jsdoc/no-restricted-syntax
  7. /** @typedef {import("webpack").LoaderContext<any>} LoaderContext */
  8. /**
  9. * @returns {boolean} always returns true
  10. */
  11. function trueFn() {
  12. return true;
  13. }
  14. /**
  15. * @param {Compilation} compilation compilation
  16. * @param {string | number} id module id
  17. * @returns {null | Module} the found module
  18. */
  19. function findModuleById(compilation, id) {
  20. const {
  21. modules,
  22. chunkGraph
  23. } = compilation;
  24. for (const module of modules) {
  25. const moduleId = typeof chunkGraph !== "undefined" ? chunkGraph.getModuleId(module) : module.id;
  26. if (moduleId === id) {
  27. return module;
  28. }
  29. }
  30. return null;
  31. }
  32. // eslint-disable-next-line jsdoc/no-restricted-syntax
  33. /**
  34. * @param {LoaderContext} loaderContext loader context
  35. * @param {string | Buffer} code code
  36. * @param {string} filename filename
  37. * @returns {Record<string, any>} exports of a module
  38. */
  39. function evalModuleCode(loaderContext, code, filename) {
  40. // @ts-expect-error
  41. const module = new NativeModule(filename, loaderContext);
  42. // @ts-expect-error
  43. module.paths = NativeModule._nodeModulePaths(loaderContext.context);
  44. module.filename = filename;
  45. // @ts-expect-error
  46. module._compile(code, filename);
  47. return module.exports;
  48. }
  49. /**
  50. * @param {string} a a
  51. * @param {string} b b
  52. * @returns {0 | 1 | -1} result of comparing
  53. */
  54. function compareIds(a, b) {
  55. if (typeof a !== typeof b) {
  56. return typeof a < typeof b ? -1 : 1;
  57. }
  58. if (a < b) {
  59. return -1;
  60. }
  61. if (a > b) {
  62. return 1;
  63. }
  64. return 0;
  65. }
  66. /**
  67. * @param {Module} a a
  68. * @param {Module} b b
  69. * @returns {0 | 1 | -1} result of comparing
  70. */
  71. function compareModulesByIdentifier(a, b) {
  72. return compareIds(a.identifier(), b.identifier());
  73. }
  74. const MODULE_TYPE = "css/mini-extract";
  75. const AUTO_PUBLIC_PATH = "__mini_css_extract_plugin_public_path_auto__";
  76. const ABSOLUTE_PUBLIC_PATH = "webpack:///mini-css-extract-plugin/";
  77. const BASE_URI = "webpack://";
  78. const SINGLE_DOT_PATH_SEGMENT = "__mini_css_extract_plugin_single_dot_path_segment__";
  79. /**
  80. * @param {string} str path
  81. * @returns {boolean} true when path is absolute, otherwise false
  82. */
  83. function isAbsolutePath(str) {
  84. return path.posix.isAbsolute(str) || path.win32.isAbsolute(str);
  85. }
  86. const RELATIVE_PATH_REGEXP = /^\.\.?[/\\]/;
  87. /**
  88. * @param {string} str string
  89. * @returns {boolean} true when path is relative, otherwise false
  90. */
  91. function isRelativePath(str) {
  92. return RELATIVE_PATH_REGEXP.test(str);
  93. }
  94. // TODO simplify for the next major release
  95. /**
  96. * @param {LoaderContext} loaderContext the loader context
  97. * @param {string} request a request
  98. * @returns {string} a stringified request
  99. */
  100. function stringifyRequest(loaderContext, request) {
  101. if (typeof loaderContext.utils !== "undefined" && typeof loaderContext.utils.contextify === "function") {
  102. return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request));
  103. }
  104. const splitted = request.split("!");
  105. const {
  106. context
  107. } = loaderContext;
  108. return JSON.stringify(splitted.map(part => {
  109. // First, separate singlePath from query, because the query might contain paths again
  110. const splittedPart = part.match(/^(.*?)(\?.*)/);
  111. const query = splittedPart ? splittedPart[2] : "";
  112. let singlePath = splittedPart ? splittedPart[1] : part;
  113. if (isAbsolutePath(singlePath) && context) {
  114. singlePath = path.relative(context, singlePath);
  115. if (isAbsolutePath(singlePath)) {
  116. // If singlePath still matches an absolute path, singlePath was on a different drive than context.
  117. // In this case, we leave the path platform-specific without replacing any separators.
  118. // @see https://github.com/webpack/loader-utils/pull/14
  119. return singlePath + query;
  120. }
  121. if (isRelativePath(singlePath) === false) {
  122. // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
  123. singlePath = `./${singlePath}`;
  124. }
  125. }
  126. return singlePath.replace(/\\/g, "/") + query;
  127. }).join("!"));
  128. }
  129. /**
  130. * @param {string} filename filename
  131. * @param {string} outputPath output path
  132. * @param {boolean} enforceRelative true when need to enforce relative path, otherwise false
  133. * @returns {string} undo path
  134. */
  135. function getUndoPath(filename, outputPath, enforceRelative) {
  136. let depth = -1;
  137. let append = "";
  138. outputPath = outputPath.replace(/[\\/]$/, "");
  139. for (const part of filename.split(/[/\\]+/)) {
  140. if (part === "..") {
  141. if (depth > -1) {
  142. depth--;
  143. } else {
  144. const i = outputPath.lastIndexOf("/");
  145. const j = outputPath.lastIndexOf("\\");
  146. const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j);
  147. if (pos < 0) {
  148. return `${outputPath}/`;
  149. }
  150. append = `${outputPath.slice(pos + 1)}/${append}`;
  151. outputPath = outputPath.slice(0, pos);
  152. }
  153. } else if (part !== ".") {
  154. depth++;
  155. }
  156. }
  157. return depth > 0 ? `${"../".repeat(depth)}${append}` : enforceRelative ? `./${append}` : append;
  158. }
  159. // eslint-disable-next-line jsdoc/no-restricted-syntax
  160. /**
  161. * @param {string | Function} value local
  162. * @returns {string} stringified local
  163. */
  164. function stringifyLocal(value) {
  165. return typeof value === "function" ? value.toString() : JSON.stringify(value);
  166. }
  167. /**
  168. * @param {string} str string
  169. * @returns {string} string
  170. */
  171. const toSimpleString = str => {
  172. // eslint-disable-next-line no-implicit-coercion
  173. if (`${+str}` === str) {
  174. return str;
  175. }
  176. return JSON.stringify(str);
  177. };
  178. /**
  179. * @param {string} str string
  180. * @returns {string} quoted meta
  181. */
  182. const quoteMeta = str => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
  183. /**
  184. * @param {Array<string>} items items
  185. * @returns {string} common prefix
  186. */
  187. const getCommonPrefix = items => {
  188. let [prefix] = items;
  189. for (let i = 1; i < items.length; i++) {
  190. const item = items[i];
  191. for (let prefixIndex = 0; prefixIndex < prefix.length; prefixIndex++) {
  192. if (item[prefixIndex] !== prefix[prefixIndex]) {
  193. prefix = prefix.slice(0, prefixIndex);
  194. break;
  195. }
  196. }
  197. }
  198. return prefix;
  199. };
  200. /**
  201. * @param {Array<string>} items items
  202. * @returns {string} common suffix
  203. */
  204. const getCommonSuffix = items => {
  205. let [suffix] = items;
  206. for (let i = 1; i < items.length; i++) {
  207. const item = items[i];
  208. for (let itemIndex = item.length - 1, suffixIndex = suffix.length - 1; suffixIndex >= 0; itemIndex--, suffixIndex--) {
  209. if (item[itemIndex] !== suffix[suffixIndex]) {
  210. suffix = suffix.slice(suffixIndex + 1);
  211. break;
  212. }
  213. }
  214. }
  215. return suffix;
  216. };
  217. /**
  218. * @param {Set<string>} itemsSet items set
  219. * @param {(str: string) => string | false} getKey get key function
  220. * @param {(str: Array<string>) => boolean} condition condition
  221. * @returns {Array<Array<string>>} list of common items
  222. */
  223. const popCommonItems = (itemsSet, getKey, condition) => {
  224. /** @type {Map<string, Array<string>>} */
  225. const map = new Map();
  226. for (const item of itemsSet) {
  227. const key = getKey(item);
  228. if (key) {
  229. let list = map.get(key);
  230. if (list === undefined) {
  231. /** @type {Array<string>} */
  232. list = [];
  233. map.set(key, list);
  234. }
  235. list.push(item);
  236. }
  237. }
  238. /** @type {Array<Array<string>>} */
  239. const result = [];
  240. for (const list of map.values()) {
  241. if (condition(list)) {
  242. for (const item of list) {
  243. itemsSet.delete(item);
  244. }
  245. result.push(list);
  246. }
  247. }
  248. return result;
  249. };
  250. /**
  251. * @param {Array<string>} itemsArr array of items
  252. * @returns {string} regexp
  253. */
  254. const itemsToRegexp = itemsArr => {
  255. if (itemsArr.length === 1) {
  256. return quoteMeta(itemsArr[0]);
  257. }
  258. /** @type {Array<string>} */
  259. const finishedItems = [];
  260. // merge single char items: (a|b|c|d|ef) => ([abcd]|ef)
  261. let countOfSingleCharItems = 0;
  262. for (const item of itemsArr) {
  263. if (item.length === 1) {
  264. countOfSingleCharItems++;
  265. }
  266. }
  267. // special case for only single char items
  268. if (countOfSingleCharItems === itemsArr.length) {
  269. return `[${quoteMeta(itemsArr.sort().join(""))}]`;
  270. }
  271. const items = new Set(itemsArr.sort());
  272. if (countOfSingleCharItems > 2) {
  273. let singleCharItems = "";
  274. for (const item of items) {
  275. if (item.length === 1) {
  276. singleCharItems += item;
  277. items.delete(item);
  278. }
  279. }
  280. finishedItems.push(`[${quoteMeta(singleCharItems)}]`);
  281. }
  282. // special case for 2 items with common prefix/suffix
  283. if (finishedItems.length === 0 && items.size === 2) {
  284. const prefix = getCommonPrefix(itemsArr);
  285. const suffix = getCommonSuffix(itemsArr.map(item => item.slice(prefix.length)));
  286. if (prefix.length > 0 || suffix.length > 0) {
  287. return `${quoteMeta(prefix)}${itemsToRegexp(itemsArr.map(i => i.slice(prefix.length, -suffix.length || undefined)))}${quoteMeta(suffix)}`;
  288. }
  289. }
  290. // special case for 2 items with common suffix
  291. if (finishedItems.length === 0 && items.size === 2) {
  292. /** @type {Iterator<string>} */
  293. const it = items[Symbol.iterator]();
  294. const a = it.next().value;
  295. const b = it.next().value;
  296. if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) {
  297. return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta(a.slice(-1))}`;
  298. }
  299. }
  300. // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5)
  301. const prefixed = popCommonItems(items, item => item.length >= 1 ? item[0] : false, list => {
  302. if (list.length >= 3) return true;
  303. if (list.length <= 1) return false;
  304. return list[0][1] === list[1][1];
  305. });
  306. for (const prefixedItems of prefixed) {
  307. const prefix = getCommonPrefix(prefixedItems);
  308. finishedItems.push(`${quoteMeta(prefix)}${itemsToRegexp(prefixedItems.map(i => i.slice(prefix.length)))}`);
  309. }
  310. // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2)
  311. const suffixed = popCommonItems(items, item => item.length >= 1 ? item.slice(-1) : false, list => {
  312. if (list.length >= 3) return true;
  313. if (list.length <= 1) return false;
  314. return list[0].slice(-2) === list[1].slice(-2);
  315. });
  316. for (const suffixedItems of suffixed) {
  317. const suffix = getCommonSuffix(suffixedItems);
  318. finishedItems.push(`${itemsToRegexp(suffixedItems.map(i => i.slice(0, -suffix.length)))}${quoteMeta(suffix)}`);
  319. }
  320. // TODO further optimize regexp, i. e.
  321. // use ranges: (1|2|3|4|a) => [1-4a]
  322. const conditional = [...finishedItems, ...Array.from(items, quoteMeta)];
  323. if (conditional.length === 1) return conditional[0];
  324. return `(${conditional.join("|")})`;
  325. };
  326. /**
  327. * @param {string[]} positiveItems positive items
  328. * @param {string[]} negativeItems negative items
  329. * @returns {(val: string) => string} a template function to determine the value at runtime
  330. */
  331. const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => {
  332. if (positiveItems.length === 0) {
  333. return () => "false";
  334. }
  335. if (negativeItems.length === 0) {
  336. return () => "true";
  337. }
  338. if (positiveItems.length === 1) {
  339. return value => `${toSimpleString(positiveItems[0])} == ${value}`;
  340. }
  341. if (negativeItems.length === 1) {
  342. return value => `${toSimpleString(negativeItems[0])} != ${value}`;
  343. }
  344. const positiveRegexp = itemsToRegexp(positiveItems);
  345. const negativeRegexp = itemsToRegexp(negativeItems);
  346. if (positiveRegexp.length <= negativeRegexp.length) {
  347. return value => `/^${positiveRegexp}$/.test(${value})`;
  348. }
  349. return value => `!/^${negativeRegexp}$/.test(${value})`;
  350. };
  351. // TODO simplify in the next major release and use it from webpack
  352. /**
  353. * @param {Record<string | number, boolean>} map value map
  354. * @returns {boolean | ((value: string) => string)} true/false, when unconditionally true/false, or a template function to determine the value at runtime
  355. */
  356. const compileBooleanMatcher = map => {
  357. const positiveItems = Object.keys(map).filter(i => map[i]);
  358. const negativeItems = Object.keys(map).filter(i => !map[i]);
  359. if (positiveItems.length === 0) {
  360. return false;
  361. }
  362. if (negativeItems.length === 0) {
  363. return true;
  364. }
  365. return compileBooleanMatcherFromLists(positiveItems, negativeItems);
  366. };
  367. module.exports = {
  368. ABSOLUTE_PUBLIC_PATH,
  369. AUTO_PUBLIC_PATH,
  370. BASE_URI,
  371. MODULE_TYPE,
  372. SINGLE_DOT_PATH_SEGMENT,
  373. compareModulesByIdentifier,
  374. compileBooleanMatcher,
  375. evalModuleCode,
  376. findModuleById,
  377. getUndoPath,
  378. stringifyLocal,
  379. stringifyRequest,
  380. trueFn
  381. };