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 { DEFAULTS } = require("./config/defaults");
  8. const createHash = require("./util/createHash");
  9. const memoize = require("./util/memoize");
  10. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  11. /** @typedef {import("./Module")} Module */
  12. /** @typedef {import("./RequestShortener")} RequestShortener */
  13. /** @typedef {typeof import("./util/Hash")} Hash */
  14. /** @typedef {string | RegExp | (string | RegExp)[]} Matcher */
  15. /** @typedef {{ test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */
  16. const ModuleFilenameHelpers = module.exports;
  17. // TODO webpack 6: consider removing these
  18. ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
  19. ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE =
  20. /\[all-?loaders\]\[resource\]/gi;
  21. ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
  22. ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
  23. ModuleFilenameHelpers.RESOURCE = "[resource]";
  24. ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
  25. ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
  26. // cSpell:words olute
  27. ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH =
  28. /\[abs(olute)?-?resource-?path\]/gi;
  29. ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
  30. ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
  31. ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";
  32. ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi;
  33. ModuleFilenameHelpers.LOADERS = "[loaders]";
  34. ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi;
  35. ModuleFilenameHelpers.QUERY = "[query]";
  36. ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi;
  37. ModuleFilenameHelpers.ID = "[id]";
  38. ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
  39. ModuleFilenameHelpers.HASH = "[hash]";
  40. ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
  41. ModuleFilenameHelpers.NAMESPACE = "[namespace]";
  42. ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi;
  43. /** @typedef {() => string} ReturnStringCallback */
  44. /**
  45. * Returns a function that returns the part of the string after the token
  46. * @param {ReturnStringCallback} strFn the function to get the string
  47. * @param {string} token the token to search for
  48. * @returns {ReturnStringCallback} a function that returns the part of the string after the token
  49. */
  50. const getAfter = (strFn, token) => () => {
  51. const str = strFn();
  52. const idx = str.indexOf(token);
  53. return idx < 0 ? "" : str.slice(idx);
  54. };
  55. /**
  56. * Returns a function that returns the part of the string before the token
  57. * @param {ReturnStringCallback} strFn the function to get the string
  58. * @param {string} token the token to search for
  59. * @returns {ReturnStringCallback} a function that returns the part of the string before the token
  60. */
  61. const getBefore = (strFn, token) => () => {
  62. const str = strFn();
  63. const idx = str.lastIndexOf(token);
  64. return idx < 0 ? "" : str.slice(0, idx);
  65. };
  66. /**
  67. * Returns a function that returns a hash of the string
  68. * @param {ReturnStringCallback} strFn the function to get the string
  69. * @param {string | Hash=} hashFunction the hash function to use
  70. * @returns {ReturnStringCallback} a function that returns the hash of the string
  71. */
  72. const getHash =
  73. (strFn, hashFunction = DEFAULTS.HASH_FUNCTION) =>
  74. () => {
  75. const hash = createHash(hashFunction);
  76. hash.update(strFn());
  77. const digest = /** @type {string} */ (hash.digest("hex"));
  78. return digest.slice(0, 4);
  79. };
  80. /**
  81. * @template T
  82. * Returns a lazy object. The object is lazy in the sense that the properties are
  83. * only evaluated when they are accessed. This is only obtained by setting a function as the value for each key.
  84. * @param {Record<string, () => T>} obj the object to convert to a lazy access object
  85. * @returns {T} the lazy access object
  86. */
  87. const lazyObject = obj => {
  88. const newObj = /** @type {T} */ ({});
  89. for (const key of Object.keys(obj)) {
  90. const fn = obj[key];
  91. Object.defineProperty(newObj, key, {
  92. get: () => fn(),
  93. set: v => {
  94. Object.defineProperty(newObj, key, {
  95. value: v,
  96. enumerable: true,
  97. writable: true
  98. });
  99. },
  100. enumerable: true,
  101. configurable: true
  102. });
  103. }
  104. return newObj;
  105. };
  106. const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
  107. /**
  108. * @param {Module | string} module the module
  109. * @param {{ namespace?: string, moduleFilenameTemplate?: string | TODO }} options options
  110. * @param {{ requestShortener: RequestShortener, chunkGraph: ChunkGraph, hashFunction?: string | Hash }} contextInfo context info
  111. * @returns {string} the filename
  112. */
  113. ModuleFilenameHelpers.createFilename = (
  114. // eslint-disable-next-line default-param-last
  115. module = "",
  116. options,
  117. { requestShortener, chunkGraph, hashFunction = DEFAULTS.HASH_FUNCTION }
  118. ) => {
  119. const opts = {
  120. namespace: "",
  121. moduleFilenameTemplate: "",
  122. ...(typeof options === "object"
  123. ? options
  124. : {
  125. moduleFilenameTemplate: options
  126. })
  127. };
  128. /** @type {ReturnStringCallback} */
  129. let absoluteResourcePath;
  130. let hash;
  131. /** @type {ReturnStringCallback} */
  132. let identifier;
  133. /** @type {ReturnStringCallback} */
  134. let moduleId;
  135. /** @type {ReturnStringCallback} */
  136. let shortIdentifier;
  137. if (typeof module === "string") {
  138. shortIdentifier =
  139. /** @type {ReturnStringCallback} */
  140. (memoize(() => requestShortener.shorten(module)));
  141. identifier = shortIdentifier;
  142. moduleId = () => "";
  143. absoluteResourcePath = () =>
  144. /** @type {string} */ (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. : /** @type {string} */ (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, () => 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. };