ModuleFilenameHelpers.js 15 KB

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