unpkg/modules/plugins/unpkgRewrite.js

48 lines
1.4 KiB
JavaScript
Raw Normal View History

2018-02-18 02:00:56 +00:00
const URL = require("whatwg-url");
const warning = require("warning");
2018-01-10 05:41:19 +00:00
2018-07-31 17:13:26 +00:00
const origin = require("../serverConfig").origin;
2018-05-17 17:10:33 +00:00
const bareIdentifierFormat = /^((?:@[^/]+\/)?[^/]+)(\/.*)?$/;
2018-01-10 05:41:19 +00:00
2018-05-17 17:10:33 +00:00
function unpkgRewrite(dependencies = {}) {
2018-01-10 05:41:19 +00:00
return {
inherits: require("babel-plugin-syntax-export-extensions"),
visitor: {
"ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration"(path) {
2018-02-18 02:00:56 +00:00
if (!path.node.source) return; // probably a variable declaration
2018-01-10 05:41:19 +00:00
if (
URL.parseURL(path.node.source.value) != null ||
path.node.source.value.substr(0, 2) === "//"
)
2018-02-18 02:00:56 +00:00
return; // valid URL or URL w/o protocol, leave it alone
2018-01-10 05:41:19 +00:00
if ([".", "/"].indexOf(path.node.source.value.charAt(0)) >= 0) {
// local path
2018-02-18 02:00:56 +00:00
path.node.source.value = `${path.node.source.value}?module`;
2018-01-10 05:41:19 +00:00
} else {
// "bare" identifier
2018-04-04 05:32:32 +00:00
const match = bareIdentifierFormat.exec(path.node.source.value);
2018-02-18 02:00:56 +00:00
const packageName = match[1];
const file = match[2] || "";
2018-01-10 05:41:19 +00:00
warning(
dependencies[packageName],
'Missing version info for package "%s" in dependencies; falling back to "latest"',
packageName
2018-02-18 02:00:56 +00:00
);
2018-01-10 05:41:19 +00:00
2018-02-18 02:00:56 +00:00
const version = dependencies[packageName] || "latest";
2018-07-27 12:08:07 +00:00
const url = `${origin}/${packageName}@${version}${file}?module`;
2018-01-10 05:41:19 +00:00
2018-07-27 12:08:07 +00:00
path.node.source.value = url;
2018-01-10 05:41:19 +00:00
}
}
}
2018-02-18 02:00:56 +00:00
};
2018-01-10 05:41:19 +00:00
}
2018-05-17 17:10:33 +00:00
module.exports = unpkgRewrite;