Skip to content

Commit

Permalink
feat: handle punycode URLs (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Feb 14, 2024
1 parent 57cc236 commit b0bde42
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
10 changes: 6 additions & 4 deletions index.js
@@ -1,18 +1,20 @@
'use strict'

const punycodeRegex = require('punycode-regex')()
const urlRegex = require('url-regex-safe')

const REGEX_HTTP_PROTOCOL = /^https?:\/\//i

module.exports = url => {
try {
const { href, hostname } = new URL(url)
if (!REGEX_HTTP_PROTOCOL.test(href)) return false
const isIPv6 = hostname.startsWith('[') && hostname.endsWith(']')
const isPunycode = punycodeRegex.test(hostname)
const exact = !isIPv6 && !isPunycode
const tlds = isPunycode ? [] : undefined
return (
REGEX_HTTP_PROTOCOL.test(href) &&
urlRegex({ apostrophes: true, exact: !isIPv6, parens: true }).test(
href
) &&
urlRegex({ apostrophes: true, exact, parens: true, tlds }).test(href) &&
href
)
} catch (_) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -34,6 +34,7 @@
"whatwg"
],
"dependencies": {
"punycode-regex": "~1.0.1",
"re2": "~1.20.1",
"url-regex-safe": "~4.0.0"
},
Expand Down
6 changes: 5 additions & 1 deletion test/index.js
Expand Up @@ -17,7 +17,10 @@ const test = require('ava')
'https://kikobeats.com',
'https://www.kikobeats.com',
'https://en.wikipedia.org/wiki/Saw_(disambiguation)',
'http://www.kikobeats.com'
'http://www.kikobeats.com',
'https://example.xn--p1ai',
'https://xn--80a0aaa.com',
'https://xn--80a0aaa.xn--p1ai'
].forEach(input => {
const url = httpUrl(input)
t.is(typeof url, 'string', `'${input}' is not true`)
Expand All @@ -42,6 +45,7 @@ const test = require('ava')
;(isLightweight
? urls
: urls.concat([
'http://Http://xn--80a0aaa.xn--p1ai',
'http://Http://kikobeats.com',
'https://admin:admin@test-http-login.vercel.app',
'http:!!!\0',
Expand Down

0 comments on commit b0bde42

Please sign in to comment.