SourceMapDevToolPlugin.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("neo-async");
  7. const { ConcatSource, RawSource } = require("webpack-sources");
  8. const Compilation = require("./Compilation");
  9. const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
  10. const ProgressPlugin = require("./ProgressPlugin");
  11. const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
  12. const createSchemaValidation = require("./util/create-schema-validation");
  13. const createHash = require("./util/createHash");
  14. const { relative, dirname } = require("./util/fs");
  15. const generateDebugId = require("./util/generateDebugId");
  16. const { makePathsAbsolute } = require("./util/identifier");
  17. /** @typedef {import("webpack-sources").MapOptions} MapOptions */
  18. /** @typedef {import("webpack-sources").Source} Source */
  19. /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
  20. /** @typedef {import("./Cache").Etag} Etag */
  21. /** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */
  22. /** @typedef {import("./Chunk")} Chunk */
  23. /** @typedef {import("./Compilation").Asset} Asset */
  24. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  25. /** @typedef {import("./Compiler")} Compiler */
  26. /** @typedef {import("./Module")} Module */
  27. /** @typedef {import("./NormalModule").SourceMap} SourceMap */
  28. /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
  29. /** @typedef {import("./util/Hash")} Hash */
  30. /** @typedef {import("./util/createHash").Algorithm} Algorithm */
  31. /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
  32. const validate = createSchemaValidation(
  33. require("../schemas/plugins/SourceMapDevToolPlugin.check.js"),
  34. () => require("../schemas/plugins/SourceMapDevToolPlugin.json"),
  35. {
  36. name: "SourceMap DevTool Plugin",
  37. baseDataPath: "options"
  38. }
  39. );
  40. /**
  41. * @typedef {object} SourceMapTask
  42. * @property {Source} asset
  43. * @property {AssetInfo} assetInfo
  44. * @property {(string | Module)[]} modules
  45. * @property {string} source
  46. * @property {string} file
  47. * @property {SourceMap} sourceMap
  48. * @property {ItemCacheFacade} cacheItem cache item
  49. */
  50. const METACHARACTERS_REGEXP = /[-[\]\\/{}()*+?.^$|]/g;
  51. const CONTENT_HASH_DETECT_REGEXP = /\[contenthash(:\w+)?\]/;
  52. const CSS_AND_JS_MODULE_EXTENSIONS_REGEXP = /\.((c|m)?js|css)($|\?)/i;
  53. const CSS_EXTENSION_DETECT_REGEXP = /\.css($|\?)/i;
  54. const MAP_URL_COMMENT_REGEXP = /\[map\]/g;
  55. const URL_COMMENT_REGEXP = /\[url\]/g;
  56. const URL_FORMATTING_REGEXP = /^\n\/\/(.*)$/;
  57. /**
  58. * Reset's .lastIndex of stateful Regular Expressions
  59. * For when `test` or `exec` is called on them
  60. * @param {RegExp} regexp Stateful Regular Expression to be reset
  61. * @returns {void}
  62. */
  63. const resetRegexpState = regexp => {
  64. regexp.lastIndex = -1;
  65. };
  66. /**
  67. * Escapes regular expression metacharacters
  68. * @param {string} str String to quote
  69. * @returns {string} Escaped string
  70. */
  71. const quoteMeta = str => str.replace(METACHARACTERS_REGEXP, "\\$&");
  72. /**
  73. * Creating {@link SourceMapTask} for given file
  74. * @param {string} file current compiled file
  75. * @param {Source} asset the asset
  76. * @param {AssetInfo} assetInfo the asset info
  77. * @param {MapOptions} options source map options
  78. * @param {Compilation} compilation compilation instance
  79. * @param {ItemCacheFacade} cacheItem cache item
  80. * @returns {SourceMapTask | undefined} created task instance or `undefined`
  81. */
  82. const getTaskForFile = (
  83. file,
  84. asset,
  85. assetInfo,
  86. options,
  87. compilation,
  88. cacheItem
  89. ) => {
  90. let source;
  91. /** @type {SourceMap} */
  92. let sourceMap;
  93. /**
  94. * Check if asset can build source map
  95. */
  96. if (asset.sourceAndMap) {
  97. const sourceAndMap = asset.sourceAndMap(options);
  98. sourceMap = /** @type {SourceMap} */ (sourceAndMap.map);
  99. source = sourceAndMap.source;
  100. } else {
  101. sourceMap = /** @type {SourceMap} */ (asset.map(options));
  102. source = asset.source();
  103. }
  104. if (!sourceMap || typeof source !== "string") return;
  105. const context = /** @type {string} */ (compilation.options.context);
  106. const root = compilation.compiler.root;
  107. const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root);
  108. const modules = sourceMap.sources.map(source => {
  109. if (!source.startsWith("webpack://")) return source;
  110. source = cachedAbsolutify(source.slice(10));
  111. const module = compilation.findModule(source);
  112. return module || source;
  113. });
  114. return {
  115. file,
  116. asset,
  117. source,
  118. assetInfo,
  119. sourceMap,
  120. modules,
  121. cacheItem
  122. };
  123. };
  124. class SourceMapDevToolPlugin {
  125. /**
  126. * @param {SourceMapDevToolPluginOptions} [options] options object
  127. * @throws {Error} throws error, if got more than 1 arguments
  128. */
  129. constructor(options = {}) {
  130. validate(options);
  131. this.sourceMapFilename = /** @type {string | false} */ (options.filename);
  132. /** @type {false | TemplatePath}} */
  133. this.sourceMappingURLComment =
  134. options.append === false
  135. ? false
  136. : // eslint-disable-next-line no-useless-concat
  137. options.append || "\n//# source" + "MappingURL=[url]";
  138. this.moduleFilenameTemplate =
  139. options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]";
  140. this.fallbackModuleFilenameTemplate =
  141. options.fallbackModuleFilenameTemplate ||
  142. "webpack://[namespace]/[resourcePath]?[hash]";
  143. this.namespace = options.namespace || "";
  144. this.options = options;
  145. }
  146. /**
  147. * Apply the plugin
  148. * @param {Compiler} compiler compiler instance
  149. * @returns {void}
  150. */
  151. apply(compiler) {
  152. const outputFs = /** @type {OutputFileSystem} */ (
  153. compiler.outputFileSystem
  154. );
  155. const sourceMapFilename = this.sourceMapFilename;
  156. const sourceMappingURLComment = this.sourceMappingURLComment;
  157. const moduleFilenameTemplate = this.moduleFilenameTemplate;
  158. const namespace = this.namespace;
  159. const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
  160. const requestShortener = compiler.requestShortener;
  161. const options = this.options;
  162. options.test = options.test || CSS_AND_JS_MODULE_EXTENSIONS_REGEXP;
  163. const matchObject = ModuleFilenameHelpers.matchObject.bind(
  164. undefined,
  165. options
  166. );
  167. compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => {
  168. new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
  169. compilation.hooks.processAssets.tapAsync(
  170. {
  171. name: "SourceMapDevToolPlugin",
  172. stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
  173. additionalAssets: true
  174. },
  175. (assets, callback) => {
  176. const chunkGraph = compilation.chunkGraph;
  177. const cache = compilation.getCache("SourceMapDevToolPlugin");
  178. /** @type {Map<string | Module, string>} */
  179. const moduleToSourceNameMapping = new Map();
  180. const reportProgress =
  181. ProgressPlugin.getReporter(compilation.compiler) || (() => {});
  182. /** @type {Map<string, Chunk>} */
  183. const fileToChunk = new Map();
  184. for (const chunk of compilation.chunks) {
  185. for (const file of chunk.files) {
  186. fileToChunk.set(file, chunk);
  187. }
  188. for (const file of chunk.auxiliaryFiles) {
  189. fileToChunk.set(file, chunk);
  190. }
  191. }
  192. /** @type {string[]} */
  193. const files = [];
  194. for (const file of Object.keys(assets)) {
  195. if (matchObject(file)) {
  196. files.push(file);
  197. }
  198. }
  199. reportProgress(0);
  200. /** @type {SourceMapTask[]} */
  201. const tasks = [];
  202. let fileIndex = 0;
  203. asyncLib.each(
  204. files,
  205. (file, callback) => {
  206. const asset =
  207. /** @type {Readonly<Asset>} */
  208. (compilation.getAsset(file));
  209. if (asset.info.related && asset.info.related.sourceMap) {
  210. fileIndex++;
  211. return callback();
  212. }
  213. const chunk = fileToChunk.get(file);
  214. const sourceMapNamespace = compilation.getPath(this.namespace, {
  215. chunk
  216. });
  217. const cacheItem = cache.getItemCache(
  218. file,
  219. cache.mergeEtags(
  220. cache.getLazyHashedEtag(asset.source),
  221. sourceMapNamespace
  222. )
  223. );
  224. cacheItem.get((err, cacheEntry) => {
  225. if (err) {
  226. return callback(err);
  227. }
  228. /**
  229. * If presented in cache, reassigns assets. Cache assets already have source maps.
  230. */
  231. if (cacheEntry) {
  232. const { assets, assetsInfo } = cacheEntry;
  233. for (const cachedFile of Object.keys(assets)) {
  234. if (cachedFile === file) {
  235. compilation.updateAsset(
  236. cachedFile,
  237. assets[cachedFile],
  238. assetsInfo[cachedFile]
  239. );
  240. } else {
  241. compilation.emitAsset(
  242. cachedFile,
  243. assets[cachedFile],
  244. assetsInfo[cachedFile]
  245. );
  246. }
  247. /**
  248. * Add file to chunk, if not presented there
  249. */
  250. if (cachedFile !== file && chunk !== undefined)
  251. chunk.auxiliaryFiles.add(cachedFile);
  252. }
  253. reportProgress(
  254. (0.5 * ++fileIndex) / files.length,
  255. file,
  256. "restored cached SourceMap"
  257. );
  258. return callback();
  259. }
  260. reportProgress(
  261. (0.5 * fileIndex) / files.length,
  262. file,
  263. "generate SourceMap"
  264. );
  265. /** @type {SourceMapTask | undefined} */
  266. const task = getTaskForFile(
  267. file,
  268. asset.source,
  269. asset.info,
  270. {
  271. module: options.module,
  272. columns: options.columns
  273. },
  274. compilation,
  275. cacheItem
  276. );
  277. if (task) {
  278. const modules = task.modules;
  279. for (let idx = 0; idx < modules.length; idx++) {
  280. const module = modules[idx];
  281. if (
  282. typeof module === "string" &&
  283. /^(data|https?):/.test(module)
  284. ) {
  285. moduleToSourceNameMapping.set(module, module);
  286. continue;
  287. }
  288. if (!moduleToSourceNameMapping.get(module)) {
  289. moduleToSourceNameMapping.set(
  290. module,
  291. ModuleFilenameHelpers.createFilename(
  292. module,
  293. {
  294. moduleFilenameTemplate,
  295. namespace: sourceMapNamespace
  296. },
  297. {
  298. requestShortener,
  299. chunkGraph,
  300. hashFunction: compilation.outputOptions.hashFunction
  301. }
  302. )
  303. );
  304. }
  305. }
  306. tasks.push(task);
  307. }
  308. reportProgress(
  309. (0.5 * ++fileIndex) / files.length,
  310. file,
  311. "generated SourceMap"
  312. );
  313. callback();
  314. });
  315. },
  316. err => {
  317. if (err) {
  318. return callback(err);
  319. }
  320. reportProgress(0.5, "resolve sources");
  321. /** @type {Set<string>} */
  322. const usedNamesSet = new Set(moduleToSourceNameMapping.values());
  323. /** @type {Set<string>} */
  324. const conflictDetectionSet = new Set();
  325. /**
  326. * all modules in defined order (longest identifier first)
  327. * @type {Array<string | Module>}
  328. */
  329. const allModules = Array.from(
  330. moduleToSourceNameMapping.keys()
  331. ).sort((a, b) => {
  332. const ai = typeof a === "string" ? a : a.identifier();
  333. const bi = typeof b === "string" ? b : b.identifier();
  334. return ai.length - bi.length;
  335. });
  336. // find modules with conflicting source names
  337. for (let idx = 0; idx < allModules.length; idx++) {
  338. const module = allModules[idx];
  339. let sourceName =
  340. /** @type {string} */
  341. (moduleToSourceNameMapping.get(module));
  342. let hasName = conflictDetectionSet.has(sourceName);
  343. if (!hasName) {
  344. conflictDetectionSet.add(sourceName);
  345. continue;
  346. }
  347. // try the fallback name first
  348. sourceName = ModuleFilenameHelpers.createFilename(
  349. module,
  350. {
  351. moduleFilenameTemplate: fallbackModuleFilenameTemplate,
  352. namespace
  353. },
  354. {
  355. requestShortener,
  356. chunkGraph,
  357. hashFunction: compilation.outputOptions.hashFunction
  358. }
  359. );
  360. hasName = usedNamesSet.has(sourceName);
  361. if (!hasName) {
  362. moduleToSourceNameMapping.set(module, sourceName);
  363. usedNamesSet.add(sourceName);
  364. continue;
  365. }
  366. // otherwise just append stars until we have a valid name
  367. while (hasName) {
  368. sourceName += "*";
  369. hasName = usedNamesSet.has(sourceName);
  370. }
  371. moduleToSourceNameMapping.set(module, sourceName);
  372. usedNamesSet.add(sourceName);
  373. }
  374. let taskIndex = 0;
  375. asyncLib.each(
  376. tasks,
  377. (task, callback) => {
  378. const assets = Object.create(null);
  379. const assetsInfo = Object.create(null);
  380. const file = task.file;
  381. const chunk = fileToChunk.get(file);
  382. const sourceMap = task.sourceMap;
  383. const source = task.source;
  384. const modules = task.modules;
  385. reportProgress(
  386. 0.5 + (0.5 * taskIndex) / tasks.length,
  387. file,
  388. "attach SourceMap"
  389. );
  390. const moduleFilenames = modules.map(m =>
  391. moduleToSourceNameMapping.get(m)
  392. );
  393. sourceMap.sources = /** @type {string[]} */ (moduleFilenames);
  394. if (options.noSources) {
  395. sourceMap.sourcesContent = undefined;
  396. }
  397. sourceMap.sourceRoot = options.sourceRoot || "";
  398. sourceMap.file = file;
  399. const usesContentHash =
  400. sourceMapFilename &&
  401. CONTENT_HASH_DETECT_REGEXP.test(sourceMapFilename);
  402. resetRegexpState(CONTENT_HASH_DETECT_REGEXP);
  403. // If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file`
  404. if (usesContentHash && task.assetInfo.contenthash) {
  405. const contenthash = task.assetInfo.contenthash;
  406. const pattern = Array.isArray(contenthash)
  407. ? contenthash.map(quoteMeta).join("|")
  408. : quoteMeta(contenthash);
  409. sourceMap.file = sourceMap.file.replace(
  410. new RegExp(pattern, "g"),
  411. m => "x".repeat(m.length)
  412. );
  413. }
  414. /** @type {false | TemplatePath} */
  415. let currentSourceMappingURLComment = sourceMappingURLComment;
  416. const cssExtensionDetected =
  417. CSS_EXTENSION_DETECT_REGEXP.test(file);
  418. resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
  419. if (
  420. currentSourceMappingURLComment !== false &&
  421. typeof currentSourceMappingURLComment !== "function" &&
  422. cssExtensionDetected
  423. ) {
  424. currentSourceMappingURLComment =
  425. currentSourceMappingURLComment.replace(
  426. URL_FORMATTING_REGEXP,
  427. "\n/*$1*/"
  428. );
  429. }
  430. if (options.debugIds) {
  431. const debugId = generateDebugId(source, sourceMap.file);
  432. sourceMap.debugId = debugId;
  433. currentSourceMappingURLComment = `\n//# debugId=${debugId}${currentSourceMappingURLComment}`;
  434. }
  435. const sourceMapString = JSON.stringify(sourceMap);
  436. if (sourceMapFilename) {
  437. const filename = file;
  438. const sourceMapContentHash =
  439. /** @type {string} */
  440. (
  441. usesContentHash &&
  442. createHash(
  443. /** @type {Algorithm} */
  444. (compilation.outputOptions.hashFunction)
  445. )
  446. .update(sourceMapString)
  447. .digest("hex")
  448. );
  449. const pathParams = {
  450. chunk,
  451. filename: options.fileContext
  452. ? relative(
  453. outputFs,
  454. `/${options.fileContext}`,
  455. `/${filename}`
  456. )
  457. : filename,
  458. contentHash: sourceMapContentHash
  459. };
  460. const { path: sourceMapFile, info: sourceMapInfo } =
  461. compilation.getPathWithInfo(
  462. sourceMapFilename,
  463. pathParams
  464. );
  465. const sourceMapUrl = options.publicPath
  466. ? options.publicPath + sourceMapFile
  467. : relative(
  468. outputFs,
  469. dirname(outputFs, `/${file}`),
  470. `/${sourceMapFile}`
  471. );
  472. /** @type {Source} */
  473. let asset = new RawSource(source);
  474. if (currentSourceMappingURLComment !== false) {
  475. // Add source map url to compilation asset, if currentSourceMappingURLComment is set
  476. asset = new ConcatSource(
  477. asset,
  478. compilation.getPath(currentSourceMappingURLComment, {
  479. url: sourceMapUrl,
  480. ...pathParams
  481. })
  482. );
  483. }
  484. const assetInfo = {
  485. related: { sourceMap: sourceMapFile }
  486. };
  487. assets[file] = asset;
  488. assetsInfo[file] = assetInfo;
  489. compilation.updateAsset(file, asset, assetInfo);
  490. // Add source map file to compilation assets and chunk files
  491. const sourceMapAsset = new RawSource(sourceMapString);
  492. const sourceMapAssetInfo = {
  493. ...sourceMapInfo,
  494. development: true
  495. };
  496. assets[sourceMapFile] = sourceMapAsset;
  497. assetsInfo[sourceMapFile] = sourceMapAssetInfo;
  498. compilation.emitAsset(
  499. sourceMapFile,
  500. sourceMapAsset,
  501. sourceMapAssetInfo
  502. );
  503. if (chunk !== undefined)
  504. chunk.auxiliaryFiles.add(sourceMapFile);
  505. } else {
  506. if (currentSourceMappingURLComment === false) {
  507. throw new Error(
  508. "SourceMapDevToolPlugin: append can't be false when no filename is provided"
  509. );
  510. }
  511. if (typeof currentSourceMappingURLComment === "function") {
  512. throw new Error(
  513. "SourceMapDevToolPlugin: append can't be a function when no filename is provided"
  514. );
  515. }
  516. /**
  517. * Add source map as data url to asset
  518. */
  519. const asset = new ConcatSource(
  520. new RawSource(source),
  521. currentSourceMappingURLComment
  522. .replace(MAP_URL_COMMENT_REGEXP, () => sourceMapString)
  523. .replace(
  524. URL_COMMENT_REGEXP,
  525. () =>
  526. `data:application/json;charset=utf-8;base64,${Buffer.from(
  527. sourceMapString,
  528. "utf-8"
  529. ).toString("base64")}`
  530. )
  531. );
  532. assets[file] = asset;
  533. assetsInfo[file] = undefined;
  534. compilation.updateAsset(file, asset);
  535. }
  536. task.cacheItem.store({ assets, assetsInfo }, err => {
  537. reportProgress(
  538. 0.5 + (0.5 * ++taskIndex) / tasks.length,
  539. task.file,
  540. "attached SourceMap"
  541. );
  542. if (err) {
  543. return callback(err);
  544. }
  545. callback();
  546. });
  547. },
  548. err => {
  549. reportProgress(1);
  550. callback(err);
  551. }
  552. );
  553. }
  554. );
  555. }
  556. );
  557. });
  558. }
  559. }
  560. module.exports = SourceMapDevToolPlugin;