UNPKG

2.86 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
5var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
6
7const logger = require('@parcel/logger');
8
9const path = require('path');
10
11const fs = require('@parcel/fs');
12
13const SOURCEMAP_RE = /(?:\/\*|\/\/)\s*[@#]\s*sourceMappingURL\s*=\s*([^\s*]+)(?:\s*\*\/)?/;
14const DATA_URL_RE = /^data:[^;]+(?:;charset=[^;]+)?;base64,(.*)/;
15
16function loadSourceMap(_x) {
17 return _loadSourceMap.apply(this, arguments);
18}
19
20function _loadSourceMap() {
21 _loadSourceMap = (0, _asyncToGenerator2.default)(function* (asset) {
22 // Get original sourcemap if there is any
23 let match = asset.contents.match(SOURCEMAP_RE);
24 let sourceMap;
25
26 if (match) {
27 asset.contents = asset.contents.replace(SOURCEMAP_RE, '');
28 let url = match[1];
29 let dataURLMatch = url.match(DATA_URL_RE);
30
31 try {
32 let json, filename;
33
34 if (dataURLMatch) {
35 filename = asset.name;
36 json = Buffer.from(dataURLMatch[1], 'base64').toString();
37 } else {
38 filename = path.join(path.dirname(asset.name), url);
39 json = yield fs.readFile(filename, 'utf8'); // Add as a dep so we watch the source map for changes.
40
41 asset.addDependency(filename, {
42 includedInParent: true
43 });
44 }
45
46 sourceMap = JSON.parse(json); // Attempt to read missing source contents
47
48 if (!sourceMap.sourcesContent) {
49 sourceMap.sourcesContent = [];
50 }
51
52 let missingSources = sourceMap.sources.slice(sourceMap.sourcesContent.length);
53
54 if (missingSources.length) {
55 let contents = yield Promise.all(missingSources.map(
56 /*#__PURE__*/
57 function () {
58 var _ref = (0, _asyncToGenerator2.default)(function* (source) {
59 try {
60 let sourceFile = path.join(path.dirname(filename), sourceMap.sourceRoot || '', source);
61 let result = yield fs.readFile(sourceFile, 'utf8');
62 asset.addDependency(sourceFile, {
63 includedInParent: true
64 });
65 return result;
66 } catch (err) {
67 logger.warn(`Could not load source file "${source}" in source map of "${asset.relativeName}".`);
68 }
69 });
70
71 return function (_x2) {
72 return _ref.apply(this, arguments);
73 };
74 }()));
75 sourceMap.sourcesContent = sourceMap.sourcesContent.concat(contents);
76 }
77 } catch (e) {
78 logger.warn(`Could not load existing sourcemap of "${asset.relativeName}".`);
79 sourceMap = undefined;
80 }
81 }
82
83 return sourceMap;
84 });
85 return _loadSourceMap.apply(this, arguments);
86}
87
88module.exports = loadSourceMap;
\No newline at end of file