From 4e4ba936a938803635de77216eee6d44aecb0fb4 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 24 Aug 2023 20:17:04 +0200 Subject: [PATCH] feat(stringifyParsedURL): support partial url inputs (resolves #166) --- src/parse.ts | 27 ++++++++++----------------- test/utilities.test.ts | 14 +++++++++++++- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/parse.ts b/src/parse.ts index e62813e1..773a3e46 100644 --- a/src/parse.ts +++ b/src/parse.ts @@ -117,23 +117,16 @@ export function parseHost(input = ""): ParsedHost { * @param [parsed] - The parsed URL * @returns A stringified URL. */ -export function stringifyParsedURL(parsed: ParsedURL): string { - const fullpath = - parsed.pathname + - (parsed.search - ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search - : "") + - parsed.hash; - if (!parsed.protocol) { - return fullpath; - } - return ( - parsed.protocol + - "//" + - (parsed.auth ? parsed.auth + "@" : "") + - parsed.host + - fullpath - ); +export function stringifyParsedURL(parsed: Partial): string { + const pathname = parsed.pathname || ""; + const search = parsed.search + ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search + : ""; + const hash = parsed.hash || ""; + const auth = parsed.auth ? parsed.auth + "@" : ""; + const host = parsed.host || ""; + const proto = parsed.protocol ? parsed.protocol + "//" : ""; + return proto + auth + host + pathname + search + hash; } const FILENAME_STRICT_REGEX = /\/([^/]+\.[^/]+)$/; diff --git a/test/utilities.test.ts b/test/utilities.test.ts index 42c5ff53..fb653b63 100644 --- a/test/utilities.test.ts +++ b/test/utilities.test.ts @@ -109,11 +109,23 @@ describe("stringifyParsedURL", () => { input: "/test?query=123,123#hash, test", out: "/test?query=123,123#hash, test", }, + { + input: { host: "google.com" }, + out: "google.com", + }, + { + input: { protocol: "https:", host: "google.com" }, + out: "https://google.com", + }, ]; for (const t of tests) { test(t.input.toString(), () => { - expect(stringifyParsedURL(parsePath(t.input))).toBe(t.out); + expect( + stringifyParsedURL( + typeof t.input === "string" ? parsePath(t.input) : t.input + ) + ).toBe(t.out); }); } });