url-parse.js 15 KB

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