Skip to content

Commit

Permalink
refactor: code (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
cap-Bernardito committed May 23, 2020
1 parent 4c39c22 commit 01b3812
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 97 deletions.
160 changes: 73 additions & 87 deletions src/index.js
Expand Up @@ -4,12 +4,14 @@
*/
import fs from 'fs';
import path from 'path';
import urlUtils from 'url';

import { promisify } from 'util';

import validateOptions from 'schema-utils';
import parseDataURL from 'data-urls';

import { SourceMapConsumer } from 'source-map';

import { labelToName, decode } from 'whatwg-encoding';
import { getOptions, urlToRequest } from 'loader-utils';

Expand All @@ -18,11 +20,11 @@ import {
flattenSourceMap,
readFile,
getContentFromSourcesContent,
isUrlRequest,
getSourceMappingUrl,
getRequestedUrl,
} from './utils';

export default function loader(input, inputMap) {
export default async function loader(input, inputMap) {
const options = getOptions(this);

validateOptions(schema, options, {
Expand All @@ -40,99 +42,83 @@ export default function loader(input, inputMap) {
return;
}

const dataURL = parseDataURL(url);

const { context, resolve, addDependency, emitWarning } = this;
const resolver = promisify(resolve);

if (dataURL) {
let map;
if (url.toLowerCase().startsWith('data:')) {
const dataURL = parseDataURL(url);

try {
dataURL.encodingName =
labelToName(dataURL.mimeType.parameters.get('charset')) || 'UTF-8';
if (dataURL) {
let map;

map = decode(dataURL.body, dataURL.encodingName);
map = JSON.parse(map.replace(/^\)\]\}'/, ''));
} catch (error) {
emitWarning(
`Cannot parse inline SourceMap with Charset ${dataURL.encodingName}: ${error}`
);
try {
dataURL.encodingName =
labelToName(dataURL.mimeType.parameters.get('charset')) || 'UTF-8';

callback(null, input, inputMap);
map = decode(dataURL.body, dataURL.encodingName);
map = JSON.parse(map.replace(/^\)\]\}'/, ''));
} catch (error) {
emitWarning(
`Cannot parse inline SourceMap with Charset ${dataURL.encodingName}: ${error}`
);

return;
}
callback(null, input, inputMap);

processMap(map, context, callback);
return;
}

return;
}
processMap(map, context, callback);

return;
}

if (url.toLowerCase().indexOf('data:') === 0) {
emitWarning(`Cannot parse inline SourceMap: ${url}`);

callback(null, input, inputMap);

return;
}

if (!isUrlRequest(url)) {
const { protocol } = urlUtils.parse(url);

if (protocol !== 'file:') {
emitWarning(`URL scheme not supported: ${protocol}`);
try {
url = getRequestedUrl(url);
} catch (error) {
emitWarning(error.message);

callback(null, input, inputMap);

return;
}

try {
url = urlUtils.fileURLToPath(url);
} catch (error) {
emitWarning(error);

callback(null, input, inputMap);
callback(null, input, inputMap);

return;
}
return;
}

resolve(context, urlToRequest(url, true), (resolveError, result) => {
if (resolveError) {
emitWarning(`Cannot find SourceMap '${url}': ${resolveError}`);

callback(null, input, inputMap);

return;
}
let urlResolved;

addDependency(result);
try {
urlResolved = await resolver(context, urlToRequest(url, true));
} catch (resolveError) {
emitWarning(`Cannot find SourceMap '${url}': ${resolveError}`);

fs.readFile(result, 'utf-8', (readFileError, content) => {
if (readFileError) {
emitWarning(`Cannot open SourceMap '${result}': ${readFileError}`);
callback(null, input, inputMap);

callback(null, input, inputMap);
return;
}

return;
}
urlResolved = urlResolved.toString();
addDependency(urlResolved);

let map;
const reader = promisify(fs.readFile);
const content = await reader(urlResolved);
let map;

try {
map = JSON.parse(content);
} catch (e) {
emitWarning(`Cannot parse SourceMap '${url}': ${e}`);
try {
map = JSON.parse(content.toString());
} catch (parseError) {
emitWarning(`Cannot parse SourceMap '${url}': ${parseError}`);

callback(null, input, inputMap);
callback(null, input, inputMap);

return;
}
return;
}

processMap(map, path.dirname(result), callback);
});
});
processMap(map, path.dirname(urlResolved), callback);

// eslint-disable-next-line no-shadow
async function processMap(map, context, callback) {
Expand Down Expand Up @@ -163,30 +149,30 @@ export default function loader(input, inputMap) {
: readFile(fullPath, 'utf-8', emitWarning);
}

return new Promise((promiseResolve) => {
resolve(
let fullPathResolved;

try {
fullPathResolved = await resolver(
context,
urlToRequest(fullPath, true),
(resolveError, result) => {
if (resolveError) {
emitWarning(
`Cannot find source file '${source}': ${resolveError}`
);

return originalData
? promiseResolve({
source: fullPath,
content: originalData,
})
: promiseResolve({ source: fullPath, content: null });
urlToRequest(fullPath, true)
);
} catch (resolveError) {
emitWarning(`Cannot find source file '${source}': ${resolveError}`);

return originalData
? {
source: fullPath,
content: originalData,
}
: { source: fullPath, content: null };
}

return originalData
? promiseResolve({ source: result, content: originalData })
: promiseResolve(readFile(result, 'utf-8', emitWarning));
return originalData
? {
source: fullPathResolved,
content: originalData,
}
);
});
: readFile(fullPathResolved, 'utf-8', emitWarning);
})
);
} catch (error) {
Expand Down
43 changes: 33 additions & 10 deletions src/utils.js
@@ -1,6 +1,10 @@
import fs from 'fs';
import path from 'path';

import { promisify } from 'util';

import urlUtils from 'url';

import sourceMap from 'source-map';

// Matches only the last occurrence of sourceMappingURL
Expand Down Expand Up @@ -68,18 +72,18 @@ async function flattenSourceMap(map) {
return generatedMap.toJSON();
}

function readFile(fullPath, charset, emitWarning) {
return new Promise((resolve) => {
fs.readFile(fullPath, charset, (readFileError, content) => {
if (readFileError) {
emitWarning(`Cannot open source file '${fullPath}': ${readFileError}`);
async function readFile(fullPath, charset, emitWarning) {
const reader = promisify(fs.readFile);
let content;

resolve({ source: null, content: null });
}
try {
content = await reader(fullPath, charset);
return { source: fullPath, content };
} catch (readFileError) {
emitWarning(`Cannot open source file '${fullPath}': ${readFileError}`);

resolve({ source: fullPath, content });
});
});
return { source: null, content: null };
}
}

function getContentFromSourcesContent(consumer, source) {
Expand Down Expand Up @@ -119,10 +123,29 @@ function getSourceMappingUrl(code) {
};
}

function getRequestedUrl(url) {
if (isUrlRequest(url)) {
return url;
}

const { protocol } = urlUtils.parse(url);

if (protocol !== 'file:') {
throw new Error(`URL scheme not supported: ${protocol}`);
}

try {
return urlUtils.fileURLToPath(url);
} catch (error) {
throw new Error(error);
}
}

export {
flattenSourceMap,
readFile,
getContentFromSourcesContent,
isUrlRequest,
getSourceMappingUrl,
getRequestedUrl,
};

0 comments on commit 01b3812

Please sign in to comment.