Skip to content

Commit b32d16c

Browse files
committed
fix: Add support for invalid ipv6 URLs
Closes #114
1 parent 4ea86a1 commit b32d16c

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/from-url.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,15 @@ describe(fromUrl.name, () => {
5757
expect(fromUrl("[1:2:3:4:5:6:7:8]")).toBe("[1:2:3:4:5:6:7:8]");
5858
});
5959

60+
// https://github.com/peerigon/parse-domain/issues/114
61+
test("it handles URLs with invalid IPv6", () => {
62+
expect(fromUrl("http://1:2:3:4:5:6:7:8/path?query")).toBe(
63+
"[1:2:3:4:5:6:7:8]"
64+
);
65+
expect(fromUrl("//1:2:3:4:5:6:7:8")).toBe("[1:2:3:4:5:6:7:8]");
66+
expect(fromUrl("1:2:3:4:5:6:7:8")).toBe("[1:2:3:4:5:6:7:8]");
67+
});
68+
6069
test("it returns the NO_HOSTNAME symbol for invalid URLs", () => {
6170
expect(fromUrl(":8080/path?query")).toBe(NO_HOSTNAME);
6271
expect(fromUrl("/path?query")).toBe(NO_HOSTNAME);

src/from-url.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const urlPattern = /^[a-z][*+.a-z-]+:\/\//i;
2+
const invalidIpv6Pattern = /^([a-z][*+.a-z-]+:\/\/)([^[].*:[^/?]*:[^/?]*)(.*)/i;
23

34
export const NO_HOSTNAME: unique symbol = Symbol("NO_HOSTNAME");
45

@@ -16,7 +17,7 @@ export const fromUrl = (urlLike: string) => {
1617
}
1718

1819
// URLs that start with // are protocol relative
19-
const url = urlLike.startsWith("//")
20+
let url = urlLike.startsWith("//")
2021
? `http:${urlLike}`
2122
: // URLs that start with / do not have a hostname section
2223
urlLike.startsWith("/")
@@ -25,6 +26,8 @@ export const fromUrl = (urlLike: string) => {
2526
? urlLike
2627
: `http://${urlLike}`;
2728

29+
url = url.replace(invalidIpv6Pattern, "$1[$2]$3");
30+
2831
try {
2932
return new URL(url).hostname;
3033
} catch {

0 commit comments

Comments
 (0)