12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- 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) {
- if (str.length > 2000) {
- throw "URI too long";
- }
- 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 = {}, 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;
- }
|