index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * Parses an URI
  3. *
  4. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  5. * @api private
  6. */
  7. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  8. var parts = [
  9. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  10. ];
  11. module.exports = function parseuri(str) {
  12. var src = str,
  13. b = str.indexOf('['),
  14. e = str.indexOf(']');
  15. if (b != -1 && e != -1) {
  16. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  17. }
  18. var m = re.exec(str || ''),
  19. uri = {},
  20. i = 14;
  21. while (i--) {
  22. uri[parts[i]] = m[i] || '';
  23. }
  24. if (b != -1 && e != -1) {
  25. uri.source = src;
  26. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  27. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  28. uri.ipv6uri = true;
  29. }
  30. uri.pathNames = pathNames(uri, uri['path']);
  31. uri.queryKey = queryKey(uri, uri['query']);
  32. return uri;
  33. };
  34. function pathNames(obj, path) {
  35. var regx = /\/{2,9}/g,
  36. names = path.replace(regx, "/").split("/");
  37. if (path.substr(0, 1) == '/' || path.length === 0) {
  38. names.splice(0, 1);
  39. }
  40. if (path.substr(path.length - 1, 1) == '/') {
  41. names.splice(names.length - 1, 1);
  42. }
  43. return names;
  44. }
  45. function queryKey(uri, query) {
  46. var data = {};
  47. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  48. if ($1) {
  49. data[$1] = $2;
  50. }
  51. });
  52. return data;
  53. }