Skip to content

Commit

Permalink
fix: protocol handling
Browse files Browse the repository at this point in the history
  • Loading branch information
manniL committed Sep 20, 2023
1 parent 1245a84 commit d9be4a6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export function isScriptProtocol(protocol?: string) {
}

const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
const HTTP_PROTOCO_RE = /^https?:\/\//;

export function hasTrailingSlash(input = "", queryParameters = false): boolean {
if (!queryParameters) {
Expand All @@ -62,6 +63,10 @@ export function withoutTrailingSlash(
input = "",
queryParameters = false
): string {
const hasProtocolDifferentThanHttp = hasProtocol(input) && !HTTP_PROTOCO_RE.test(input);
if(hasProtocolDifferentThanHttp) {
return input;
}
if (!queryParameters) {
const url = hasTrailingSlash(input) ? input.slice(0, -1) : input;
return url || "/";
Expand All @@ -80,6 +85,10 @@ export function withoutTrailingSlash(
}

export function withTrailingSlash(input = "", queryParameters = false): string {
const hasProtocolDifferentThanHttp = hasProtocol(input) && !HTTP_PROTOCO_RE.test(input);
if(hasProtocolDifferentThanHttp) {
return input;
}
if (!queryParameters) {
return input.endsWith("/") ? input : input + "/";
}
Expand Down
4 changes: 4 additions & 0 deletions test/trailing-slash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ describe("withTrailingSlash, queryParams: false", () => {
"foo?123": "foo?123/",
"foo/?123": "foo/?123/",
"foo/?123#abc": "foo/?123#abc/",
"mailto:example@example.com": "mailto:example@example.com",
};

for (const input in tests) {
Expand All @@ -31,6 +32,7 @@ describe("withTrailingSlash, queryParams: true", () => {
"foo?123": "foo/?123",
"foo/?123": "foo/?123",
"foo?123#abc": "foo/?123#abc",
"mailto:example@example.com": "mailto:example@example.com",
};

for (const input in tests) {
Expand All @@ -54,6 +56,7 @@ describe("withoutTrailingSlash, queryParams: false", () => {
"foo?123": "foo?123",
"foo/?123": "foo/?123",
"foo/?123#abc": "foo/?123#abc",
'scheme://host:port/path/': 'scheme://host:port/path/',
};

for (const input in tests) {
Expand All @@ -78,6 +81,7 @@ describe("withoutTrailingSlash, queryParams: true", () => {
"foo?123": "foo?123",
"foo/?123": "foo?123",
"foo/?123#abc": "foo?123#abc",
'scheme://host:port/path/': 'scheme://host:port/path/',
};

for (const input in tests) {
Expand Down

0 comments on commit d9be4a6

Please sign in to comment.