rollup-plugin-sourcemaps2
Version:
Rollup plugin for grabbing source maps from sourceMappingURLs
79 lines (76 loc) • 2.83 kB
JavaScript
import * as urlLib from 'node:url';
import decodeUriComponent from './decode-uri-component.js';
function resolveUrl(...args) {
return args.reduce((resolved, nextUrl)=>urlLib.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
};
}
export { resolveSourceMap, resolveSources };
//# sourceMappingURL=source-map-resolve.js.map