TemplatedPathPlugin.js 10 KB

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