signal-desktop/ts/util/url.ts

40 lines
898 B
TypeScript
Raw Normal View History

// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
export function maybeParseUrl(value: string): undefined | URL {
if (typeof value === 'string') {
try {
return new URL(value);
2023-11-02 19:42:31 +00:00
} catch {
/* Errors are ignored. */
}
}
return undefined;
}
export function setUrlSearchParams(
url: Readonly<URL>,
searchParams: Readonly<Record<string, unknown>>
): URL {
const result = cloneUrl(url);
2023-04-07 16:42:12 +00:00
result.search = '';
for (const [key, value] of Object.entries(searchParams)) {
if (value == null) {
continue;
}
result.searchParams.append(key, String(value));
}
return result;
}
function cloneUrl(url: Readonly<URL>): URL {
return new URL(url.href);
}
export function urlPathFromComponents(
components: ReadonlyArray<string>
): string {
return `/${components.filter(Boolean).map(encodeURIComponent).join('/')}`;
}