Files
ms/packages/websocket/src/engine.io-client/contrib/parseuri.ts
2022-11-21 23:18:39 +08:00

69 lines
1.8 KiB
TypeScript

// imported from https://github.com/galkn/parseuri
/**
* Parses an URI
*
* @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api private
*/
const re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
const parts = [
'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
]
export function parse(str) {
const src = str,
b = str.indexOf('['),
e = str.indexOf(']')
if (b != -1 && e != -1) {
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length)
}
let m = re.exec(str || ''),
uri = {} as any,
i = 14
while (i--) {
uri[parts[i]] = m[i] || ''
}
if (b != -1 && e != -1) {
uri.source = src
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':')
uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':')
uri.ipv6uri = true
}
uri.pathNames = pathNames(uri, uri['path'])
uri.queryKey = queryKey(uri, uri['query'])
return uri
}
function pathNames(obj, path) {
const regx = /\/{2,9}/g,
names = path.replace(regx, "/").split("/")
if (path.slice(0, 1) == '/' || path.length === 0) {
names.splice(0, 1)
}
if (path.slice(-1) == '/') {
names.splice(names.length - 1, 1)
}
return names
}
function queryKey(uri, query) {
const data = {}
query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
if ($1) {
data[$1] = $2
}
})
return data
}