TemplatedPathPlugin.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Jason Anderson @diurnalist
  4. */
  5. "use strict";
  6. const mime = require("mime-types");
  7. const { basename, extname } = require("path");
  8. const util = require("util");
  9. const Chunk = require("./Chunk");
  10. const Module = require("./Module");
  11. const { parseResource } = require("./util/identifier");
  12. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  13. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  14. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  15. /** @typedef {import("./Compilation").PathData} PathData */
  16. /** @typedef {import("./Compiler")} Compiler */
  17. const REGEXP = /\[\\*([\w:]+)\\*\]/gi;
  18. /**
  19. * @param {string | number} id id
  20. * @returns {string | number} result
  21. */
  22. const prepareId = id => {
  23. if (typeof id !== "string") return id;
  24. if (/^"\s\+*.*\+\s*"$/.test(id)) {
  25. const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id);
  26. return `" + (${
  27. /** @type {string[]} */ (match)[1]
  28. } + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`;
  29. }
  30. return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_");
  31. };
  32. /**
  33. * @callback ReplacerFunction
  34. * @param {string} match
  35. * @param {string | undefined} arg
  36. * @param {string} input
  37. */
  38. /**
  39. * @param {ReplacerFunction} replacer replacer
  40. * @param {((arg0: number) => string) | undefined} handler handler
  41. * @param {AssetInfo | undefined} assetInfo asset info
  42. * @param {string} hashName hash name
  43. * @returns {ReplacerFunction} hash replacer function
  44. */
  45. const hashLength = (replacer, handler, assetInfo, hashName) => {
  46. /** @type {ReplacerFunction} */
  47. const fn = (match, arg, input) => {
  48. let result;
  49. const length = arg && Number.parseInt(arg, 10);
  50. if (length && handler) {
  51. result = handler(length);
  52. } else {
  53. const hash = replacer(match, arg, input);
  54. result = length ? hash.slice(0, length) : hash;
  55. }
  56. if (assetInfo) {
  57. assetInfo.immutable = true;
  58. if (Array.isArray(assetInfo[hashName])) {
  59. assetInfo[hashName] = [...assetInfo[hashName], result];
  60. } else if (assetInfo[hashName]) {
  61. assetInfo[hashName] = [assetInfo[hashName], result];
  62. } else {
  63. assetInfo[hashName] = result;
  64. }
  65. }
  66. return result;
  67. };
  68. return fn;
  69. };
  70. /** @typedef {(match: string, arg?: string, input?: string) => string} Replacer */
  71. /**
  72. * @param {string | number | null | undefined | (() => string | number | null | undefined)} value value
  73. * @param {boolean=} allowEmpty allow empty
  74. * @returns {Replacer} replacer
  75. */
  76. const replacer = (value, allowEmpty) => {
  77. /** @type {Replacer} */
  78. const fn = (match, arg, input) => {
  79. if (typeof value === "function") {
  80. value = value();
  81. }
  82. if (value === null || value === undefined) {
  83. if (!allowEmpty) {
  84. throw new Error(
  85. `Path variable ${match} not implemented in this context: ${input}`
  86. );
  87. }
  88. return "";
  89. }
  90. return `${value}`;
  91. };
  92. return fn;
  93. };
  94. const deprecationCache = new Map();
  95. const deprecatedFunction = (() => () => {})();
  96. /**
  97. * @param {Function} fn function
  98. * @param {string} message message
  99. * @param {string} code code
  100. * @returns {function(...any[]): void} function with deprecation output
  101. */
  102. const deprecated = (fn, message, code) => {
  103. let d = deprecationCache.get(message);
  104. if (d === undefined) {
  105. d = util.deprecate(deprecatedFunction, message, code);
  106. deprecationCache.set(message, d);
  107. }
  108. return (...args) => {
  109. d();
  110. return fn(...args);
  111. };
  112. };
  113. /** @typedef {string | function(PathData, AssetInfo=): string} TemplatePath */
  114. /**
  115. * @param {TemplatePath} path the raw path
  116. * @param {PathData} data context data
  117. * @param {AssetInfo | undefined} assetInfo extra info about the asset (will be written to)
  118. * @returns {string} the interpolated path
  119. */
  120. const replacePathVariables = (path, data, assetInfo) => {
  121. const chunkGraph = data.chunkGraph;
  122. /** @type {Map<string, Function>} */
  123. const replacements = new Map();
  124. // Filename context
  125. //
  126. // Placeholders
  127. //
  128. // for /some/path/file.js?query#fragment:
  129. // [file] - /some/path/file.js
  130. // [query] - ?query
  131. // [fragment] - #fragment
  132. // [base] - file.js
  133. // [path] - /some/path/
  134. // [name] - file
  135. // [ext] - .js
  136. if (typeof data.filename === "string") {
  137. // check that filename is data uri
  138. const match = data.filename.match(/^data:([^;,]+)/);
  139. if (match) {
  140. const ext = mime.extension(match[1]);
  141. const emptyReplacer = replacer("", true);
  142. // "XXXX" used for `updateHash`, so we don't need it here
  143. const contentHash =
  144. data.contentHash && !/X+/.test(data.contentHash)
  145. ? data.contentHash
  146. : false;
  147. const baseReplacer = contentHash ? replacer(contentHash) : emptyReplacer;
  148. replacements.set("file", emptyReplacer);
  149. replacements.set("query", emptyReplacer);
  150. replacements.set("fragment", emptyReplacer);
  151. replacements.set("path", emptyReplacer);
  152. replacements.set("base", baseReplacer);
  153. replacements.set("name", baseReplacer);
  154. replacements.set("ext", replacer(ext ? `.${ext}` : "", true));
  155. // Legacy
  156. replacements.set(
  157. "filebase",
  158. deprecated(
  159. baseReplacer,
  160. "[filebase] is now [base]",
  161. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
  162. )
  163. );
  164. } else {
  165. const { path: file, query, fragment } = parseResource(data.filename);
  166. const ext = extname(file);
  167. const base = basename(file);
  168. const name = base.slice(0, base.length - ext.length);
  169. const path = file.slice(0, file.length - base.length);
  170. replacements.set("file", replacer(file));
  171. replacements.set("query", replacer(query, true));
  172. replacements.set("fragment", replacer(fragment, true));
  173. replacements.set("path", replacer(path, true));
  174. replacements.set("base", replacer(base));
  175. replacements.set("name", replacer(name));
  176. replacements.set("ext", replacer(ext, true));
  177. // Legacy
  178. replacements.set(
  179. "filebase",
  180. deprecated(
  181. replacer(base),
  182. "[filebase] is now [base]",
  183. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
  184. )
  185. );
  186. }
  187. }
  188. // Compilation context
  189. //
  190. // Placeholders
  191. //
  192. // [fullhash] - data.hash (3a4b5c6e7f)
  193. //
  194. // Legacy Placeholders
  195. //
  196. // [hash] - data.hash (3a4b5c6e7f)
  197. if (data.hash) {
  198. const hashReplacer = hashLength(
  199. replacer(data.hash),
  200. data.hashWithLength,
  201. assetInfo,
  202. "fullhash"
  203. );
  204. replacements.set("fullhash", hashReplacer);
  205. // Legacy
  206. replacements.set(
  207. "hash",
  208. deprecated(
  209. hashReplacer,
  210. "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)",
  211. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH"
  212. )
  213. );
  214. }
  215. // Chunk Context
  216. //
  217. // Placeholders
  218. //
  219. // [id] - chunk.id (0.js)
  220. // [name] - chunk.name (app.js)
  221. // [chunkhash] - chunk.hash (7823t4t4.js)
  222. // [contenthash] - chunk.contentHash[type] (3256u3zg.js)
  223. if (data.chunk) {
  224. const chunk = data.chunk;
  225. const contentHashType = data.contentHashType;
  226. const idReplacer = replacer(chunk.id);
  227. const nameReplacer = replacer(chunk.name || chunk.id);
  228. const chunkhashReplacer = hashLength(
  229. replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash),
  230. "hashWithLength" in chunk ? chunk.hashWithLength : undefined,
  231. assetInfo,
  232. "chunkhash"
  233. );
  234. const contenthashReplacer = hashLength(
  235. replacer(
  236. data.contentHash ||
  237. (contentHashType &&
  238. chunk.contentHash &&
  239. chunk.contentHash[contentHashType])
  240. ),
  241. data.contentHashWithLength ||
  242. ("contentHashWithLength" in chunk && chunk.contentHashWithLength
  243. ? chunk.contentHashWithLength[/** @type {string} */ (contentHashType)]
  244. : undefined),
  245. assetInfo,
  246. "contenthash"
  247. );
  248. replacements.set("id", idReplacer);
  249. replacements.set("name", nameReplacer);
  250. replacements.set("chunkhash", chunkhashReplacer);
  251. replacements.set("contenthash", contenthashReplacer);
  252. }
  253. // Module Context
  254. //
  255. // Placeholders
  256. //
  257. // [id] - module.id (2.png)
  258. // [hash] - module.hash (6237543873.png)
  259. //
  260. // Legacy Placeholders
  261. //
  262. // [moduleid] - module.id (2.png)
  263. // [modulehash] - module.hash (6237543873.png)
  264. if (data.module) {
  265. const module = data.module;
  266. const idReplacer = replacer(() =>
  267. prepareId(
  268. module instanceof Module
  269. ? /** @type {ModuleId} */
  270. (/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
  271. : module.id
  272. )
  273. );
  274. const moduleHashReplacer = hashLength(
  275. replacer(() =>
  276. module instanceof Module
  277. ? /** @type {ChunkGraph} */
  278. (chunkGraph).getRenderedModuleHash(module, data.runtime)
  279. : module.hash
  280. ),
  281. "hashWithLength" in module ? module.hashWithLength : undefined,
  282. assetInfo,
  283. "modulehash"
  284. );
  285. const contentHashReplacer = hashLength(
  286. replacer(/** @type {string} */ (data.contentHash)),
  287. undefined,
  288. assetInfo,
  289. "contenthash"
  290. );
  291. replacements.set("id", idReplacer);
  292. replacements.set("modulehash", moduleHashReplacer);
  293. replacements.set("contenthash", contentHashReplacer);
  294. replacements.set(
  295. "hash",
  296. data.contentHash ? contentHashReplacer : moduleHashReplacer
  297. );
  298. // Legacy
  299. replacements.set(
  300. "moduleid",
  301. deprecated(
  302. idReplacer,
  303. "[moduleid] is now [id]",
  304. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID"
  305. )
  306. );
  307. }
  308. // Other things
  309. if (data.url) {
  310. replacements.set("url", replacer(data.url));
  311. }
  312. if (typeof data.runtime === "string") {
  313. replacements.set(
  314. "runtime",
  315. replacer(() => prepareId(/** @type {string} */ (data.runtime)))
  316. );
  317. } else {
  318. replacements.set("runtime", replacer("_"));
  319. }
  320. if (typeof path === "function") {
  321. path = path(data, assetInfo);
  322. }
  323. path = path.replace(REGEXP, (match, content) => {
  324. if (content.length + 2 === match.length) {
  325. const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content);
  326. if (!contentMatch) return match;
  327. const [, kind, arg] = contentMatch;
  328. const replacer = replacements.get(kind);
  329. if (replacer !== undefined) {
  330. return replacer(match, arg, path);
  331. }
  332. } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
  333. return `[${match.slice(2, -2)}]`;
  334. }
  335. return match;
  336. });
  337. return path;
  338. };
  339. const plugin = "TemplatedPathPlugin";
  340. class TemplatedPathPlugin {
  341. /**
  342. * Apply the plugin
  343. * @param {Compiler} compiler the compiler instance
  344. * @returns {void}
  345. */
  346. apply(compiler) {
  347. compiler.hooks.compilation.tap(plugin, compilation => {
  348. compilation.hooks.assetPath.tap(plugin, replacePathVariables);
  349. });
  350. }
  351. }
  352. module.exports = TemplatedPathPlugin;