url-parse.js 17 KB

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