UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

30 lines (29 loc) 1.05 kB
import { RequiredError } from "../error/RequiredError.js"; import { notOptional } from "./optional.js"; /** Is an unknown value a URL object? */ export function isURL(value) { return value instanceof URL; } /** Assert that an unknown value is a URL object. */ export function assertURL(value, caller = assertURL) { if (!isURL(value)) throw new RequiredError("Invalid URL", { received: value, caller }); } /** Convert a possible URL to a URL, or return `undefined` if conversion fails. */ export function getURL(possible, base = _BASE) { if (notOptional(possible)) { try { return isURL(possible) ? possible : new URL(possible, base); } catch (e) { // } } } const _BASE = typeof document === "object" ? document.baseURI : undefined; /** Convert a possible URL to a URL, or throw `RequiredError` if conversion fails. */ export function requireURL(possible, base, caller = requireURL) { const url = getURL(possible, base); assertURL(url, caller); return url; }