index.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. 'use strict'
  2. const { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = require('./lib/utils')
  3. const SCHEMES = require('./lib/schemes')
  4. function normalize (uri, options) {
  5. if (typeof uri === 'string') {
  6. uri = serialize(parse(uri, options), options)
  7. } else if (typeof uri === 'object') {
  8. uri = parse(serialize(uri, options), options)
  9. }
  10. return uri
  11. }
  12. function resolve (baseURI, relativeURI, options) {
  13. const schemelessOptions = Object.assign({ scheme: 'null' }, options)
  14. const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)
  15. return serialize(resolved, { ...schemelessOptions, skipEscape: true })
  16. }
  17. function resolveComponents (base, relative, options, skipNormalization) {
  18. const target = {}
  19. if (!skipNormalization) {
  20. base = parse(serialize(base, options), options) // normalize base components
  21. relative = parse(serialize(relative, options), options) // normalize relative components
  22. }
  23. options = options || {}
  24. if (!options.tolerant && relative.scheme) {
  25. target.scheme = relative.scheme
  26. // target.authority = relative.authority;
  27. target.userinfo = relative.userinfo
  28. target.host = relative.host
  29. target.port = relative.port
  30. target.path = removeDotSegments(relative.path || '')
  31. target.query = relative.query
  32. } else {
  33. if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
  34. // target.authority = relative.authority;
  35. target.userinfo = relative.userinfo
  36. target.host = relative.host
  37. target.port = relative.port
  38. target.path = removeDotSegments(relative.path || '')
  39. target.query = relative.query
  40. } else {
  41. if (!relative.path) {
  42. target.path = base.path
  43. if (relative.query !== undefined) {
  44. target.query = relative.query
  45. } else {
  46. target.query = base.query
  47. }
  48. } else {
  49. if (relative.path.charAt(0) === '/') {
  50. target.path = removeDotSegments(relative.path)
  51. } else {
  52. if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
  53. target.path = '/' + relative.path
  54. } else if (!base.path) {
  55. target.path = relative.path
  56. } else {
  57. target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path
  58. }
  59. target.path = removeDotSegments(target.path)
  60. }
  61. target.query = relative.query
  62. }
  63. // target.authority = base.authority;
  64. target.userinfo = base.userinfo
  65. target.host = base.host
  66. target.port = base.port
  67. }
  68. target.scheme = base.scheme
  69. }
  70. target.fragment = relative.fragment
  71. return target
  72. }
  73. function equal (uriA, uriB, options) {
  74. if (typeof uriA === 'string') {
  75. uriA = unescape(uriA)
  76. uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true })
  77. } else if (typeof uriA === 'object') {
  78. uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true })
  79. }
  80. if (typeof uriB === 'string') {
  81. uriB = unescape(uriB)
  82. uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true })
  83. } else if (typeof uriB === 'object') {
  84. uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true })
  85. }
  86. return uriA.toLowerCase() === uriB.toLowerCase()
  87. }
  88. function serialize (cmpts, opts) {
  89. const components = {
  90. host: cmpts.host,
  91. scheme: cmpts.scheme,
  92. userinfo: cmpts.userinfo,
  93. port: cmpts.port,
  94. path: cmpts.path,
  95. query: cmpts.query,
  96. nid: cmpts.nid,
  97. nss: cmpts.nss,
  98. uuid: cmpts.uuid,
  99. fragment: cmpts.fragment,
  100. reference: cmpts.reference,
  101. resourceName: cmpts.resourceName,
  102. secure: cmpts.secure,
  103. error: ''
  104. }
  105. const options = Object.assign({}, opts)
  106. const uriTokens = []
  107. // find scheme handler
  108. const schemeHandler = SCHEMES[(options.scheme || components.scheme || '').toLowerCase()]
  109. // perform scheme specific serialization
  110. if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options)
  111. if (components.path !== undefined) {
  112. if (!options.skipEscape) {
  113. components.path = escape(components.path)
  114. if (components.scheme !== undefined) {
  115. components.path = components.path.split('%3A').join(':')
  116. }
  117. } else {
  118. components.path = unescape(components.path)
  119. }
  120. }
  121. if (options.reference !== 'suffix' && components.scheme) {
  122. uriTokens.push(components.scheme)
  123. uriTokens.push(':')
  124. }
  125. const authority = recomposeAuthority(components, options)
  126. if (authority !== undefined) {
  127. if (options.reference !== 'suffix') {
  128. uriTokens.push('//')
  129. }
  130. uriTokens.push(authority)
  131. if (components.path && components.path.charAt(0) !== '/') {
  132. uriTokens.push('/')
  133. }
  134. }
  135. if (components.path !== undefined) {
  136. let s = components.path
  137. if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
  138. s = removeDotSegments(s)
  139. }
  140. if (authority === undefined) {
  141. s = s.replace(/^\/\//u, '/%2F') // don't allow the path to start with "//"
  142. }
  143. uriTokens.push(s)
  144. }
  145. if (components.query !== undefined) {
  146. uriTokens.push('?')
  147. uriTokens.push(components.query)
  148. }
  149. if (components.fragment !== undefined) {
  150. uriTokens.push('#')
  151. uriTokens.push(components.fragment)
  152. }
  153. return uriTokens.join('')
  154. }
  155. const hexLookUp = Array.from({ length: 127 }, (v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k)))
  156. function nonSimpleDomain (value) {
  157. let code = 0
  158. for (let i = 0, len = value.length; i < len; ++i) {
  159. code = value.charCodeAt(i)
  160. if (code > 126 || hexLookUp[code]) {
  161. return true
  162. }
  163. }
  164. return false
  165. }
  166. const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u
  167. function parse (uri, opts) {
  168. const options = Object.assign({}, opts)
  169. const parsed = {
  170. scheme: undefined,
  171. userinfo: undefined,
  172. host: '',
  173. port: undefined,
  174. path: '',
  175. query: undefined,
  176. fragment: undefined
  177. }
  178. const gotEncoding = uri.indexOf('%') !== -1
  179. let isIP = false
  180. if (options.reference === 'suffix') uri = (options.scheme ? options.scheme + ':' : '') + '//' + uri
  181. const matches = uri.match(URI_PARSE)
  182. if (matches) {
  183. // store each component
  184. parsed.scheme = matches[1]
  185. parsed.userinfo = matches[3]
  186. parsed.host = matches[4]
  187. parsed.port = parseInt(matches[5], 10)
  188. parsed.path = matches[6] || ''
  189. parsed.query = matches[7]
  190. parsed.fragment = matches[8]
  191. // fix port number
  192. if (isNaN(parsed.port)) {
  193. parsed.port = matches[5]
  194. }
  195. if (parsed.host) {
  196. const ipv4result = normalizeIPv4(parsed.host)
  197. if (ipv4result.isIPV4 === false) {
  198. const ipv6result = normalizeIPv6(ipv4result.host, { isIPV4: false })
  199. parsed.host = ipv6result.host.toLowerCase()
  200. isIP = ipv6result.isIPV6
  201. } else {
  202. parsed.host = ipv4result.host
  203. isIP = true
  204. }
  205. }
  206. if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && !parsed.path && parsed.query === undefined) {
  207. parsed.reference = 'same-document'
  208. } else if (parsed.scheme === undefined) {
  209. parsed.reference = 'relative'
  210. } else if (parsed.fragment === undefined) {
  211. parsed.reference = 'absolute'
  212. } else {
  213. parsed.reference = 'uri'
  214. }
  215. // check for reference errors
  216. if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
  217. parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'
  218. }
  219. // find scheme handler
  220. const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || '').toLowerCase()]
  221. // check if scheme can't handle IRIs
  222. if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
  223. // if host component is a domain name
  224. if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {
  225. // convert Unicode IDN -> ASCII IDN
  226. try {
  227. parsed.host = URL.domainToASCII(parsed.host.toLowerCase())
  228. } catch (e) {
  229. parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e
  230. }
  231. }
  232. // convert IRI -> URI
  233. }
  234. if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
  235. if (gotEncoding && parsed.scheme !== undefined) {
  236. parsed.scheme = unescape(parsed.scheme)
  237. }
  238. if (gotEncoding && parsed.userinfo !== undefined) {
  239. parsed.userinfo = unescape(parsed.userinfo)
  240. }
  241. if (gotEncoding && parsed.host !== undefined) {
  242. parsed.host = unescape(parsed.host)
  243. }
  244. if (parsed.path !== undefined && parsed.path.length) {
  245. parsed.path = escape(unescape(parsed.path))
  246. }
  247. if (parsed.fragment !== undefined && parsed.fragment.length) {
  248. parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))
  249. }
  250. }
  251. // perform scheme specific parsing
  252. if (schemeHandler && schemeHandler.parse) {
  253. schemeHandler.parse(parsed, options)
  254. }
  255. } else {
  256. parsed.error = parsed.error || 'URI can not be parsed.'
  257. }
  258. return parsed
  259. }
  260. const fastUri = {
  261. SCHEMES,
  262. normalize,
  263. resolve,
  264. resolveComponents,
  265. equal,
  266. serialize,
  267. parse
  268. }
  269. module.exports = fastUri
  270. module.exports.default = fastUri
  271. module.exports.fastUri = fastUri