URI.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  1. /*!
  2. * URI.js - Mutating URLs
  3. *
  4. * Version: 1.8.3
  5. *
  6. * Author: Rodney Rehm
  7. * Web: http://medialize.github.com/URI.js/
  8. *
  9. * Licensed under
  10. * MIT License http://www.opensource.org/licenses/mit-license
  11. * GPL v3 http://opensource.org/licenses/GPL-3.0
  12. *
  13. */
  14. (function(root, factory) {
  15. // https://github.com/umdjs/umd/blob/master/returnExports.js
  16. if (typeof exports === 'object') {
  17. // Node
  18. module.exports = factory(require('./punycode'), require('./IPv6'), require('./SecondLevelDomains'));
  19. } else if (typeof define === 'function' && define.amd) {
  20. // AMD. Register as an anonymous module.
  21. define(['./punycode', './IPv6', './SecondLevelDomains'], factory);
  22. } else {
  23. // Browser globals (root is window)
  24. root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains);
  25. }
  26. }(this, function(punycode, IPv6, SLD) {
  27. "use strict";
  28. function URI(url, base) {
  29. // Allow instantiation without the 'new' keyword
  30. if (!(this instanceof URI)) {
  31. return new URI(url, base);
  32. }
  33. if (url === undefined) {
  34. if (typeof location !== 'undefined') {
  35. url = location.href + "";
  36. } else {
  37. url = "";
  38. }
  39. }
  40. this.href(url);
  41. // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
  42. if (base !== undefined) {
  43. return this.absoluteTo(base);
  44. }
  45. return this;
  46. };
  47. var p = URI.prototype;
  48. var hasOwn = Object.prototype.hasOwnProperty;
  49. function escapeRegEx(string) {
  50. // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
  51. return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  52. }
  53. function isArray(obj) {
  54. return String(Object.prototype.toString.call(obj)) === "[object Array]";
  55. }
  56. function filterArrayValues(data, value) {
  57. var lookup = {};
  58. var i, length;
  59. if (isArray(value)) {
  60. for (i = 0, length = value.length; i < length; i++) {
  61. lookup[value[i]] = true;
  62. }
  63. } else {
  64. lookup[value] = true;
  65. }
  66. for (i = 0, length = data.length; i < length; i++) {
  67. if (lookup[data[i]] !== undefined) {
  68. data.splice(i, 1);
  69. length--;
  70. i--;
  71. }
  72. }
  73. return data;
  74. }
  75. URI._parts = function() {
  76. return {
  77. protocol: null,
  78. username: null,
  79. password: null,
  80. hostname: null,
  81. urn: null,
  82. port: null,
  83. path: null,
  84. query: null,
  85. fragment: null,
  86. // state
  87. duplicateQueryParameters: URI.duplicateQueryParameters
  88. };
  89. };
  90. // state: allow duplicate query parameters (a=1&a=1)
  91. URI.duplicateQueryParameters = false;
  92. // static properties
  93. URI.protocol_expression = /^[a-z][a-z0-9-+-]*$/i;
  94. URI.idn_expression = /[^a-z0-9\.-]/i;
  95. URI.punycode_expression = /(xn--)/i;
  96. // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
  97. URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  98. // credits to Rich Brown
  99. // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
  100. // specification: http://www.ietf.org/rfc/rfc4291.txt
  101. URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
  102. // gruber revised expression - http://rodneyrehm.de/t/url-regex.html
  103. URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
  104. // http://www.iana.org/assignments/uri-schemes.html
  105. // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
  106. URI.defaultPorts = {
  107. http: "80",
  108. https: "443",
  109. ftp: "21",
  110. gopher: "70",
  111. ws: "80",
  112. wss: "443"
  113. };
  114. // allowed hostname characters according to RFC 3986
  115. // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
  116. // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . -
  117. URI.invalid_hostname_characters = /[^a-zA-Z0-9\.-]/;
  118. // encoding / decoding according to RFC3986
  119. function strictEncodeURIComponent(string) {
  120. // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
  121. return encodeURIComponent(string).replace(/[!'()*]/g, escape).replace(/\*/g, "%2A");
  122. }
  123. URI.encode = strictEncodeURIComponent;
  124. URI.decode = decodeURIComponent;
  125. URI.iso8859 = function() {
  126. URI.encode = escape;
  127. URI.decode = unescape;
  128. };
  129. URI.unicode = function() {
  130. URI.encode = strictEncodeURIComponent;
  131. URI.decode = decodeURIComponent;
  132. };
  133. URI.characters = {
  134. pathname: {
  135. encode: {
  136. // RFC3986 2.1: For consistency, URI producers and normalizers should
  137. // use uppercase hexadecimal digits for all percent-encodings.
  138. expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
  139. map: {
  140. // -._~!'()*
  141. "%24": "$",
  142. "%26": "&",
  143. "%2B": "+",
  144. "%2C": ",",
  145. "%3B": ";",
  146. "%3D": "=",
  147. "%3A": ":",
  148. "%40": "@"
  149. }
  150. },
  151. decode: {
  152. expression: /[\/\?#]/g,
  153. map: {
  154. "/": "%2F",
  155. "?": "%3F",
  156. "#": "%23"
  157. }
  158. }
  159. },
  160. reserved: {
  161. encode: {
  162. // RFC3986 2.1: For consistency, URI producers and normalizers should
  163. // use uppercase hexadecimal digits for all percent-encodings.
  164. expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
  165. map: {
  166. // gen-delims
  167. "%3A": ":",
  168. "%2F": "/",
  169. "%3F": "?",
  170. "%23": "#",
  171. "%5B": "[",
  172. "%5D": "]",
  173. "%40": "@",
  174. // sub-delims
  175. "%21": "!",
  176. "%24": "$",
  177. "%26": "&",
  178. "%27": "'",
  179. "%28": "(",
  180. "%29": ")",
  181. "%2A": "*",
  182. "%2B": "+",
  183. "%2C": ",",
  184. "%3B": ";",
  185. "%3D": "="
  186. }
  187. }
  188. }
  189. };
  190. URI.encodeQuery = function(string) {
  191. return URI.encode(string + "").replace(/%20/g, '+');
  192. };
  193. URI.decodeQuery = function(string) {
  194. return URI.decode((string + "").replace(/\+/g, '%20'));
  195. };
  196. URI.recodePath = function(string) {
  197. var segments = (string + "").split('/');
  198. for (var i = 0, length = segments.length; i < length; i++) {
  199. segments[i] = URI.encodePathSegment(URI.decode(segments[i]));
  200. }
  201. return segments.join('/');
  202. };
  203. URI.decodePath = function(string) {
  204. var segments = (string + "").split('/');
  205. for (var i = 0, length = segments.length; i < length; i++) {
  206. segments[i] = URI.decodePathSegment(segments[i]);
  207. }
  208. return segments.join('/');
  209. };
  210. // generate encode/decode path functions
  211. var _parts = {
  212. 'encode': 'encode',
  213. 'decode': 'decode'
  214. };
  215. var _part;
  216. var generateAccessor = function(_group, _part) {
  217. return function(string) {
  218. return URI[_part](string + "").replace(URI.characters[_group][_part].expression, function(c) {
  219. return URI.characters[_group][_part].map[c];
  220. });
  221. };
  222. };
  223. for (_part in _parts) {
  224. URI[_part + "PathSegment"] = generateAccessor("pathname", _parts[_part]);
  225. }
  226. URI.encodeReserved = generateAccessor("reserved", "encode");
  227. URI.parse = function(string, parts) {
  228. var pos, t;
  229. if (!parts) {
  230. parts = {};
  231. }
  232. // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
  233. // extract fragment
  234. pos = string.indexOf('#');
  235. if (pos > -1) {
  236. // escaping?
  237. parts.fragment = string.substring(pos + 1) || null;
  238. string = string.substring(0, pos);
  239. }
  240. // extract query
  241. pos = string.indexOf('?');
  242. if (pos > -1) {
  243. // escaping?
  244. parts.query = string.substring(pos + 1) || null;
  245. string = string.substring(0, pos);
  246. }
  247. // extract protocol
  248. if (string.substring(0, 2) === '//') {
  249. // relative-scheme
  250. parts.protocol = '';
  251. string = string.substring(2);
  252. // extract "user:pass@host:port"
  253. string = URI.parseAuthority(string, parts);
  254. } else {
  255. pos = string.indexOf(':');
  256. if (pos > -1) {
  257. parts.protocol = string.substring(0, pos);
  258. if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
  259. // : may be within the path
  260. parts.protocol = undefined;
  261. } else if (parts.protocol === 'file') {
  262. // the file scheme: does not contain an authority
  263. string = string.substring(pos + 3);
  264. } else if (string.substring(pos + 1, pos + 3) === '//') {
  265. string = string.substring(pos + 3);
  266. // extract "user:pass@host:port"
  267. string = URI.parseAuthority(string, parts);
  268. } else {
  269. string = string.substring(pos + 1);
  270. parts.urn = true;
  271. }
  272. }
  273. }
  274. // what's left must be the path
  275. parts.path = string;
  276. // and we're done
  277. return parts;
  278. };
  279. URI.parseHost = function(string, parts) {
  280. // extract host:port
  281. var pos = string.indexOf('/');
  282. var bracketPos;
  283. var t;
  284. if (pos === -1) {
  285. pos = string.length;
  286. }
  287. if (string[0] === "[") {
  288. // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
  289. // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
  290. // IPv6+port in the format [2001:db8::1]:80 (for the time being)
  291. bracketPos = string.indexOf(']');
  292. parts.hostname = string.substring(1, bracketPos) || null;
  293. parts.port = string.substring(bracketPos + 2, pos) || null;
  294. } else if (string.indexOf(':') !== string.lastIndexOf(':')) {
  295. // IPv6 host contains multiple colons - but no port
  296. // this notation is actually not allowed by RFC 3986, but we're a liberal parser
  297. parts.hostname = string.substring(0, pos) || null;
  298. parts.port = null;
  299. } else {
  300. t = string.substring(0, pos).split(':');
  301. parts.hostname = t[0] || null;
  302. parts.port = t[1] || null;
  303. }
  304. if (parts.hostname && string.substring(pos)[0] !== '/') {
  305. pos++;
  306. string = "/" + string;
  307. }
  308. return string.substring(pos) || '/';
  309. };
  310. URI.parseAuthority = function(string, parts) {
  311. string = URI.parseUserinfo(string, parts);
  312. return URI.parseHost(string, parts);
  313. };
  314. URI.parseUserinfo = function(string, parts) {
  315. // extract username:password
  316. var pos = string.indexOf('@');
  317. var firstSlash = string.indexOf('/');
  318. var t;
  319. // authority@ must come before /path
  320. if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
  321. t = string.substring(0, pos).split(':');
  322. parts.username = t[0] ? URI.decode(t[0]) : null;
  323. t.shift();
  324. parts.password = t[0] ? URI.decode(t.join(':')) : null;
  325. string = string.substring(pos + 1);
  326. } else {
  327. parts.username = null;
  328. parts.password = null;
  329. }
  330. return string;
  331. };
  332. URI.parseQuery = function(string) {
  333. if (!string) {
  334. return {};
  335. }
  336. // throw out the funky business - "?"[name"="value"&"]+
  337. string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
  338. if (!string) {
  339. return {};
  340. }
  341. var items = {};
  342. var splits = string.split('&');
  343. var length = splits.length;
  344. var v, name, value;
  345. for (var i = 0; i < length; i++) {
  346. v = splits[i].split('=');
  347. name = URI.decodeQuery(v.shift());
  348. // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
  349. value = v.length ? URI.decodeQuery(v.join('=')) : null;
  350. if (items[name]) {
  351. if (typeof items[name] === "string") {
  352. items[name] = [items[name]];
  353. }
  354. items[name].push(value);
  355. } else {
  356. items[name] = value;
  357. }
  358. }
  359. return items;
  360. };
  361. URI.build = function(parts) {
  362. var t = "";
  363. if (parts.protocol) {
  364. t += parts.protocol + ":";
  365. }
  366. if (!parts.urn && (t || parts.hostname)) {
  367. t += '//';
  368. }
  369. t += (URI.buildAuthority(parts) || '');
  370. if (typeof parts.path === "string") {
  371. if (parts.path[0] !== '/' && typeof parts.hostname === "string") {
  372. t += '/';
  373. }
  374. t += parts.path;
  375. }
  376. if (typeof parts.query === "string" && parts.query) {
  377. t += '?' + parts.query;
  378. }
  379. if (typeof parts.fragment === "string" && parts.fragment) {
  380. t += '#' + parts.fragment;
  381. }
  382. return t;
  383. };
  384. URI.buildHost = function(parts) {
  385. var t = "";
  386. if (!parts.hostname) {
  387. return "";
  388. } else if (URI.ip6_expression.test(parts.hostname)) {
  389. if (parts.port) {
  390. t += "[" + parts.hostname + "]:" + parts.port;
  391. } else {
  392. // don't know if we should always wrap IPv6 in []
  393. // the RFC explicitly says SHOULD, not MUST.
  394. t += parts.hostname;
  395. }
  396. } else {
  397. t += parts.hostname;
  398. if (parts.port) {
  399. t += ':' + parts.port;
  400. }
  401. }
  402. return t;
  403. };
  404. URI.buildAuthority = function(parts) {
  405. return URI.buildUserinfo(parts) + URI.buildHost(parts);
  406. };
  407. URI.buildUserinfo = function(parts) {
  408. var t = "";
  409. if (parts.username) {
  410. t += URI.encode(parts.username);
  411. if (parts.password) {
  412. t += ':' + URI.encode(parts.password);
  413. }
  414. t += "@";
  415. }
  416. return t;
  417. };
  418. URI.buildQuery = function(data, duplicates) {
  419. // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
  420. // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
  421. // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
  422. // URI.js treats the query string as being application/x-www-form-urlencoded
  423. // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
  424. var t = "";
  425. var unique, key, i, length;
  426. for (key in data) {
  427. if (hasOwn.call(data, key) && key) {
  428. if (isArray(data[key])) {
  429. unique = {};
  430. for (i = 0, length = data[key].length; i < length; i++) {
  431. if (data[key][i] !== undefined && unique[data[key][i] + ""] === undefined) {
  432. t += "&" + URI.buildQueryParameter(key, data[key][i]);
  433. if (duplicates !== true) {
  434. unique[data[key][i] + ""] = true;
  435. }
  436. }
  437. }
  438. } else if (data[key] !== undefined) {
  439. t += '&' + URI.buildQueryParameter(key, data[key]);
  440. }
  441. }
  442. }
  443. return t.substring(1);
  444. };
  445. URI.buildQueryParameter = function(name, value) {
  446. // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
  447. // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
  448. return URI.encodeQuery(name) + (value !== null ? "=" + URI.encodeQuery(value) : "");
  449. };
  450. URI.addQuery = function(data, name, value) {
  451. if (typeof name === "object") {
  452. for (var key in name) {
  453. if (hasOwn.call(name, key)) {
  454. URI.addQuery(data, key, name[key]);
  455. }
  456. }
  457. } else if (typeof name === "string") {
  458. if (data[name] === undefined) {
  459. data[name] = value;
  460. return;
  461. } else if (typeof data[name] === "string") {
  462. data[name] = [data[name]];
  463. }
  464. if (!isArray(value)) {
  465. value = [value];
  466. }
  467. data[name] = data[name].concat(value);
  468. } else {
  469. throw new TypeError("URI.addQuery() accepts an object, string as the name parameter");
  470. }
  471. };
  472. URI.removeQuery = function(data, name, value) {
  473. var i, length, key;
  474. if (isArray(name)) {
  475. for (i = 0, length = name.length; i < length; i++) {
  476. data[name[i]] = undefined;
  477. }
  478. } else if (typeof name === "object") {
  479. for (key in name) {
  480. if (hasOwn.call(name, key)) {
  481. URI.removeQuery(data, key, name[key]);
  482. }
  483. }
  484. } else if (typeof name === "string") {
  485. if (value !== undefined) {
  486. if (data[name] === value) {
  487. data[name] = undefined;
  488. } else if (isArray(data[name])) {
  489. data[name] = filterArrayValues(data[name], value);
  490. }
  491. } else {
  492. data[name] = undefined;
  493. }
  494. } else {
  495. throw new TypeError("URI.addQuery() accepts an object, string as the first parameter");
  496. }
  497. };
  498. URI.commonPath = function(one, two) {
  499. var length = Math.min(one.length, two.length);
  500. var pos;
  501. // find first non-matching character
  502. for (pos = 0; pos < length; pos++) {
  503. if (one[pos] !== two[pos]) {
  504. pos--;
  505. break;
  506. }
  507. }
  508. if (pos < 1) {
  509. return one[0] === two[0] && one[0] === '/' ? '/' : '';
  510. }
  511. // revert to last /
  512. if (one[pos] !== '/') {
  513. pos = one.substring(0, pos).lastIndexOf('/');
  514. }
  515. return one.substring(0, pos + 1);
  516. };
  517. URI.withinString = function(string, callback) {
  518. // expression used is "gruber revised" (@gruber v2) determined to be the best solution in
  519. // a regex sprint we did a couple of ages ago at
  520. // * http://mathiasbynens.be/demo/url-regex
  521. // * http://rodneyrehm.de/t/url-regex.html
  522. return string.replace(URI.find_uri_expression, callback);
  523. };
  524. URI.ensureValidHostname = function(v) {
  525. // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
  526. // they are not part of DNS and therefore ignored by URI.js
  527. if (v.match(URI.invalid_hostname_characters)) {
  528. // test punycode
  529. if (!punycode) {
  530. throw new TypeError("Hostname '" + v + "' contains characters other than [A-Z0-9.-] and Punycode.js is not available");
  531. }
  532. if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
  533. throw new TypeError("Hostname '" + v + "' contains characters other than [A-Z0-9.-]");
  534. }
  535. }
  536. };
  537. p.build = function(deferBuild) {
  538. if (deferBuild === true) {
  539. this._deferred_build = true;
  540. } else if (deferBuild === undefined || this._deferred_build) {
  541. this._string = URI.build(this._parts);
  542. this._deferred_build = false;
  543. }
  544. return this;
  545. };
  546. p.clone = function() {
  547. return new URI(this);
  548. };
  549. p.valueOf = p.toString = function() {
  550. return this.build(false)._string;
  551. };
  552. // generate simple accessors
  553. _parts = {
  554. protocol: 'protocol',
  555. username: 'username',
  556. password: 'password',
  557. hostname: 'hostname',
  558. port: 'port'
  559. };
  560. generateAccessor = function(_part) {
  561. return function(v, build) {
  562. if (v === undefined) {
  563. return this._parts[_part] || "";
  564. } else {
  565. this._parts[_part] = v;
  566. this.build(!build);
  567. return this;
  568. }
  569. };
  570. };
  571. for (_part in _parts) {
  572. p[_part] = generateAccessor(_parts[_part]);
  573. }
  574. // generate accessors with optionally prefixed input
  575. _parts = {
  576. query: '?',
  577. fragment: '#'
  578. };
  579. generateAccessor = function(_part, _key) {
  580. return function(v, build) {
  581. if (v === undefined) {
  582. return this._parts[_part] || "";
  583. } else {
  584. if (v !== null) {
  585. v = v + "";
  586. if (v[0] === _key) {
  587. v = v.substring(1);
  588. }
  589. }
  590. this._parts[_part] = v;
  591. this.build(!build);
  592. return this;
  593. }
  594. };
  595. };
  596. for (_part in _parts) {
  597. p[_part] = generateAccessor(_part, _parts[_part]);
  598. }
  599. // generate accessors with prefixed output
  600. _parts = {
  601. search: ['?', 'query'],
  602. hash: ['#', 'fragment']
  603. };
  604. generateAccessor = function(_part, _key) {
  605. return function(v, build) {
  606. var t = this[_part](v, build);
  607. return typeof t === "string" && t.length ? (_key + t) : t;
  608. };
  609. };
  610. for (_part in _parts) {
  611. p[_part] = generateAccessor(_parts[_part][1], _parts[_part][0]);
  612. }
  613. p.pathname = function(v, build) {
  614. if (v === undefined || v === true) {
  615. var res = this._parts.path || (this._parts.urn ? '' : '/');
  616. return v ? URI.decodePath(res) : res;
  617. } else {
  618. this._parts.path = v ? URI.recodePath(v) : "/";
  619. this.build(!build);
  620. return this;
  621. }
  622. };
  623. p.path = p.pathname;
  624. p.href = function(href, build) {
  625. var key;
  626. if (href === undefined) {
  627. return this.toString();
  628. }
  629. this._string = "";
  630. this._parts = URI._parts();
  631. var _URI = href instanceof URI;
  632. var _object = typeof href === "object" && (href.hostname || href.path);
  633. // window.location is reported to be an object, but it's not the sort
  634. // of object we're looking for:
  635. // * location.protocol ends with a colon
  636. // * location.query != object.search
  637. // * location.hash != object.fragment
  638. // simply serializing the unknown object should do the trick
  639. // (for location, not for everything...)
  640. if (!_URI && _object && Object.prototype.toString.call(href) !== "[object Object]") {
  641. href = href.toString();
  642. }
  643. if (typeof href === "string") {
  644. this._parts = URI.parse(href, this._parts);
  645. } else if (_URI || _object) {
  646. var src = _URI ? href._parts : href;
  647. for (key in src) {
  648. if (hasOwn.call(this._parts, key)) {
  649. this._parts[key] = src[key];
  650. }
  651. }
  652. } else {
  653. throw new TypeError("invalid input");
  654. }
  655. this.build(!build);
  656. return this;
  657. };
  658. // identification accessors
  659. p.is = function(what) {
  660. var ip = false;
  661. var ip4 = false;
  662. var ip6 = false;
  663. var name = false;
  664. var sld = false;
  665. var idn = false;
  666. var punycode = false;
  667. var relative = !this._parts.urn;
  668. if (this._parts.hostname) {
  669. relative = false;
  670. ip4 = URI.ip4_expression.test(this._parts.hostname);
  671. ip6 = URI.ip6_expression.test(this._parts.hostname);
  672. ip = ip4 || ip6;
  673. name = !ip;
  674. sld = name && SLD && SLD.has(this._parts.hostname);
  675. idn = name && URI.idn_expression.test(this._parts.hostname);
  676. punycode = name && URI.punycode_expression.test(this._parts.hostname);
  677. }
  678. switch (what.toLowerCase()) {
  679. case 'relative':
  680. return relative;
  681. case 'absolute':
  682. return !relative;
  683. // hostname identification
  684. case 'domain':
  685. case 'name':
  686. return name;
  687. case 'sld':
  688. return sld;
  689. case 'ip':
  690. return ip;
  691. case 'ip4':
  692. case 'ipv4':
  693. case 'inet4':
  694. return ip4;
  695. case 'ip6':
  696. case 'ipv6':
  697. case 'inet6':
  698. return ip6;
  699. case 'idn':
  700. return idn;
  701. case 'url':
  702. return !this._parts.urn;
  703. case 'urn':
  704. return !!this._parts.urn;
  705. case 'punycode':
  706. return punycode;
  707. }
  708. return null;
  709. };
  710. // component specific input validation
  711. var _protocol = p.protocol;
  712. var _port = p.port;
  713. var _hostname = p.hostname;
  714. p.protocol = function(v, build) {
  715. if (v !== undefined) {
  716. if (v) {
  717. // accept trailing ://
  718. v = v.replace(/:(\/\/)?$/, '');
  719. if (v.match(/[^a-zA-z0-9\.+-]/)) {
  720. throw new TypeError("Protocol '" + v + "' contains characters other than [A-Z0-9.+-]");
  721. }
  722. }
  723. }
  724. return _protocol.call(this, v, build);
  725. };
  726. p.scheme = p.protocol;
  727. p.port = function(v, build) {
  728. if (this._parts.urn) {
  729. return v === undefined ? '' : this;
  730. }
  731. if (v !== undefined) {
  732. if (v === 0) {
  733. v = null;
  734. }
  735. if (v) {
  736. v += "";
  737. if (v[0] === ":") {
  738. v = v.substring(1);
  739. }
  740. if (v.match(/[^0-9]/)) {
  741. throw new TypeError("Port '" + v + "' contains characters other than [0-9]");
  742. }
  743. }
  744. }
  745. return _port.call(this, v, build);
  746. };
  747. p.hostname = function(v, build) {
  748. if (this._parts.urn) {
  749. return v === undefined ? '' : this;
  750. }
  751. if (v !== undefined) {
  752. var x = {};
  753. URI.parseHost(v, x);
  754. v = x.hostname;
  755. }
  756. return _hostname.call(this, v, build);
  757. };
  758. // compound accessors
  759. p.host = function(v, build) {
  760. if (this._parts.urn) {
  761. return v === undefined ? '' : this;
  762. }
  763. if (v === undefined) {
  764. return this._parts.hostname ? URI.buildHost(this._parts) : "";
  765. } else {
  766. URI.parseHost(v, this._parts);
  767. this.build(!build);
  768. return this;
  769. }
  770. };
  771. p.authority = function(v, build) {
  772. if (this._parts.urn) {
  773. return v === undefined ? '' : this;
  774. }
  775. if (v === undefined) {
  776. return this._parts.hostname ? URI.buildAuthority(this._parts) : "";
  777. } else {
  778. URI.parseAuthority(v, this._parts);
  779. this.build(!build);
  780. return this;
  781. }
  782. };
  783. p.userinfo = function(v, build) {
  784. if (this._parts.urn) {
  785. return v === undefined ? '' : this;
  786. }
  787. if (v === undefined) {
  788. if (!this._parts.username) {
  789. return "";
  790. }
  791. var t = URI.buildUserinfo(this._parts);
  792. return t.substring(0, t.length - 1);
  793. } else {
  794. if (v[v.length - 1] !== '@') {
  795. v += '@';
  796. }
  797. URI.parseUserinfo(v, this._parts);
  798. this.build(!build);
  799. return this;
  800. }
  801. };
  802. p.resource = function(v, build) {
  803. var parts;
  804. if (v === undefined) {
  805. return this.path() + this.search() + this.hash();
  806. }
  807. parts = URI.parse(v);
  808. this._parts.path = parts.path;
  809. this._parts.query = parts.query;
  810. this._parts.fragment = parts.fragment;
  811. this.build(!build);
  812. return this;
  813. };
  814. // fraction accessors
  815. p.subdomain = function(v, build) {
  816. if (this._parts.urn) {
  817. return v === undefined ? '' : this;
  818. }
  819. // convenience, return "www" from "www.example.org"
  820. if (v === undefined) {
  821. if (!this._parts.hostname || this.is('IP')) {
  822. return "";
  823. }
  824. // grab domain and add another segment
  825. var end = this._parts.hostname.length - this.domain().length - 1;
  826. return this._parts.hostname.substring(0, end) || "";
  827. } else {
  828. var e = this._parts.hostname.length - this.domain().length;
  829. var sub = this._parts.hostname.substring(0, e);
  830. var replace = new RegExp('^' + escapeRegEx(sub));
  831. if (v && v[v.length - 1] !== '.') {
  832. v += ".";
  833. }
  834. if (v) {
  835. URI.ensureValidHostname(v);
  836. }
  837. this._parts.hostname = this._parts.hostname.replace(replace, v);
  838. this.build(!build);
  839. return this;
  840. }
  841. };
  842. p.domain = function(v, build) {
  843. if (this._parts.urn) {
  844. return v === undefined ? '' : this;
  845. }
  846. if (typeof v === 'boolean') {
  847. build = v;
  848. v = undefined;
  849. }
  850. // convenience, return "example.org" from "www.example.org"
  851. if (v === undefined) {
  852. if (!this._parts.hostname || this.is('IP')) {
  853. return "";
  854. }
  855. // if hostname consists of 1 or 2 segments, it must be the domain
  856. var t = this._parts.hostname.match(/\./g);
  857. if (t && t.length < 2) {
  858. return this._parts.hostname;
  859. }
  860. // grab tld and add another segment
  861. var end = this._parts.hostname.length - this.tld(build).length - 1;
  862. end = this._parts.hostname.lastIndexOf('.', end - 1) + 1;
  863. return this._parts.hostname.substring(end) || "";
  864. } else {
  865. if (!v) {
  866. throw new TypeError("cannot set domain empty");
  867. }
  868. URI.ensureValidHostname(v);
  869. if (!this._parts.hostname || this.is('IP')) {
  870. this._parts.hostname = v;
  871. } else {
  872. var replace = new RegExp(escapeRegEx(this.domain()) + "$");
  873. this._parts.hostname = this._parts.hostname.replace(replace, v);
  874. }
  875. this.build(!build);
  876. return this;
  877. }
  878. };
  879. p.tld = function(v, build) {
  880. if (this._parts.urn) {
  881. return v === undefined ? '' : this;
  882. }
  883. if (typeof v === 'boolean') {
  884. build = v;
  885. v = undefined;
  886. }
  887. // return "org" from "www.example.org"
  888. if (v === undefined) {
  889. if (!this._parts.hostname || this.is('IP')) {
  890. return "";
  891. }
  892. var pos = this._parts.hostname.lastIndexOf('.');
  893. var tld = this._parts.hostname.substring(pos + 1);
  894. if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
  895. return SLD.get(this._parts.hostname) || tld;
  896. }
  897. return tld;
  898. } else {
  899. var replace;
  900. if (!v) {
  901. throw new TypeError("cannot set TLD empty");
  902. } else if (v.match(/[^a-zA-Z0-9-]/)) {
  903. if (SLD && SLD.is(v)) {
  904. replace = new RegExp(escapeRegEx(this.tld()) + "$");
  905. this._parts.hostname = this._parts.hostname.replace(replace, v);
  906. } else {
  907. throw new TypeError("TLD '" + v + "' contains characters other than [A-Z0-9]");
  908. }
  909. } else if (!this._parts.hostname || this.is('IP')) {
  910. throw new ReferenceError("cannot set TLD on non-domain host");
  911. } else {
  912. replace = new RegExp(escapeRegEx(this.tld()) + "$");
  913. this._parts.hostname = this._parts.hostname.replace(replace, v);
  914. }
  915. this.build(!build);
  916. return this;
  917. }
  918. };
  919. p.directory = function(v, build) {
  920. if (this._parts.urn) {
  921. return v === undefined ? '' : this;
  922. }
  923. if (v === undefined || v === true) {
  924. if (!this._parts.path && !this._parts.hostname) {
  925. return '';
  926. }
  927. if (this._parts.path === '/') {
  928. return '/';
  929. }
  930. var end = this._parts.path.length - this.filename().length - 1;
  931. var res = this._parts.path.substring(0, end) || (this._parts.hostname ? "/" : "");
  932. return v ? URI.decodePath(res) : res;
  933. } else {
  934. var e = this._parts.path.length - this.filename().length;
  935. var directory = this._parts.path.substring(0, e);
  936. var replace = new RegExp('^' + escapeRegEx(directory));
  937. // fully qualifier directories begin with a slash
  938. if (!this.is('relative')) {
  939. if (!v) {
  940. v = '/';
  941. }
  942. if (v[0] !== '/') {
  943. v = "/" + v;
  944. }
  945. }
  946. // directories always end with a slash
  947. if (v && v[v.length - 1] !== '/') {
  948. v += '/';
  949. }
  950. v = URI.recodePath(v);
  951. this._parts.path = this._parts.path.replace(replace, v);
  952. this.build(!build);
  953. return this;
  954. }
  955. };
  956. p.filename = function(v, build) {
  957. if (this._parts.urn) {
  958. return v === undefined ? '' : this;
  959. }
  960. if (v === undefined || v === true) {
  961. if (!this._parts.path || this._parts.path === '/') {
  962. return "";
  963. }
  964. var pos = this._parts.path.lastIndexOf('/');
  965. var res = this._parts.path.substring(pos + 1);
  966. return v ? URI.decodePathSegment(res) : res;
  967. } else {
  968. var mutatedDirectory = false;
  969. if (v[0] === '/') {
  970. v = v.substring(1);
  971. }
  972. if (v.match(/\.?\//)) {
  973. mutatedDirectory = true;
  974. }
  975. var replace = new RegExp(escapeRegEx(this.filename()) + "$");
  976. v = URI.recodePath(v);
  977. this._parts.path = this._parts.path.replace(replace, v);
  978. if (mutatedDirectory) {
  979. this.normalizePath(build);
  980. } else {
  981. this.build(!build);
  982. }
  983. return this;
  984. }
  985. };
  986. p.suffix = function(v, build) {
  987. if (this._parts.urn) {
  988. return v === undefined ? '' : this;
  989. }
  990. if (v === undefined || v === true) {
  991. if (!this._parts.path || this._parts.path === '/') {
  992. return "";
  993. }
  994. var filename = this.filename();
  995. var pos = filename.lastIndexOf('.');
  996. var s, res;
  997. if (pos === -1) {
  998. return "";
  999. }
  1000. // suffix may only contain alnum characters (yup, I made this up.)
  1001. s = filename.substring(pos + 1);
  1002. res = (/^[a-z0-9%]+$/i).test(s) ? s : "";
  1003. return v ? URI.decodePathSegment(res) : res;
  1004. } else {
  1005. if (v[0] === '.') {
  1006. v = v.substring(1);
  1007. }
  1008. var suffix = this.suffix();
  1009. var replace;
  1010. if (!suffix) {
  1011. if (!v) {
  1012. return this;
  1013. }
  1014. this._parts.path += '.' + URI.recodePath(v);
  1015. } else if (!v) {
  1016. replace = new RegExp(escapeRegEx("." + suffix) + "$");
  1017. } else {
  1018. replace = new RegExp(escapeRegEx(suffix) + "$");
  1019. }
  1020. if (replace) {
  1021. v = URI.recodePath(v);
  1022. this._parts.path = this._parts.path.replace(replace, v);
  1023. }
  1024. this.build(!build);
  1025. return this;
  1026. }
  1027. };
  1028. p.segment = function(segment, v, build) {
  1029. var separator = this._parts.urn ? ':' : '/';
  1030. var path = this.path();
  1031. var absolute = path.substring(0, 1) === '/';
  1032. var segments = path.split(separator);
  1033. if (typeof segment !== 'number') {
  1034. build = v;
  1035. v = segment;
  1036. segment = undefined;
  1037. }
  1038. if (segment !== undefined && typeof segment !== 'number') {
  1039. throw new Error("Bad segment '" + segment + "', must be 0-based integer");
  1040. }
  1041. if (absolute) {
  1042. segments.shift();
  1043. }
  1044. if (segment < 0) {
  1045. // allow negative indexes to address from the end
  1046. segment = Math.max(segments.length + segment, 0);
  1047. }
  1048. if (v === undefined) {
  1049. return segment === undefined ? segments : segments[segment];
  1050. } else if (segment === null || segments[segment] === undefined) {
  1051. if (isArray(v)) {
  1052. segments = v;
  1053. } else if (v || (typeof v === "string" && v.length)) {
  1054. if (segments[segments.length - 1] === "") {
  1055. // empty trailing elements have to be overwritten
  1056. // to prefent results such as /foo//bar
  1057. segments[segments.length - 1] = v;
  1058. } else {
  1059. segments.push(v);
  1060. }
  1061. }
  1062. } else {
  1063. if (v || (typeof v === "string" && v.length)) {
  1064. segments[segment] = v;
  1065. } else {
  1066. segments.splice(segment, 1);
  1067. }
  1068. }
  1069. if (absolute) {
  1070. segments.unshift("");
  1071. }
  1072. return this.path(segments.join(separator), build);
  1073. };
  1074. // mutating query string
  1075. var q = p.query;
  1076. p.query = function(v, build) {
  1077. if (v === true) {
  1078. return URI.parseQuery(this._parts.query);
  1079. } else if (v !== undefined && typeof v !== "string") {
  1080. this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters);
  1081. this.build(!build);
  1082. return this;
  1083. } else {
  1084. return q.call(this, v, build);
  1085. }
  1086. };
  1087. p.addQuery = function(name, value, build) {
  1088. var data = URI.parseQuery(this._parts.query);
  1089. URI.addQuery(data, name, value === undefined ? null : value);
  1090. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters);
  1091. if (typeof name !== "string") {
  1092. build = value;
  1093. }
  1094. this.build(!build);
  1095. return this;
  1096. };
  1097. p.removeQuery = function(name, value, build) {
  1098. var data = URI.parseQuery(this._parts.query);
  1099. URI.removeQuery(data, name, value);
  1100. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters);
  1101. if (typeof name !== "string") {
  1102. build = value;
  1103. }
  1104. this.build(!build);
  1105. return this;
  1106. };
  1107. p.addSearch = p.addQuery;
  1108. p.removeSearch = p.removeQuery;
  1109. // sanitizing URLs
  1110. p.normalize = function() {
  1111. if (this._parts.urn) {
  1112. return this.normalizeProtocol(false).normalizeQuery(false).normalizeFragment(false).build();
  1113. }
  1114. return this.normalizeProtocol(false).normalizeHostname(false).normalizePort(false).normalizePath(false).normalizeQuery(false).normalizeFragment(false).build();
  1115. };
  1116. p.normalizeProtocol = function(build) {
  1117. if (typeof this._parts.protocol === "string") {
  1118. this._parts.protocol = this._parts.protocol.toLowerCase();
  1119. this.build(!build);
  1120. }
  1121. return this;
  1122. };
  1123. p.normalizeHostname = function(build) {
  1124. if (this._parts.hostname) {
  1125. if (this.is('IDN') && punycode) {
  1126. this._parts.hostname = punycode.toASCII(this._parts.hostname);
  1127. } else if (this.is('IPv6') && IPv6) {
  1128. this._parts.hostname = IPv6.best(this._parts.hostname);
  1129. }
  1130. this._parts.hostname = this._parts.hostname.toLowerCase();
  1131. this.build(!build);
  1132. }
  1133. return this;
  1134. };
  1135. p.normalizePort = function(build) {
  1136. // remove port of it's the protocol's default
  1137. if (typeof this._parts.protocol === "string" && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
  1138. this._parts.port = null;
  1139. this.build(!build);
  1140. }
  1141. return this;
  1142. };
  1143. p.normalizePath = function(build) {
  1144. if (this._parts.urn) {
  1145. return this;
  1146. }
  1147. if (!this._parts.path || this._parts.path === '/') {
  1148. return this;
  1149. }
  1150. var _was_relative;
  1151. var _was_relative_prefix;
  1152. var _path = this._parts.path;
  1153. var _parent, _pos;
  1154. // handle relative paths
  1155. if (_path[0] !== '/') {
  1156. if (_path[0] === '.') {
  1157. _was_relative_prefix = _path.substring(0, _path.indexOf('/'));
  1158. }
  1159. _was_relative = true;
  1160. _path = '/' + _path;
  1161. }
  1162. // resolve simples
  1163. _path = _path.replace(/(\/(\.\/)+)|\/{2,}/g, '/');
  1164. // resolve parents
  1165. while (true) {
  1166. _parent = _path.indexOf('/../');
  1167. if (_parent === -1) {
  1168. // no more ../ to resolve
  1169. break;
  1170. } else if (_parent === 0) {
  1171. // top level cannot be relative...
  1172. _path = _path.substring(3);
  1173. break;
  1174. }
  1175. _pos = _path.substring(0, _parent).lastIndexOf('/');
  1176. if (_pos === -1) {
  1177. _pos = _parent;
  1178. }
  1179. _path = _path.substring(0, _pos) + _path.substring(_parent + 3);
  1180. }
  1181. // revert to relative
  1182. if (_was_relative && this.is('relative')) {
  1183. if (_was_relative_prefix) {
  1184. _path = _was_relative_prefix + _path;
  1185. } else {
  1186. _path = _path.substring(1);
  1187. }
  1188. }
  1189. _path = URI.recodePath(_path);
  1190. this._parts.path = _path;
  1191. this.build(!build);
  1192. return this;
  1193. };
  1194. p.normalizePathname = p.normalizePath;
  1195. p.normalizeQuery = function(build) {
  1196. if (typeof this._parts.query === "string") {
  1197. if (!this._parts.query.length) {
  1198. this._parts.query = null;
  1199. } else {
  1200. this.query(URI.parseQuery(this._parts.query));
  1201. }
  1202. this.build(!build);
  1203. }
  1204. return this;
  1205. };
  1206. p.normalizeFragment = function(build) {
  1207. if (!this._parts.fragment) {
  1208. this._parts.fragment = null;
  1209. this.build(!build);
  1210. }
  1211. return this;
  1212. };
  1213. p.normalizeSearch = p.normalizeQuery;
  1214. p.normalizeHash = p.normalizeFragment;
  1215. p.iso8859 = function() {
  1216. // expect unicode input, iso8859 output
  1217. var e = URI.encode;
  1218. var d = URI.decode;
  1219. URI.encode = escape;
  1220. URI.decode = decodeURIComponent;
  1221. this.normalize();
  1222. URI.encode = e;
  1223. URI.decode = d;
  1224. return this;
  1225. };
  1226. p.unicode = function() {
  1227. // expect iso8859 input, unicode output
  1228. var e = URI.encode;
  1229. var d = URI.decode;
  1230. URI.encode = strictEncodeURIComponent;
  1231. URI.decode = unescape;
  1232. this.normalize();
  1233. URI.encode = e;
  1234. URI.decode = d;
  1235. return this;
  1236. };
  1237. p.readable = function() {
  1238. var uri = this.clone();
  1239. // removing username, password, because they shouldn't be displayed according to RFC 3986
  1240. uri.username("").password("").normalize();
  1241. var t = '';
  1242. if (uri._parts.protocol) {
  1243. t += uri._parts.protocol + '://';
  1244. }
  1245. if (uri._parts.hostname) {
  1246. if (uri.is('punycode') && punycode) {
  1247. t += punycode.toUnicode(uri._parts.hostname);
  1248. if (uri._parts.port) {
  1249. t += ":" + uri._parts.port;
  1250. }
  1251. } else {
  1252. t += uri.host();
  1253. }
  1254. }
  1255. if (uri._parts.hostname && uri._parts.path && uri._parts.path[0] !== '/') {
  1256. t += '/';
  1257. }
  1258. t += uri.path(true);
  1259. if (uri._parts.query) {
  1260. var q = '';
  1261. for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
  1262. var kv = (qp[i] || "").split('=');
  1263. q += '&' + URI.decodeQuery(kv[0]).replace(/&/g, '%26');
  1264. if (kv[1] !== undefined) {
  1265. q += "=" + URI.decodeQuery(kv[1]).replace(/&/g, '%26');
  1266. }
  1267. }
  1268. t += '?' + q.substring(1);
  1269. }
  1270. t += uri.hash();
  1271. return t;
  1272. };
  1273. // resolving relative and absolute URLs
  1274. p.absoluteTo = function(base) {
  1275. var resolved = this.clone();
  1276. var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
  1277. var basedir, i, p;
  1278. if (this._parts.urn) {
  1279. throw new Error('URNs do not have any generally defined hierachical components');
  1280. }
  1281. if (this._parts.hostname) {
  1282. return resolved;
  1283. }
  1284. if (!(base instanceof URI)) {
  1285. base = new URI(base);
  1286. }
  1287. for (i = 0, p; p = properties[i]; i++) {
  1288. resolved._parts[p] = base._parts[p];
  1289. }
  1290. properties = ['query', 'path'];
  1291. for (i = 0, p; p = properties[i]; i++) {
  1292. if (!resolved._parts[p] && base._parts[p]) {
  1293. resolved._parts[p] = base._parts[p];
  1294. }
  1295. }
  1296. if (resolved.path()[0] !== '/') {
  1297. basedir = base.directory();
  1298. resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
  1299. resolved.normalizePath();
  1300. }
  1301. resolved.build();
  1302. return resolved;
  1303. };
  1304. p.relativeTo = function(base) {
  1305. var relative = this.clone();
  1306. var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
  1307. var common, _base, _this, _base_diff, _this_diff;
  1308. if (this._parts.urn) {
  1309. throw new Error('URNs do not have any generally defined hierachical components');
  1310. }
  1311. if (!(base instanceof URI)) {
  1312. base = new URI(base);
  1313. }
  1314. if (this.path()[0] !== '/' || base.path()[0] !== '/') {
  1315. throw new Error('Cannot calculate common path from non-relative URLs');
  1316. }
  1317. // determine common sub path
  1318. common = URI.commonPath(relative.path(), base.path());
  1319. // no relation if there's nothing in common
  1320. if (!common || common === '/') {
  1321. return relative;
  1322. }
  1323. // relative paths don't have authority
  1324. for (var i = 0, p; p = properties[i]; i++) {
  1325. relative._parts[p] = null;
  1326. }
  1327. _base = base.directory();
  1328. _this = this.directory();
  1329. // base and this are on the same level
  1330. if (_base === _this) {
  1331. relative._parts.path = './' + relative.filename();
  1332. return relative.build();
  1333. }
  1334. _base_diff = _base.substring(common.length);
  1335. _this_diff = _this.substring(common.length);
  1336. // this is a descendant of base
  1337. if (_base + '/' === common) {
  1338. if (_this_diff) {
  1339. _this_diff += '/';
  1340. }
  1341. relative._parts.path = './' + _this_diff + relative.filename();
  1342. return relative.build();
  1343. }
  1344. // this is a descendant of base
  1345. var parents = '../';
  1346. var _common = new RegExp('^' + escapeRegEx(common));
  1347. var _parents = _base.replace(_common, '/').match(/\//g).length - 1;
  1348. while (_parents--) {
  1349. parents += '../';
  1350. }
  1351. relative._parts.path = relative._parts.path.replace(_common, parents);
  1352. return relative.build();
  1353. };
  1354. // comparing URIs
  1355. p.equals = function(uri) {
  1356. var one = this.clone();
  1357. var two = new URI(uri);
  1358. var one_map = {};
  1359. var two_map = {};
  1360. var checked = {};
  1361. var one_query, two_query, key;
  1362. one.normalize();
  1363. two.normalize();
  1364. // exact match
  1365. if (one.toString() === two.toString()) {
  1366. return true;
  1367. }
  1368. // extract query string
  1369. one_query = one.query();
  1370. two_query = two.query();
  1371. one.query("");
  1372. two.query("");
  1373. // definitely not equal if not even non-query parts match
  1374. if (one.toString() !== two.toString()) {
  1375. return false;
  1376. }
  1377. // query parameters have the same length, even if they're permutated
  1378. if (one_query.length !== two_query.length) {
  1379. return false;
  1380. }
  1381. one_map = URI.parseQuery(one_query);
  1382. two_map = URI.parseQuery(two_query);
  1383. for (key in one_map) {
  1384. if (hasOwn.call(one_map, key)) {
  1385. if (!isArray(one_map[key])) {
  1386. if (one_map[key] !== two_map[key]) {
  1387. return false;
  1388. }
  1389. } else {
  1390. if (!isArray(two_map[key])) {
  1391. return false;
  1392. }
  1393. // arrays can't be equal if they have different amount of content
  1394. if (one_map[key].length !== two_map[key].length) {
  1395. return false;
  1396. }
  1397. one_map[key].sort();
  1398. two_map[key].sort();
  1399. for (var i = 0, l = one_map[key].length; i < l; i++) {
  1400. if (one_map[key][i] !== two_map[key][i]) {
  1401. return false;
  1402. }
  1403. }
  1404. }
  1405. checked[key] = true;
  1406. }
  1407. }
  1408. for (key in two_map) {
  1409. if (hasOwn.call(two_map, key)) {
  1410. if (!checked[key]) {
  1411. // two contains a parameter not present in one
  1412. return false;
  1413. }
  1414. }
  1415. }
  1416. return true;
  1417. };
  1418. // state
  1419. p.duplicateQueryParameters = function(v) {
  1420. this._parts.duplicateQueryParameters = !! v;
  1421. return this;
  1422. };
  1423. return URI;
  1424. }));