ModuleFilenameHelpers.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const NormalModule = require("./NormalModule");
  7. const createHash = require("./util/createHash");
  8. const memoize = require("./util/memoize");
  9. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  10. /** @typedef {import("./Module")} Module */
  11. /** @typedef {import("./RequestShortener")} RequestShortener */
  12. /** @typedef {typeof import("./util/Hash")} Hash */
  13. /** @typedef {string | RegExp | (string | RegExp)[]} Matcher */
  14. /** @typedef {{test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */
  15. const ModuleFilenameHelpers = module.exports;
  16. // TODO webpack 6: consider removing these
  17. ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
  18. ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE =
  19. /\[all-?loaders\]\[resource\]/gi;
  20. ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
  21. ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
  22. ModuleFilenameHelpers.RESOURCE = "[resource]";
  23. ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
  24. ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
  25. // cSpell:words olute
  26. ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH =
  27. /\[abs(olute)?-?resource-?path\]/gi;
  28. ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
  29. ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
  30. ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";
  31. ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi;
  32. ModuleFilenameHelpers.LOADERS = "[loaders]";
  33. ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi;
  34. ModuleFilenameHelpers.QUERY = "[query]";
  35. ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi;
  36. ModuleFilenameHelpers.ID = "[id]";
  37. ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
  38. ModuleFilenameHelpers.HASH = "[hash]";
  39. ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
  40. ModuleFilenameHelpers.NAMESPACE = "[namespace]";
  41. ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi;
  42. /** @typedef {() => string} ReturnStringCallback */
  43. /**
  44. * Returns a function that returns the part of the string after the token
  45. * @param {ReturnStringCallback} strFn the function to get the string
  46. * @param {string} token the token to search for
  47. * @returns {ReturnStringCallback} a function that returns the part of the string after the token
  48. */
  49. const getAfter = (strFn, token) => () => {
  50. const str = strFn();
  51. const idx = str.indexOf(token);
  52. return idx < 0 ? "" : str.slice(idx);
  53. };
  54. /**
  55. * Returns a function that returns the part of the string before the token
  56. * @param {ReturnStringCallback} strFn the function to get the string
  57. * @param {string} token the token to search for
  58. * @returns {ReturnStringCallback} a function that returns the part of the string before the token
  59. */
  60. const getBefore = (strFn, token) => () => {
  61. const str = strFn();
  62. const idx = str.lastIndexOf(token);
  63. return idx < 0 ? "" : str.slice(0, idx);
  64. };
  65. /**
  66. * Returns a function that returns a hash of the string
  67. * @param {ReturnStringCallback} strFn the function to get the string
  68. * @param {string | Hash=} hashFunction the hash function to use
  69. * @returns {ReturnStringCallback} a function that returns the hash of the string
  70. */
  71. const getHash =
  72. (strFn, hashFunction = "md4") =>
  73. () => {
  74. const hash = createHash(hashFunction);
  75. hash.update(strFn());
  76. const digest = /** @type {string} */ (hash.digest("hex"));
  77. return digest.slice(0, 4);
  78. };
  79. /**
  80. * @template T
  81. * Returns a lazy object. The object is lazy in the sense that the properties are
  82. * only evaluated when they are accessed. This is only obtained by setting a function as the value for each key.
  83. * @param {Record<string, () => T>} obj the object to convert to a lazy access object
  84. * @returns {object} the lazy access object
  85. */
  86. const lazyObject = obj => {
  87. const newObj = {};
  88. for (const key of Object.keys(obj)) {
  89. const fn = obj[key];
  90. Object.defineProperty(newObj, key, {
  91. get: () => fn(),
  92. set: v => {
  93. Object.defineProperty(newObj, key, {
  94. value: v,
  95. enumerable: true,
  96. writable: true
  97. });
  98. },
  99. enumerable: true,
  100. configurable: true
  101. });
  102. }
  103. return newObj;
  104. };
  105. const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
  106. /**
  107. * @param {Module | string} module the module
  108. * @param {TODO} options options
  109. * @param {object} contextInfo context info
  110. * @param {RequestShortener} contextInfo.requestShortener requestShortener
  111. * @param {ChunkGraph} contextInfo.chunkGraph chunk graph
  112. * @param {string | Hash=} contextInfo.hashFunction the hash function to use
  113. * @returns {string} the filename
  114. */
  115. ModuleFilenameHelpers.createFilename = (
  116. // eslint-disable-next-line default-param-last
  117. module = "",
  118. options,
  119. { requestShortener, chunkGraph, hashFunction = "md4" }
  120. ) => {
  121. const opts = {
  122. namespace: "",
  123. moduleFilenameTemplate: "",
  124. ...(typeof options === "object"
  125. ? options
  126. : {
  127. moduleFilenameTemplate: options
  128. })
  129. };
  130. let absoluteResourcePath;
  131. let hash;
  132. /** @type {ReturnStringCallback} */
  133. let identifier;
  134. /** @type {ReturnStringCallback} */
  135. let moduleId;
  136. /** @type {ReturnStringCallback} */
  137. let shortIdentifier;
  138. if (typeof module === "string") {
  139. shortIdentifier =
  140. /** @type {ReturnStringCallback} */
  141. (memoize(() => requestShortener.shorten(module)));
  142. identifier = shortIdentifier;
  143. moduleId = () => "";
  144. absoluteResourcePath = () => module.split("!").pop();
  145. hash = getHash(identifier, hashFunction);
  146. } else {
  147. shortIdentifier = memoize(() =>
  148. module.readableIdentifier(requestShortener)
  149. );
  150. identifier =
  151. /** @type {ReturnStringCallback} */
  152. (memoize(() => requestShortener.shorten(module.identifier())));
  153. moduleId =
  154. /** @type {ReturnStringCallback} */
  155. (() => chunkGraph.getModuleId(module));
  156. absoluteResourcePath = () =>
  157. module instanceof NormalModule
  158. ? module.resource
  159. : module.identifier().split("!").pop();
  160. hash = getHash(identifier, hashFunction);
  161. }
  162. const resource =
  163. /** @type {ReturnStringCallback} */
  164. (memoize(() => shortIdentifier().split("!").pop()));
  165. const loaders = getBefore(shortIdentifier, "!");
  166. const allLoaders = getBefore(identifier, "!");
  167. const query = getAfter(resource, "?");
  168. const resourcePath = () => {
  169. const q = query().length;
  170. return q === 0 ? resource() : resource().slice(0, -q);
  171. };
  172. if (typeof opts.moduleFilenameTemplate === "function") {
  173. return opts.moduleFilenameTemplate(
  174. lazyObject({
  175. identifier,
  176. shortIdentifier,
  177. resource,
  178. resourcePath: memoize(resourcePath),
  179. absoluteResourcePath: memoize(absoluteResourcePath),
  180. loaders: memoize(loaders),
  181. allLoaders: memoize(allLoaders),
  182. query: memoize(query),
  183. moduleId: memoize(moduleId),
  184. hash: memoize(hash),
  185. namespace: () => opts.namespace
  186. })
  187. );
  188. }
  189. // TODO webpack 6: consider removing alternatives without dashes
  190. /** @type {Map<string, function(): string>} */
  191. const replacements = new Map([
  192. ["identifier", identifier],
  193. ["short-identifier", shortIdentifier],
  194. ["resource", resource],
  195. ["resource-path", resourcePath],
  196. // cSpell:words resourcepath
  197. ["resourcepath", resourcePath],
  198. ["absolute-resource-path", absoluteResourcePath],
  199. ["abs-resource-path", absoluteResourcePath],
  200. // cSpell:words absoluteresource
  201. ["absoluteresource-path", absoluteResourcePath],
  202. // cSpell:words absresource
  203. ["absresource-path", absoluteResourcePath],
  204. // cSpell:words resourcepath
  205. ["absolute-resourcepath", absoluteResourcePath],
  206. // cSpell:words resourcepath
  207. ["abs-resourcepath", absoluteResourcePath],
  208. // cSpell:words absoluteresourcepath
  209. ["absoluteresourcepath", absoluteResourcePath],
  210. // cSpell:words absresourcepath
  211. ["absresourcepath", absoluteResourcePath],
  212. ["all-loaders", allLoaders],
  213. // cSpell:words allloaders
  214. ["allloaders", allLoaders],
  215. ["loaders", loaders],
  216. ["query", query],
  217. ["id", moduleId],
  218. ["hash", hash],
  219. ["namespace", () => opts.namespace]
  220. ]);
  221. // TODO webpack 6: consider removing weird double placeholders
  222. return /** @type {string} */ (opts.moduleFilenameTemplate)
  223. .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, "[identifier]")
  224. .replace(
  225. ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE,
  226. "[short-identifier]"
  227. )
  228. .replace(SQUARE_BRACKET_TAG_REGEXP, (match, content) => {
  229. if (content.length + 2 === match.length) {
  230. const replacement = replacements.get(content.toLowerCase());
  231. if (replacement !== undefined) {
  232. return replacement();
  233. }
  234. } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
  235. return `[${match.slice(2, -2)}]`;
  236. }
  237. return match;
  238. });
  239. };
  240. /**
  241. * Replaces duplicate items in an array with new values generated by a callback function.
  242. * The callback function is called with the duplicate item, the index of the duplicate item, and the number of times the item has been replaced.
  243. * The callback function should return the new value for the duplicate item.
  244. * @template T
  245. * @param {T[]} array the array with duplicates to be replaced
  246. * @param {(duplicateItem: T, duplicateItemIndex: number, numberOfTimesReplaced: number) => T} fn callback function to generate new values for the duplicate items
  247. * @param {(firstElement:T, nextElement:T) => -1 | 0 | 1} [comparator] optional comparator function to sort the duplicate items
  248. * @returns {T[]} the array with duplicates replaced
  249. * @example
  250. * ```js
  251. * const array = ["a", "b", "c", "a", "b", "a"];
  252. * const result = ModuleFilenameHelpers.replaceDuplicates(array, (item, index, count) => `${item}-${count}`);
  253. * // result: ["a-1", "b-1", "c", "a-2", "b-2", "a-3"]
  254. * ```
  255. */
  256. ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
  257. const countMap = Object.create(null);
  258. const posMap = Object.create(null);
  259. for (const [idx, item] of array.entries()) {
  260. countMap[item] = countMap[item] || [];
  261. countMap[item].push(idx);
  262. posMap[item] = 0;
  263. }
  264. if (comparator) {
  265. for (const item of Object.keys(countMap)) {
  266. countMap[item].sort(comparator);
  267. }
  268. }
  269. return array.map((item, i) => {
  270. if (countMap[item].length > 1) {
  271. if (comparator && countMap[item][0] === i) return item;
  272. return fn(item, i, posMap[item]++);
  273. }
  274. return item;
  275. });
  276. };
  277. /**
  278. * Tests if a string matches a RegExp or an array of RegExp.
  279. * @param {string} str string to test
  280. * @param {Matcher} test value which will be used to match against the string
  281. * @returns {boolean} true, when the RegExp matches
  282. * @example
  283. * ```js
  284. * ModuleFilenameHelpers.matchPart("foo.js", "foo"); // true
  285. * ModuleFilenameHelpers.matchPart("foo.js", "foo.js"); // true
  286. * ModuleFilenameHelpers.matchPart("foo.js", "foo."); // false
  287. * ModuleFilenameHelpers.matchPart("foo.js", "foo*"); // false
  288. * ModuleFilenameHelpers.matchPart("foo.js", "foo.*"); // true
  289. * ModuleFilenameHelpers.matchPart("foo.js", /^foo/); // true
  290. * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
  291. * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
  292. * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, /^bar/]); // true
  293. * ModuleFilenameHelpers.matchPart("foo.js", [/^baz/, /^bar/]); // false
  294. * ```
  295. */
  296. const matchPart = (str, test) => {
  297. if (!test) return true;
  298. if (Array.isArray(test)) {
  299. return test.some(test => matchPart(str, test));
  300. }
  301. if (typeof test === "string") {
  302. return str.startsWith(test);
  303. }
  304. return test.test(str);
  305. };
  306. ModuleFilenameHelpers.matchPart = matchPart;
  307. /**
  308. * Tests if a string matches a match object. The match object can have the following properties:
  309. * - `test`: a RegExp or an array of RegExp
  310. * - `include`: a RegExp or an array of RegExp
  311. * - `exclude`: a RegExp or an array of RegExp
  312. *
  313. * The `test` property is tested first, then `include` and then `exclude`.
  314. * @param {MatchObject} obj a match object to test against the string
  315. * @param {string} str string to test against the matching object
  316. * @returns {boolean} true, when the object matches
  317. * @example
  318. * ```js
  319. * ModuleFilenameHelpers.matchObject({ test: "foo.js" }, "foo.js"); // true
  320. * ModuleFilenameHelpers.matchObject({ test: /^foo/ }, "foo.js"); // true
  321. * ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "foo.js"); // true
  322. * ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "baz.js"); // false
  323. * ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "foo.js"); // true
  324. * ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "bar.js"); // false
  325. * ModuleFilenameHelpers.matchObject({ include: /^foo/ }, "foo.js"); // true
  326. * ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "foo.js"); // true
  327. * ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "baz.js"); // false
  328. * ModuleFilenameHelpers.matchObject({ exclude: "foo.js" }, "foo.js"); // false
  329. * ModuleFilenameHelpers.matchObject({ exclude: [/^foo/, "bar"] }, "foo.js"); // false
  330. * ```
  331. */
  332. ModuleFilenameHelpers.matchObject = (obj, str) => {
  333. if (obj.test && !ModuleFilenameHelpers.matchPart(str, obj.test)) {
  334. return false;
  335. }
  336. if (obj.include && !ModuleFilenameHelpers.matchPart(str, obj.include)) {
  337. return false;
  338. }
  339. if (obj.exclude && ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
  340. return false;
  341. }
  342. return true;
  343. };