index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. 'use strict';
  2. var required = require('requires-port')
  3. , qs = require('querystringify')
  4. , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i
  5. , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;
  6. /**
  7. * These are the parse rules for the URL parser, it informs the parser
  8. * about:
  9. *
  10. * 0. The char it Needs to parse, if it's a string it should be done using
  11. * indexOf, RegExp using exec and NaN means set as current value.
  12. * 1. The property we should set when parsing this value.
  13. * 2. Indication if it's backwards or forward parsing, when set as number it's
  14. * the value of extra chars that should be split off.
  15. * 3. Inherit from location if non existing in the parser.
  16. * 4. `toLowerCase` the resulting value.
  17. */
  18. var rules = [
  19. ['#', 'hash'], // Extract from the back.
  20. ['?', 'query'], // Extract from the back.
  21. function sanitize(address) { // Sanitize what is left of the address
  22. return address.replace('\\', '/');
  23. },
  24. ['/', 'pathname'], // Extract from the back.
  25. ['@', 'auth', 1], // Extract from the front.
  26. [NaN, 'host', undefined, 1, 1], // Set left over value.
  27. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back.
  28. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  29. ];
  30. /**
  31. * These properties should not be copied or inherited from. This is only needed
  32. * for all non blob URL's as a blob URL does not include a hash, only the
  33. * origin.
  34. *
  35. * @type {Object}
  36. * @private
  37. */
  38. var ignore = { hash: 1, query: 1 };
  39. /**
  40. * The location object differs when your code is loaded through a normal page,
  41. * Worker or through a worker using a blob. And with the blobble begins the
  42. * trouble as the location object will contain the URL of the blob, not the
  43. * location of the page where our code is loaded in. The actual origin is
  44. * encoded in the `pathname` so we can thankfully generate a good "default"
  45. * location from it so we can generate proper relative URL's again.
  46. *
  47. * @param {Object|String} loc Optional default location object.
  48. * @returns {Object} lolcation object.
  49. * @public
  50. */
  51. function lolcation(loc) {
  52. var location = global && global.location || {};
  53. loc = loc || location;
  54. var finaldestination = {}
  55. , type = typeof loc
  56. , key;
  57. if ('blob:' === loc.protocol) {
  58. finaldestination = new Url(unescape(loc.pathname), {});
  59. } else if ('string' === type) {
  60. finaldestination = new Url(loc, {});
  61. for (key in ignore) delete finaldestination[key];
  62. } else if ('object' === type) {
  63. for (key in loc) {
  64. if (key in ignore) continue;
  65. finaldestination[key] = loc[key];
  66. }
  67. if (finaldestination.slashes === undefined) {
  68. finaldestination.slashes = slashes.test(loc.href);
  69. }
  70. }
  71. return finaldestination;
  72. }
  73. /**
  74. * @typedef ProtocolExtract
  75. * @type Object
  76. * @property {String} protocol Protocol matched in the URL, in lowercase.
  77. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
  78. * @property {String} rest Rest of the URL that is not part of the protocol.
  79. */
  80. /**
  81. * Extract protocol information from a URL with/without double slash ("//").
  82. *
  83. * @param {String} address URL we want to extract from.
  84. * @return {ProtocolExtract} Extracted information.
  85. * @private
  86. */
  87. function extractProtocol(address) {
  88. var match = protocolre.exec(address);
  89. return {
  90. protocol: match[1] ? match[1].toLowerCase() : '',
  91. slashes: !!match[2],
  92. rest: match[3]
  93. };
  94. }
  95. /**
  96. * Resolve a relative URL pathname against a base URL pathname.
  97. *
  98. * @param {String} relative Pathname of the relative URL.
  99. * @param {String} base Pathname of the base URL.
  100. * @return {String} Resolved pathname.
  101. * @private
  102. */
  103. function resolve(relative, base) {
  104. var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
  105. , i = path.length
  106. , last = path[i - 1]
  107. , unshift = false
  108. , up = 0;
  109. while (i--) {
  110. if (path[i] === '.') {
  111. path.splice(i, 1);
  112. } else if (path[i] === '..') {
  113. path.splice(i, 1);
  114. up++;
  115. } else if (up) {
  116. if (i === 0) unshift = true;
  117. path.splice(i, 1);
  118. up--;
  119. }
  120. }
  121. if (unshift) path.unshift('');
  122. if (last === '.' || last === '..') path.push('');
  123. return path.join('/');
  124. }
  125. /**
  126. * The actual URL instance. Instead of returning an object we've opted-in to
  127. * create an actual constructor as it's much more memory efficient and
  128. * faster and it pleases my OCD.
  129. *
  130. * It is worth noting that we should not use `URL` as class name to prevent
  131. * clashes with the global URL instance that got introduced in browsers.
  132. *
  133. * @constructor
  134. * @param {String} address URL we want to parse.
  135. * @param {Object|String} location Location defaults for relative paths.
  136. * @param {Boolean|Function} parser Parser for the query string.
  137. * @private
  138. */
  139. function Url(address, location, parser) {
  140. if (!(this instanceof Url)) {
  141. return new Url(address, location, parser);
  142. }
  143. var relative, extracted, parse, instruction, index, key
  144. , instructions = rules.slice()
  145. , type = typeof location
  146. , url = this
  147. , i = 0;
  148. //
  149. // The following if statements allows this module two have compatibility with
  150. // 2 different API:
  151. //
  152. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  153. // where the boolean indicates that the query string should also be parsed.
  154. //
  155. // 2. The `URL` interface of the browser which accepts a URL, object as
  156. // arguments. The supplied object will be used as default values / fall-back
  157. // for relative paths.
  158. //
  159. if ('object' !== type && 'string' !== type) {
  160. parser = location;
  161. location = null;
  162. }
  163. if (parser && 'function' !== typeof parser) parser = qs.parse;
  164. location = lolcation(location);
  165. //
  166. // Extract protocol information before running the instructions.
  167. //
  168. extracted = extractProtocol(address || '');
  169. relative = !extracted.protocol && !extracted.slashes;
  170. url.slashes = extracted.slashes || relative && location.slashes;
  171. url.protocol = extracted.protocol || location.protocol || '';
  172. address = extracted.rest;
  173. //
  174. // When the authority component is absent the URL starts with a path
  175. // component.
  176. //
  177. if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];
  178. for (; i < instructions.length; i++) {
  179. instruction = instructions[i];
  180. if (typeof instruction === 'function') {
  181. address = instruction(address);
  182. continue;
  183. }
  184. parse = instruction[0];
  185. key = instruction[1];
  186. if (parse !== parse) {
  187. url[key] = address;
  188. } else if ('string' === typeof parse) {
  189. if (~(index = address.indexOf(parse))) {
  190. if ('number' === typeof instruction[2]) {
  191. url[key] = address.slice(0, index);
  192. address = address.slice(index + instruction[2]);
  193. } else {
  194. url[key] = address.slice(index);
  195. address = address.slice(0, index);
  196. }
  197. }
  198. } else if ((index = parse.exec(address))) {
  199. url[key] = index[1];
  200. address = address.slice(0, index.index);
  201. }
  202. url[key] = url[key] || (
  203. relative && instruction[3] ? location[key] || '' : ''
  204. );
  205. //
  206. // Hostname, host and protocol should be lowercased so they can be used to
  207. // create a proper `origin`.
  208. //
  209. if (instruction[4]) url[key] = url[key].toLowerCase();
  210. }
  211. //
  212. // Also parse the supplied query string in to an object. If we're supplied
  213. // with a custom parser as function use that instead of the default build-in
  214. // parser.
  215. //
  216. if (parser) url.query = parser(url.query);
  217. //
  218. // If the URL is relative, resolve the pathname against the base URL.
  219. //
  220. if (
  221. relative
  222. && location.slashes
  223. && url.pathname.charAt(0) !== '/'
  224. && (url.pathname !== '' || location.pathname !== '')
  225. ) {
  226. url.pathname = resolve(url.pathname, location.pathname);
  227. }
  228. //
  229. // We should not add port numbers if they are already the default port number
  230. // for a given protocol. As the host also contains the port number we're going
  231. // override it with the hostname which contains no port number.
  232. //
  233. if (!required(url.port, url.protocol)) {
  234. url.host = url.hostname;
  235. url.port = '';
  236. }
  237. //
  238. // Parse down the `auth` for the username and password.
  239. //
  240. url.username = url.password = '';
  241. if (url.auth) {
  242. instruction = url.auth.split(':');
  243. url.username = instruction[0] || '';
  244. url.password = instruction[1] || '';
  245. }
  246. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  247. ? url.protocol +'//'+ url.host
  248. : 'null';
  249. //
  250. // The href is just the compiled result.
  251. //
  252. url.href = url.toString();
  253. }
  254. /**
  255. * This is convenience method for changing properties in the URL instance to
  256. * insure that they all propagate correctly.
  257. *
  258. * @param {String} part Property we need to adjust.
  259. * @param {Mixed} value The newly assigned value.
  260. * @param {Boolean|Function} fn When setting the query, it will be the function
  261. * used to parse the query.
  262. * When setting the protocol, double slash will be
  263. * removed from the final url if it is true.
  264. * @returns {URL} URL instance for chaining.
  265. * @public
  266. */
  267. function set(part, value, fn) {
  268. var url = this;
  269. switch (part) {
  270. case 'query':
  271. if ('string' === typeof value && value.length) {
  272. value = (fn || qs.parse)(value);
  273. }
  274. url[part] = value;
  275. break;
  276. case 'port':
  277. url[part] = value;
  278. if (!required(value, url.protocol)) {
  279. url.host = url.hostname;
  280. url[part] = '';
  281. } else if (value) {
  282. url.host = url.hostname +':'+ value;
  283. }
  284. break;
  285. case 'hostname':
  286. url[part] = value;
  287. if (url.port) value += ':'+ url.port;
  288. url.host = value;
  289. break;
  290. case 'host':
  291. url[part] = value;
  292. if (/:\d+$/.test(value)) {
  293. value = value.split(':');
  294. url.port = value.pop();
  295. url.hostname = value.join(':');
  296. } else {
  297. url.hostname = value;
  298. url.port = '';
  299. }
  300. break;
  301. case 'protocol':
  302. url.protocol = value.toLowerCase();
  303. url.slashes = !fn;
  304. break;
  305. case 'pathname':
  306. case 'hash':
  307. if (value) {
  308. var char = part === 'pathname' ? '/' : '#';
  309. url[part] = value.charAt(0) !== char ? char + value : value;
  310. } else {
  311. url[part] = value;
  312. }
  313. break;
  314. default:
  315. url[part] = value;
  316. }
  317. for (var i = 0; i < rules.length; i++) {
  318. var ins = rules[i];
  319. if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  320. }
  321. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  322. ? url.protocol +'//'+ url.host
  323. : 'null';
  324. url.href = url.toString();
  325. return url;
  326. }
  327. /**
  328. * Transform the properties back in to a valid and full URL string.
  329. *
  330. * @param {Function} stringify Optional query stringify function.
  331. * @returns {String} Compiled version of the URL.
  332. * @public
  333. */
  334. function toString(stringify) {
  335. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  336. var query
  337. , url = this
  338. , protocol = url.protocol;
  339. if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  340. var result = protocol + (url.slashes ? '//' : '');
  341. if (url.username) {
  342. result += url.username;
  343. if (url.password) result += ':'+ url.password;
  344. result += '@';
  345. }
  346. result += url.host + url.pathname;
  347. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  348. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  349. if (url.hash) result += url.hash;
  350. return result;
  351. }
  352. Url.prototype = { set: set, toString: toString };
  353. //
  354. // Expose the URL parser and some additional properties that might be useful for
  355. // others or testing.
  356. //
  357. Url.extractProtocol = extractProtocol;
  358. Url.location = lolcation;
  359. Url.qs = qs;
  360. module.exports = Url;