Skip to content

Commit

Permalink
fix: stringify protocol-relative URLs (#207)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Feb 5, 2024
1 parent 21e644e commit 3cd8c3f
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/parse.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { decode } from "./encoding";
import { hasProtocol } from "./utils";
const protocolRelative = Symbol.for("ufo:protocolRelative");
export interface ParsedURL {
protocol?: string;
host?: string;
Expand All @@ -8,6 +9,7 @@ export interface ParsedURL {
pathname: string;
hash: string;
search: string;
[protocolRelative]?: boolean;
}

export interface ParsedAuth {
Expand Down Expand Up @@ -64,6 +66,7 @@ export function parseURL(input = "", defaultProto?: string): ParsedURL {
pathname,
search,
hash,
[protocolRelative]: !protocol,
};
}

Expand Down Expand Up @@ -125,7 +128,10 @@ export function stringifyParsedURL(parsed: Partial<ParsedURL>): string {
const hash = parsed.hash || "";
const auth = parsed.auth ? parsed.auth + "@" : "";
const host = parsed.host || "";
const proto = parsed.protocol ? parsed.protocol + "//" : "";
const proto =
parsed.protocol || parsed[protocolRelative]
? (parsed.protocol || "") + "//"
: "";
return proto + auth + host + pathname + search + hash;
}

Expand Down
2 changes: 1 addition & 1 deletion test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ describe("parseURL", () => {

for (const t of tests) {
test(t.input.toString(), () => {
expect(parseURL(t.input)).toEqual(t.out);
expect(JSON.parse(JSON.stringify(parseURL(t.input)))).toEqual(t.out);
});
}
});
Expand Down
1 change: 1 addition & 0 deletions test/utilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ describe("stringifyParsedURL", () => {
{ input: "test?query=123#hash", out: "test?query=123#hash" },
{ input: "/%c", out: "/%c" },
{ input: "/%", out: "/%" },
{ input: "//test.com", out: "//test.com" },
{
input: "http://foo.com/test?query=123#hash",
out: "http://foo.com/test?query=123#hash",
Expand Down

0 comments on commit 3cd8c3f

Please sign in to comment.