2018-12-17 17:38:05 +00:00
|
|
|
const url = require('url');
|
2018-04-04 19:06:17 +00:00
|
|
|
|
|
|
|
const packageURLFormat = /^\/((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?(\/.*)?$/;
|
2017-05-25 18:25:42 +00:00
|
|
|
|
2017-08-12 03:27:27 +00:00
|
|
|
function decodeParam(param) {
|
2017-08-12 16:40:53 +00:00
|
|
|
if (param) {
|
|
|
|
try {
|
2018-02-18 02:00:56 +00:00
|
|
|
return decodeURIComponent(param);
|
2017-08-12 16:40:53 +00:00
|
|
|
} catch (error) {
|
|
|
|
// Ignore invalid params.
|
|
|
|
}
|
2017-08-12 03:27:27 +00:00
|
|
|
}
|
2017-08-12 16:40:53 +00:00
|
|
|
|
2018-12-17 17:38:05 +00:00
|
|
|
return '';
|
2017-08-12 03:27:27 +00:00
|
|
|
}
|
2017-05-25 18:25:42 +00:00
|
|
|
|
2018-03-20 17:34:31 +00:00
|
|
|
function parsePackageURL(originalURL) {
|
|
|
|
const { pathname, search, query } = url.parse(originalURL, true);
|
2018-04-04 19:06:17 +00:00
|
|
|
const match = packageURLFormat.exec(pathname);
|
2017-05-25 18:25:42 +00:00
|
|
|
|
2017-11-15 00:44:53 +00:00
|
|
|
// Disallow invalid URL formats.
|
2018-03-20 17:34:31 +00:00
|
|
|
if (match == null) {
|
|
|
|
return null;
|
|
|
|
}
|
2017-05-25 18:25:42 +00:00
|
|
|
|
2018-02-18 02:00:56 +00:00
|
|
|
const packageName = match[1];
|
2018-12-17 17:38:05 +00:00
|
|
|
const packageVersion = decodeParam(match[2]) || 'latest';
|
2018-02-18 02:00:56 +00:00
|
|
|
const filename = decodeParam(match[3]);
|
2017-05-25 18:25:42 +00:00
|
|
|
|
2017-11-08 16:57:15 +00:00
|
|
|
return {
|
|
|
|
// If the URL is /@scope/name@version/file.js?main=browser:
|
|
|
|
pathname, // /@scope/name@version/path.js
|
2018-12-17 17:38:05 +00:00
|
|
|
search: search || '', // ?main=browser
|
2017-11-08 16:57:15 +00:00
|
|
|
query, // { main: 'browser' }
|
|
|
|
packageName, // @scope/name
|
2017-08-10 17:12:50 +00:00
|
|
|
packageVersion, // version
|
2017-11-08 16:57:15 +00:00
|
|
|
filename // /file.js
|
2018-02-18 02:00:56 +00:00
|
|
|
};
|
2017-05-25 18:25:42 +00:00
|
|
|
}
|
|
|
|
|
2018-02-18 02:00:56 +00:00
|
|
|
module.exports = parsePackageURL;
|