unpkg/modules/plugins/unpkgRewrite.js

89 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2019-01-06 00:50:05 +00:00
import URL from 'whatwg-url';
import warning from 'warning';
2018-01-10 05:41:19 +00:00
const bareIdentifierFormat = /^((?:@[^/]+\/)?[^/]+)(\/.*)?$/;
2018-01-10 05:41:19 +00:00
function isValidURL(value) {
return URL.parseURL(value) != null;
}
function isProbablyURLWithoutProtocol(value) {
2018-12-17 17:38:05 +00:00
return value.substr(0, 2) === '//';
}
function isAbsoluteURL(value) {
return isValidURL(value) || isProbablyURLWithoutProtocol(value);
}
function isBareIdentifier(value) {
2018-12-17 17:38:05 +00:00
return value.charAt(0) !== '.' && value.charAt(0) !== '/';
}
2019-01-24 00:03:27 +00:00
function rewriteValue(/* StringLiteral */ node, origin, dependencies) {
if (isAbsoluteURL(node.value)) {
return;
}
if (isBareIdentifier(node.value)) {
// "bare" identifier
const match = bareIdentifierFormat.exec(node.value);
const packageName = match[1];
2018-12-17 17:38:05 +00:00
const file = match[2] || '';
warning(
dependencies[packageName],
'Missing version info for package "%s" in dependencies; falling back to "latest"',
packageName
);
2018-12-17 17:38:05 +00:00
const version = dependencies[packageName] || 'latest';
node.value = `${origin}/${packageName}@${version}${file}?module`;
} else {
// local path
node.value = `${node.value}?module`;
}
}
2019-01-24 00:03:27 +00:00
export default function unpkgRewrite(origin, dependencies = {}) {
2018-01-10 05:41:19 +00:00
return {
manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push(
2018-12-17 17:38:05 +00:00
'dynamicImport',
'exportDefaultFrom',
'exportNamespaceFrom',
'importMeta'
);
},
2018-01-10 05:41:19 +00:00
visitor: {
CallExpression(path) {
2018-12-17 17:38:05 +00:00
if (path.node.callee.type !== 'Import') {
// Some other function call, not import();
return;
}
2019-01-24 00:03:27 +00:00
rewriteValue(path.node.arguments[0], origin, dependencies);
},
ExportAllDeclaration(path) {
2019-01-24 00:03:27 +00:00
rewriteValue(path.node.source, origin, dependencies);
},
ExportNamedDeclaration(path) {
if (!path.node.source) {
// This export has no "source", so it's probably
// a local variable or function, e.g.
// export { varName }
// export const constName = ...
// export function funcName() {}
return;
2018-01-10 05:41:19 +00:00
}
2019-01-24 00:03:27 +00:00
rewriteValue(path.node.source, origin, dependencies);
},
ImportDeclaration(path) {
2019-01-24 00:03:27 +00:00
rewriteValue(path.node.source, origin, dependencies);
2018-01-10 05:41:19 +00:00
}
}
2018-02-18 02:00:56 +00:00
};
2018-01-10 05:41:19 +00:00
}