url.js 23 KB

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