summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint-plugin-markdown/node_modules/micromark/lib/util/normalize-uri.mjs
blob: 3102243354dab532d01e1658bee38322a333775d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
export default normalizeUri

import asciiAlphanumeric from '../character/ascii-alphanumeric.mjs'
import codes from '../character/codes.mjs'
import values from '../character/values.mjs'
import fromCharCode from '../constant/from-char-code.mjs'

// Encode unsafe characters with percent-encoding, skipping already
// encoded sequences.
function normalizeUri(value) {
  var index = -1
  var result = []
  var start = 0
  var skip = 0
  var code
  var next
  var replace

  while (++index < value.length) {
    code = value.charCodeAt(index)

    // A correct percent encoded value.
    if (
      code === codes.percentSign &&
      asciiAlphanumeric(value.charCodeAt(index + 1)) &&
      asciiAlphanumeric(value.charCodeAt(index + 2))
    ) {
      skip = 2
    }
    // ASCII.
    else if (code < 128) {
      if (!/[!#$&-;=?-Z_a-z~]/.test(fromCharCode(code))) {
        replace = fromCharCode(code)
      }
    }
    // Astral.
    else if (code > 55295 && code < 57344) {
      next = value.charCodeAt(index + 1)

      // A correct surrogate pair.
      if (code < 56320 && next > 56319 && next < 57344) {
        replace = fromCharCode(code, next)
        skip = 1
      }
      // Lone surrogate.
      else {
        replace = values.replacementCharacter
      }
    }
    // Unicode.
    else {
      replace = fromCharCode(code)
    }

    if (replace) {
      result.push(value.slice(start, index), encodeURIComponent(replace))
      start = index + skip + 1
      replace = undefined
    }

    if (skip) {
      index += skip
      skip = 0
    }
  }

  return result.join('') + value.slice(start)
}