This repository has been archived by the owner on Jul 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
84 lines (67 loc) · 2.05 KB
/
index.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const punycode = require('punycode')
const sldMap = require('./data/sldMap.json')
const ccTldMap = require('./data/ccTldMap.json')
module.exports = function isValidDomain (value, opts) {
if (typeof value !== 'string') return false
if (!(opts instanceof Object)) opts = {}
value = value.toLowerCase()
if (value.endsWith('.')) {
value = value.slice(0, value.length - 1)
}
if (opts.allowUnicode) {
value = punycode.toASCII(value)
}
if (value.length > 253) {
return false
}
const validChars = /^([\u0E00-\u0E7Fa-z0-9-._*]+)$/g
if (!validChars.test(value)) {
return false
}
if (opts.topLevel) {
if (ccTldMap[value.replace(/\.$/, '')]) {
return true
}
}
const sldRegex = /(.*)\.(([\u0E00-\u0E7Fa-z0-9]+)(\.[a-z0-9]+))/
const matches = value.match(sldRegex)
let tld = null
let labels = null
if (matches && matches.length > 2) {
if (sldMap[matches[2]]) {
tld = matches[2]
labels = matches[1].split('.')
}
}
if (!labels) {
labels = value.split('.')
if (labels.length <= 1) return false
tld = labels.pop()
const tldRegex = /^(?:xn--)?(?!^\d+$)[\u0E00-\u0E7Fa-z0-9]+$/gi
if (!tldRegex.test(tld)) return false
}
if (opts.subdomain === false && labels.length > 1) return false
const isValid = labels.every(function (label, index) {
if (opts.wildcard && index === 0 && label === '*' && labels.length > 1) {
return true
}
let validLabelChars = /^([\u0E00-\u0E7Fa-zA-Z0-9-_]+)$/g
if (index === labels.length - 1) {
validLabelChars = /^([\u0E00-\u0E7Fa-zA-Z0-9-]+)$/g
}
// https://github.com/miguelmota/is-valid-domain/issues/22
const doubleDashCount = (label.match(/--(--)?/g) || []).length
const xnDashCount = (label.match(/xn--/g) || []).length
if (index === labels.length - 1 && doubleDashCount !== xnDashCount) {
return false
}
const isValid = (
validLabelChars.test(label) &&
label.length < 64 &&
!label.startsWith('-') &&
!label.endsWith('-')
)
return isValid
})
return isValid
}