UNPKG

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