parseuri.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // imported from https://github.com/galkn/parseuri
  2. /**
  3. * Parses a URI
  4. *
  5. * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
  6. *
  7. * See:
  8. * - https://developer.mozilla.org/en-US/docs/Web/API/URL
  9. * - https://caniuse.com/url
  10. * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
  11. *
  12. * History of the parse() method:
  13. * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
  14. * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
  15. * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
  16. *
  17. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  18. * @api private
  19. */
  20. const re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  21. const parts = [
  22. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  23. ];
  24. export function parse(str) {
  25. const src = str, b = str.indexOf('['), e = str.indexOf(']');
  26. if (b != -1 && e != -1) {
  27. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  28. }
  29. let m = re.exec(str || ''), uri = {}, i = 14;
  30. while (i--) {
  31. uri[parts[i]] = m[i] || '';
  32. }
  33. if (b != -1 && e != -1) {
  34. uri.source = src;
  35. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  36. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  37. uri.ipv6uri = true;
  38. }
  39. uri.pathNames = pathNames(uri, uri['path']);
  40. uri.queryKey = queryKey(uri, uri['query']);
  41. return uri;
  42. }
  43. function pathNames(obj, path) {
  44. const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
  45. if (path.slice(0, 1) == '/' || path.length === 0) {
  46. names.splice(0, 1);
  47. }
  48. if (path.slice(-1) == '/') {
  49. names.splice(names.length - 1, 1);
  50. }
  51. return names;
  52. }
  53. function queryKey(uri, query) {
  54. const data = {};
  55. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  56. if ($1) {
  57. data[$1] = $2;
  58. }
  59. });
  60. return data;
  61. }