123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. // Copyright Joyent, Inc. and other Node contributors.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a
  4. // copy of this software and associated documentation files (the
  5. // "Software"), to deal in the Software without restriction, including
  6. // without limitation the rights to use, copy, modify, merge, publish,
  7. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8. // persons to whom the Software is furnished to do so, subject to the
  9. // following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included
  12. // in all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  18. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. 'use strict';
  22. var punycode = require('punycode');
  23. var util = require('./util');
  24. exports.parse = urlParse;
  25. exports.resolve = urlResolve;
  26. exports.resolveObject = urlResolveObject;
  27. exports.format = urlFormat;
  28. exports.Url = Url;
  29. function Url() {
  30. this.protocol = null;
  31. this.slashes = null;
  32. this.auth = null;
  33. this.host = null;
  34. this.port = null;
  35. this.hostname = null;
  36. this.hash = null;
  37. this.search = null;
  38. this.query = null;
  39. this.pathname = null;
  40. this.path = null;
  41. this.href = null;
  42. }
  43. // Reference: RFC 3986, RFC 1808, RFC 2396
  44. // define these here so at least they only have to be
  45. // compiled once on the first module load.
  46. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  47. portPattern = /:[0-9]*$/,
  48. // Special case for a simple path URL
  49. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  50. // RFC 2396: characters reserved for delimiting URLs.
  51. // We actually just auto-escape these.
  52. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  53. // RFC 2396: characters not allowed for various reasons.
  54. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  55. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  56. autoEscape = ['\''].concat(unwise),
  57. // Characters that are never ever allowed in a hostname.
  58. // Note that any invalid chars are also handled, but these
  59. // are the ones that are *expected* to be seen, so we fast-path
  60. // them.
  61. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  62. hostEndingChars = ['/', '?', '#'],
  63. hostnameMaxLen = 255,
  64. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  65. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  66. // protocols that can allow "unsafe" and "unwise" chars.
  67. unsafeProtocol = {
  68. 'javascript': true,
  69. 'javascript:': true
  70. },
  71. // protocols that never have a hostname.
  72. hostlessProtocol = {
  73. 'javascript': true,
  74. 'javascript:': true
  75. },
  76. // protocols that always contain a // bit.
  77. slashedProtocol = {
  78. 'http': true,
  79. 'https': true,
  80. 'ftp': true,
  81. 'gopher': true,
  82. 'file': true,
  83. 'http:': true,
  84. 'https:': true,
  85. 'ftp:': true,
  86. 'gopher:': true,
  87. 'file:': true
  88. },
  89. querystring = require('querystring');
  90. function urlParse(url, parseQueryString, slashesDenoteHost) {
  91. if (url && util.isObject(url) && url instanceof Url) return url;
  92. var u = new Url;
  93. u.parse(url, parseQueryString, slashesDenoteHost);
  94. return u;
  95. }
  96. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  97. if (!util.isString(url)) {
  98. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  99. }
  100. // Copy chrome, IE, opera backslash-handling behavior.
  101. // Back slashes before the query string get converted to forward slashes
  102. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  103. var queryIndex = url.indexOf('?'),
  104. splitter =
  105. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  106. uSplit = url.split(splitter),
  107. slashRegex = /\\/g;
  108. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  109. url = uSplit.join(splitter);
  110. var rest = url;
  111. // trim before proceeding.
  112. // This is to support parse stuff like " http://foo.com \n"
  113. rest = rest.trim();
  114. if (!slashesDenoteHost && url.split('#').length === 1) {
  115. // Try fast path regexp
  116. var simplePath = simplePathPattern.exec(rest);
  117. if (simplePath) {
  118. this.path = rest;
  119. this.href = rest;
  120. this.pathname = simplePath[1];
  121. if (simplePath[2]) {
  122. this.search = simplePath[2];
  123. if (parseQueryString) {
  124. this.query = querystring.parse(this.search.substr(1));
  125. } else {
  126. this.query = this.search.substr(1);
  127. }
  128. } else if (parseQueryString) {
  129. this.search = '';
  130. this.query = {};
  131. }
  132. return this;
  133. }
  134. }
  135. var proto = protocolPattern.exec(rest);
  136. if (proto) {
  137. proto = proto[0];
  138. var lowerProto = proto.toLowerCase();
  139. this.protocol = lowerProto;
  140. rest = rest.substr(proto.length);
  141. }
  142. // figure out if it's got a host
  143. // user@server is *always* interpreted as a hostname, and url
  144. // resolution will treat //foo/bar as host=foo,path=bar because that's
  145. // how the browser resolves relative URLs.
  146. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  147. var slashes = rest.substr(0, 2) === '//';
  148. if (slashes && !(proto && hostlessProtocol[proto])) {
  149. rest = rest.substr(2);
  150. this.slashes = true;
  151. }
  152. }
  153. if (!hostlessProtocol[proto] &&
  154. (slashes || (proto && !slashedProtocol[proto]))) {
  155. // there's a hostname.
  156. // the first instance of /, ?, ;, or # ends the host.
  157. //
  158. // If there is an @ in the hostname, then non-host chars *are* allowed
  159. // to the left of the last @ sign, unless some host-ending character
  160. // comes *before* the @-sign.
  161. // URLs are obnoxious.
  162. //
  163. // ex:
  164. // http://a@b@c/ => user:a@b host:c
  165. // http://a@b?@c => user:a host:c path:/?@c
  166. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  167. // Review our test case against browsers more comprehensively.
  168. // find the first instance of any hostEndingChars
  169. var hostEnd = -1;
  170. for (var i = 0; i < hostEndingChars.length; i++) {
  171. var hec = rest.indexOf(hostEndingChars[i]);
  172. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  173. hostEnd = hec;
  174. }
  175. // at this point, either we have an explicit point where the
  176. // auth portion cannot go past, or the last @ char is the decider.
  177. var auth, atSign;
  178. if (hostEnd === -1) {
  179. // atSign can be anywhere.
  180. atSign = rest.lastIndexOf('@');
  181. } else {
  182. // atSign must be in auth portion.
  183. // http://a@b/c@d => host:b auth:a path:/c@d
  184. atSign = rest.lastIndexOf('@', hostEnd);
  185. }
  186. // Now we have a portion which is definitely the auth.
  187. // Pull that off.
  188. if (atSign !== -1) {
  189. auth = rest.slice(0, atSign);
  190. rest = rest.slice(atSign + 1);
  191. this.auth = decodeURIComponent(auth);
  192. }
  193. // the host is the remaining to the left of the first non-host char
  194. hostEnd = -1;
  195. for (var i = 0; i < nonHostChars.length; i++) {
  196. var hec = rest.indexOf(nonHostChars[i]);
  197. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  198. hostEnd = hec;
  199. }
  200. // if we still have not hit it, then the entire thing is a host.
  201. if (hostEnd === -1)
  202. hostEnd = rest.length;
  203. this.host = rest.slice(0, hostEnd);
  204. rest = rest.slice(hostEnd);
  205. // pull out port.
  206. this.parseHost();
  207. // we've indicated that there is a hostname,
  208. // so even if it's empty, it has to be present.
  209. this.hostname = this.hostname || '';
  210. // if hostname begins with [ and ends with ]
  211. // assume that it's an IPv6 address.
  212. var ipv6Hostname = this.hostname[0] === '[' &&
  213. this.hostname[this.hostname.length - 1] === ']';
  214. // validate a little.
  215. if (!ipv6Hostname) {
  216. var hostparts = this.hostname.split(/\./);
  217. for (var i = 0, l = hostparts.length; i < l; i++) {
  218. var part = hostparts[i];
  219. if (!part) continue;
  220. if (!part.match(hostnamePartPattern)) {
  221. var newpart = '';
  222. for (var j = 0, k = part.length; j < k; j++) {
  223. if (part.charCodeAt(j) > 127) {
  224. // we replace non-ASCII char with a temporary placeholder
  225. // we need this to make sure size of hostname is not
  226. // broken by replacing non-ASCII by nothing
  227. newpart += 'x';
  228. } else {
  229. newpart += part[j];
  230. }
  231. }
  232. // we test again with ASCII char only
  233. if (!newpart.match(hostnamePartPattern)) {
  234. var validParts = hostparts.slice(0, i);
  235. var notHost = hostparts.slice(i + 1);
  236. var bit = part.match(hostnamePartStart);
  237. if (bit) {
  238. validParts.push(bit[1]);
  239. notHost.unshift(bit[2]);
  240. }
  241. if (notHost.length) {
  242. rest = '/' + notHost.join('.') + rest;
  243. }
  244. this.hostname = validParts.join('.');
  245. break;
  246. }
  247. }
  248. }
  249. }
  250. if (this.hostname.length > hostnameMaxLen) {
  251. this.hostname = '';
  252. } else {
  253. // hostnames are always lower case.
  254. this.hostname = this.hostname.toLowerCase();
  255. }
  256. if (!ipv6Hostname) {
  257. // IDNA Support: Returns a punycoded representation of "domain".
  258. // It only converts parts of the domain name that
  259. // have non-ASCII characters, i.e. it doesn't matter if
  260. // you call it with a domain that already is ASCII-only.
  261. this.hostname = punycode.toASCII(this.hostname);
  262. }
  263. var p = this.port ? ':' + this.port : '';
  264. var h = this.hostname || '';
  265. this.host = h + p;
  266. this.href += this.host;
  267. // strip [ and ] from the hostname
  268. // the host field still retains them, though
  269. if (ipv6Hostname) {
  270. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  271. if (rest[0] !== '/') {
  272. rest = '/' + rest;
  273. }
  274. }
  275. }
  276. // now rest is set to the post-host stuff.
  277. // chop off any delim chars.
  278. if (!unsafeProtocol[lowerProto]) {
  279. // First, make 100% sure that any "autoEscape" chars get
  280. // escaped, even if encodeURIComponent doesn't think they
  281. // need to be.
  282. for (var i = 0, l = autoEscape.length; i < l; i++) {
  283. var ae = autoEscape[i];
  284. if (rest.indexOf(ae) === -1)
  285. continue;
  286. var esc = encodeURIComponent(ae);
  287. if (esc === ae) {
  288. esc = escape(ae);
  289. }
  290. rest = rest.split(ae).join(esc);
  291. }
  292. }
  293. // chop off from the tail first.
  294. var hash = rest.indexOf('#');
  295. if (hash !== -1) {
  296. // got a fragment string.
  297. this.hash = rest.substr(hash);
  298. rest = rest.slice(0, hash);
  299. }
  300. var qm = rest.indexOf('?');
  301. if (qm !== -1) {
  302. this.search = rest.substr(qm);
  303. this.query = rest.substr(qm + 1);
  304. if (parseQueryString) {
  305. this.query = querystring.parse(this.query);
  306. }
  307. rest = rest.slice(0, qm);
  308. } else if (parseQueryString) {
  309. // no query string, but parseQueryString still requested
  310. this.search = '';
  311. this.query = {};
  312. }
  313. if (rest) this.pathname = rest;
  314. if (slashedProtocol[lowerProto] &&
  315. this.hostname && !this.pathname) {
  316. this.pathname = '/';
  317. }
  318. //to support http.request
  319. if (this.pathname || this.search) {
  320. var p = this.pathname || '';
  321. var s = this.search || '';
  322. this.path = p + s;
  323. }
  324. // finally, reconstruct the href based on what has been validated.
  325. this.href = this.format();
  326. return this;
  327. };
  328. // format a parsed object into a url string
  329. function urlFormat(obj) {
  330. // ensure it's an object, and not a string url.
  331. // If it's an obj, this is a no-op.
  332. // this way, you can call url_format() on strings
  333. // to clean up potentially wonky urls.
  334. if (util.isString(obj)) obj = urlParse(obj);
  335. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  336. return obj.format();
  337. }
  338. Url.prototype.format = function() {
  339. var auth = this.auth || '';
  340. if (auth) {
  341. auth = encodeURIComponent(auth);
  342. auth = auth.replace(/%3A/i, ':');
  343. auth += '@';
  344. }
  345. var protocol = this.protocol || '',
  346. pathname = this.pathname || '',
  347. hash = this.hash || '',
  348. host = false,
  349. query = '';
  350. if (this.host) {
  351. host = auth + this.host;
  352. } else if (this.hostname) {
  353. host = auth + (this.hostname.indexOf(':') === -1 ?
  354. this.hostname :
  355. '[' + this.hostname + ']');
  356. if (this.port) {
  357. host += ':' + this.port;
  358. }
  359. }
  360. if (this.query &&
  361. util.isObject(this.query) &&
  362. Object.keys(this.query).length) {
  363. query = querystring.stringify(this.query);
  364. }
  365. var search = this.search || (query && ('?' + query)) || '';
  366. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  367. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  368. // unless they had them to begin with.
  369. if (this.slashes ||
  370. (!protocol || slashedProtocol[protocol]) && host !== false) {
  371. host = '//' + (host || '');
  372. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  373. } else if (!host) {
  374. host = '';
  375. }
  376. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  377. if (search && search.charAt(0) !== '?') search = '?' + search;
  378. pathname = pathname.replace(/[?#]/g, function(match) {
  379. return encodeURIComponent(match);
  380. });
  381. search = search.replace('#', '%23');
  382. return protocol + host + pathname + search + hash;
  383. };
  384. function urlResolve(source, relative) {
  385. return urlParse(source, false, true).resolve(relative);
  386. }
  387. Url.prototype.resolve = function(relative) {
  388. return this.resolveObject(urlParse(relative, false, true)).format();
  389. };
  390. function urlResolveObject(source, relative) {
  391. if (!source) return relative;
  392. return urlParse(source, false, true).resolveObject(relative);
  393. }
  394. Url.prototype.resolveObject = function(relative) {
  395. if (util.isString(relative)) {
  396. var rel = new Url();
  397. rel.parse(relative, false, true);
  398. relative = rel;
  399. }
  400. var result = new Url();
  401. var tkeys = Object.keys(this);
  402. for (var tk = 0; tk < tkeys.length; tk++) {
  403. var tkey = tkeys[tk];
  404. result[tkey] = this[tkey];
  405. }
  406. // hash is always overridden, no matter what.
  407. // even href="" will remove it.
  408. result.hash = relative.hash;
  409. // if the relative url is empty, then there's nothing left to do here.
  410. if (relative.href === '') {
  411. result.href = result.format();
  412. return result;
  413. }
  414. // hrefs like //foo/bar always cut to the protocol.
  415. if (relative.slashes && !relative.protocol) {
  416. // take everything except the protocol from relative
  417. var rkeys = Object.keys(relative);
  418. for (var rk = 0; rk < rkeys.length; rk++) {
  419. var rkey = rkeys[rk];
  420. if (rkey !== 'protocol')
  421. result[rkey] = relative[rkey];
  422. }
  423. //urlParse appends trailing / to urls like http://www.example.com
  424. if (slashedProtocol[result.protocol] &&
  425. result.hostname && !result.pathname) {
  426. result.path = result.pathname = '/';
  427. }
  428. result.href = result.format();
  429. return result;
  430. }
  431. if (relative.protocol && relative.protocol !== result.protocol) {
  432. // if it's a known url protocol, then changing
  433. // the protocol does weird things
  434. // first, if it's not file:, then we MUST have a host,
  435. // and if there was a path
  436. // to begin with, then we MUST have a path.
  437. // if it is file:, then the host is dropped,
  438. // because that's known to be hostless.
  439. // anything else is assumed to be absolute.
  440. if (!slashedProtocol[relative.protocol]) {
  441. var keys = Object.keys(relative);
  442. for (var v = 0; v < keys.length; v++) {
  443. var k = keys[v];
  444. result[k] = relative[k];
  445. }
  446. result.href = result.format();
  447. return result;
  448. }
  449. result.protocol = relative.protocol;
  450. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  451. var relPath = (relative.pathname || '').split('/');
  452. while (relPath.length && !(relative.host = relPath.shift()));
  453. if (!relative.host) relative.host = '';
  454. if (!relative.hostname) relative.hostname = '';
  455. if (relPath[0] !== '') relPath.unshift('');
  456. if (relPath.length < 2) relPath.unshift('');
  457. result.pathname = relPath.join('/');
  458. } else {
  459. result.pathname = relative.pathname;
  460. }
  461. result.search = relative.search;
  462. result.query = relative.query;
  463. result.host = relative.host || '';
  464. result.auth = relative.auth;
  465. result.hostname = relative.hostname || relative.host;
  466. result.port = relative.port;
  467. // to support http.request
  468. if (result.pathname || result.search) {
  469. var p = result.pathname || '';
  470. var s = result.search || '';
  471. result.path = p + s;
  472. }
  473. result.slashes = result.slashes || relative.slashes;
  474. result.href = result.format();
  475. return result;
  476. }
  477. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  478. isRelAbs = (
  479. relative.host ||
  480. relative.pathname && relative.pathname.charAt(0) === '/'
  481. ),
  482. mustEndAbs = (isRelAbs || isSourceAbs ||
  483. (result.host && relative.pathname)),
  484. removeAllDots = mustEndAbs,
  485. srcPath = result.pathname && result.pathname.split('/') || [],
  486. relPath = relative.pathname && relative.pathname.split('/') || [],
  487. psychotic = result.protocol && !slashedProtocol[result.protocol];
  488. // if the url is a non-slashed url, then relative
  489. // links like ../.. should be able
  490. // to crawl up to the hostname, as well. This is strange.
  491. // result.protocol has already been set by now.
  492. // Later on, put the first path part into the host field.
  493. if (psychotic) {
  494. result.hostname = '';
  495. result.port = null;
  496. if (result.host) {
  497. if (srcPath[0] === '') srcPath[0] = result.host;
  498. else srcPath.unshift(result.host);
  499. }
  500. result.host = '';
  501. if (relative.protocol) {
  502. relative.hostname = null;
  503. relative.port = null;
  504. if (relative.host) {
  505. if (relPath[0] === '') relPath[0] = relative.host;
  506. else relPath.unshift(relative.host);
  507. }
  508. relative.host = null;
  509. }
  510. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  511. }
  512. if (isRelAbs) {
  513. // it's absolute.
  514. result.host = (relative.host || relative.host === '') ?
  515. relative.host : result.host;
  516. result.hostname = (relative.hostname || relative.hostname === '') ?
  517. relative.hostname : result.hostname;
  518. result.search = relative.search;
  519. result.query = relative.query;
  520. srcPath = relPath;
  521. // fall through to the dot-handling below.
  522. } else if (relPath.length) {
  523. // it's relative
  524. // throw away the existing file, and take the new path instead.
  525. if (!srcPath) srcPath = [];
  526. srcPath.pop();
  527. srcPath = srcPath.concat(relPath);
  528. result.search = relative.search;
  529. result.query = relative.query;
  530. } else if (!util.isNullOrUndefined(relative.search)) {
  531. // just pull out the search.
  532. // like href='?foo'.
  533. // Put this after the other two cases because it simplifies the booleans
  534. if (psychotic) {
  535. result.hostname = result.host = srcPath.shift();
  536. //occationaly the auth can get stuck only in host
  537. //this especially happens in cases like
  538. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  539. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  540. result.host.split('@') : false;
  541. if (authInHost) {
  542. result.auth = authInHost.shift();
  543. result.host = result.hostname = authInHost.shift();
  544. }
  545. }
  546. result.search = relative.search;
  547. result.query = relative.query;
  548. //to support http.request
  549. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  550. result.path = (result.pathname ? result.pathname : '') +
  551. (result.search ? result.search : '');
  552. }
  553. result.href = result.format();
  554. return result;
  555. }
  556. if (!srcPath.length) {
  557. // no path at all. easy.
  558. // we've already handled the other stuff above.
  559. result.pathname = null;
  560. //to support http.request
  561. if (result.search) {
  562. result.path = '/' + result.search;
  563. } else {
  564. result.path = null;
  565. }
  566. result.href = result.format();
  567. return result;
  568. }
  569. // if a url ENDs in . or .., then it must get a trailing slash.
  570. // however, if it ends in anything else non-slashy,
  571. // then it must NOT get a trailing slash.
  572. var last = srcPath.slice(-1)[0];
  573. var hasTrailingSlash = (
  574. (result.host || relative.host || srcPath.length > 1) &&
  575. (last === '.' || last === '..') || last === '');
  576. // strip single dots, resolve double dots to parent dir
  577. // if the path tries to go above the root, `up` ends up > 0
  578. var up = 0;
  579. for (var i = srcPath.length; i >= 0; i--) {
  580. last = srcPath[i];
  581. if (last === '.') {
  582. srcPath.splice(i, 1);
  583. } else if (last === '..') {
  584. srcPath.splice(i, 1);
  585. up++;
  586. } else if (up) {
  587. srcPath.splice(i, 1);
  588. up--;
  589. }
  590. }
  591. // if the path is allowed to go above the root, restore leading ..s
  592. if (!mustEndAbs && !removeAllDots) {
  593. for (; up--; up) {
  594. srcPath.unshift('..');
  595. }
  596. }
  597. if (mustEndAbs && srcPath[0] !== '' &&
  598. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  599. srcPath.unshift('');
  600. }
  601. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  602. srcPath.push('');
  603. }
  604. var isAbsolute = srcPath[0] === '' ||
  605. (srcPath[0] && srcPath[0].charAt(0) === '/');
  606. // put the host back
  607. if (psychotic) {
  608. result.hostname = result.host = isAbsolute ? '' :
  609. srcPath.length ? srcPath.shift() : '';
  610. //occationaly the auth can get stuck only in host
  611. //this especially happens in cases like
  612. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  613. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  614. result.host.split('@') : false;
  615. if (authInHost) {
  616. result.auth = authInHost.shift();
  617. result.host = result.hostname = authInHost.shift();
  618. }
  619. }
  620. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  621. if (mustEndAbs && !isAbsolute) {
  622. srcPath.unshift('');
  623. }
  624. if (!srcPath.length) {
  625. result.pathname = null;
  626. result.path = null;
  627. } else {
  628. result.pathname = srcPath.join('/');
  629. }
  630. //to support request.http
  631. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  632. result.path = (result.pathname ? result.pathname : '') +
  633. (result.search ? result.search : '');
  634. }
  635. result.auth = relative.auth || result.auth;
  636. result.slashes = result.slashes || relative.slashes;
  637. result.href = result.format();
  638. return result;
  639. };
  640. Url.prototype.parseHost = function() {
  641. var host = this.host;
  642. var port = portPattern.exec(host);
  643. if (port) {
  644. port = port[0];
  645. if (port !== ':') {
  646. this.port = port.substr(1);
  647. }
  648. host = host.substr(0, host.length - port.length);
  649. }
  650. if (host) this.hostname = host;
  651. };