url-parse.js 15 KB

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