unpkg/server/utils/parsePackageURL.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

2017-11-25 21:25:01 +00:00
const url = require("url")
const validatePackageName = require("./validatePackageName")
2017-05-25 18:25:42 +00:00
const URLFormat = /^\/((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?(\/.*)?$/
2017-05-25 18:25:42 +00:00
function decodeParam(param) {
2017-08-12 16:40:53 +00:00
if (param) {
try {
return decodeURIComponent(param)
} catch (error) {
// Ignore invalid params.
}
}
2017-08-12 16:40:53 +00:00
2017-11-25 21:25:01 +00:00
return ""
}
2017-05-25 18:25:42 +00:00
function parsePackageURL(packageURL) {
const { pathname, search, query } = url.parse(packageURL, true)
2017-05-25 18:25:42 +00:00
const match = URLFormat.exec(pathname)
// Disallow invalid URL formats.
2017-11-08 16:57:15 +00:00
if (match == null) return null
2017-05-25 18:25:42 +00:00
const packageName = match[1]
// Disallow invalid npm package names.
if (!validatePackageName(packageName)) return null
2017-11-25 21:25:01 +00:00
const packageVersion = decodeParam(match[2]) || "latest"
2017-05-25 18:25:42 +00:00
const filename = decodeParam(match[3])
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
search, // ?main=browser
query, // { main: 'browser' }
packageName, // @scope/name
packageVersion, // version
2017-11-08 16:57:15 +00:00
filename // /file.js
2017-05-25 18:25:42 +00:00
}
}
2017-08-19 18:44:01 +00:00
module.exports = parsePackageURL