rollup-plugin-sourcemaps2
Version:
Rollup plugin for grabbing source maps from sourceMappingURLs
101 lines (95 loc) • 3.37 kB
JavaScript
const urlLib = require('node:url');
const decodeUriComponent = require('./decode-uri-component.cjs');
function _interopNamespaceDefault(e) {
const n = Object.create(null);
if (e) {
for (const k in e) {
if (k !== 'default') {
const d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
}
}
n.default = e;
return Object.freeze(n);
}
const urlLib__namespace = /*#__PURE__*/_interopNamespaceDefault(urlLib);
function resolveUrl(...args) {
return args.reduce((resolved, nextUrl)=>urlLib__namespace.resolve(resolved, nextUrl), '');
}
function customDecodeUriComponent(encodedURI) {
return decodeUriComponent(encodedURI.replace(/\+/g, '%2B'));
}
function parseMapToJSON(string) {
return JSON.parse(string.replace(/^\)\]\}'/, ''));
}
const sourceMappingURLRegex = /(?:\/\*(?:\s*\r?\n(?:\/\/)?)?(?:[#@] sourceMappingURL=([^\s'"]*))\s*\*\/|\/\/(?:[#@] sourceMappingURL=([^\s'"]*)))\s*/g;
function getSourceMappingUrl(code) {
const match = Array.from(code.matchAll(sourceMappingURLRegex)).pop();
return match ? match[1] || match[2] || '' : null;
}
async function resolveSourceMap(code, codeUrl, read) {
const sourceMappingURL = getSourceMappingUrl(code);
if (!sourceMappingURL) {
return null;
}
const dataUri = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/.exec(sourceMappingURL);
if (dataUri) {
const mimeType = dataUri[1] || 'text/plain';
if (!/^(?:application|text)\/json$/.test(mimeType)) {
throw new Error(`Unuseful data uri mime type: ${mimeType}`);
}
const map = parseMapToJSON((dataUri[2] === ';base64' ? atob : decodeURIComponent)(dataUri[3] || ''));
return {
sourceMappingURL,
url: null,
sourcesRelativeTo: codeUrl,
map
};
}
const url = resolveUrl(codeUrl, sourceMappingURL);
const map = parseMapToJSON(String(await read(customDecodeUriComponent(url))));
return {
sourceMappingURL,
url,
sourcesRelativeTo: url,
map
};
}
async function resolveSources(map, mapUrl, read) {
const sourcesResolved = [];
const sourcesContent = [];
for(let index = 0, len = map.sources.length; index < len; index++){
const sourceRoot = map.sourceRoot;
const sourceContent = (map.sourcesContent || [])[index];
const resolvePaths = [
mapUrl,
map.sources[index]
];
if (sourceRoot !== undefined && sourceRoot !== '') {
resolvePaths.splice(1, 0, sourceRoot.replace(/\/?$/, '/'));
}
sourcesResolved[index] = resolveUrl(...resolvePaths);
if (typeof sourceContent === 'string') {
sourcesContent[index] = sourceContent;
continue;
}
try {
const source = await read(customDecodeUriComponent(sourcesResolved[index]));
sourcesContent[index] = String(source);
} catch (error) {
sourcesContent[index] = error;
}
}
return {
sourcesResolved,
sourcesContent
};
}
exports.resolveSourceMap = resolveSourceMap;
exports.resolveSources = resolveSources;
//# sourceMappingURL=source-map-resolve.cjs.map
;