Skip to content

Commit

Permalink
feat: handle punycode URLs
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Feb 14, 2024
1 parent 00be750 commit 36d0dfb
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 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
9 changes: 5 additions & 4 deletions package.json
Expand Up @@ -5,6 +5,10 @@
"version": "1.1.3",
"types": "src/index.d.ts",
"browser": "lightweight.js",
"exports": {
".": "./index.js",
"./lightweight": "./lightweight.js"
},
"author": {
"email": "josefrancisco.verdu@gmail.com",
"name": "Kiko Beats",
Expand All @@ -30,6 +34,7 @@
"whatwg"
],
"dependencies": {
"punycode-regex": "~1.0.1",
"re2": "~1.20.1",
"url-regex-safe": "~4.0.0"
},
Expand Down Expand Up @@ -79,10 +84,6 @@
"@commitlint/config-conventional"
]
},
"exports": {
".": "./index.js",
"./lightweight": "./lightweight.js"
},
"nano-staged": {
"*.js": [
"prettier-standard",
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 36d0dfb

Please sign in to comment.