unpkg/server/PackageURL.js

54 lines
1.2 KiB
JavaScript
Raw Normal View History

const url = require('url')
2017-05-25 18:25:42 +00:00
const URLFormat = /^\/((?:@[^\/@]+\/)?[^\/@]+)(?:@([^\/]+))?(\/.*)?$/
function decodeParam(param) {
try {
return decodeURIComponent(param)
} catch (error) {
return null
}
}
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)
if (match == null)
return null
const packageName = match[1]
const packageVersion = decodeParam(match[2]) || 'latest'
2017-05-25 18:25:42 +00:00
const filename = decodeParam(match[3])
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
filename // /file.js
2017-05-25 18:25:42 +00:00
}
}
function createPackageURL(packageName, version, filename, search) {
2017-05-25 18:25:42 +00:00
let pathname = `/${packageName}`
if (version != null)
pathname += `@${version}`
2017-08-05 04:59:44 +00:00
if (filename)
2017-05-25 18:25:42 +00:00
pathname += filename
if (search)
pathname += search
return pathname
}
module.exports = {
parse: parsePackageURL,
create: createPackageURL
2017-05-25 18:25:42 +00:00
}