ModuleFilenameHelpers.js 13 KB

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