shelving
Version:
Toolkit for using data in JavaScript.
45 lines (44 loc) • 2.19 kB
JavaScript
import { RequiredError } from "../error/RequiredError.js";
import { getURL, isURL } from "./url.js";
/** Default whitelist for URL schemes. */
const SCHEMES = ["http:", "https:"];
/**
* Is an unknown value a link URL?
* - A valid link URL is a `URL` instance with a scheme matching the `schemes` array, and `host` matching the optional `hosts` array.
*/
export function isLinkURL(value, schemes = SCHEMES, hosts) {
return isURL(value) && schemes.includes(value.protocol) && (!hosts || hosts.includes(value.host));
}
/**
* Convert a possible URL to a link URL, or return `undefined` if conversion fails.
* - A valid link URL is a `URL` instance with a scheme matching the `schemes` array, and `host` matching the optional `hosts` array.
*/
export function getLinkURL(value, base, schemes = SCHEMES, hosts) {
const url = getURL(value, base);
if (isLinkURL(url, schemes, hosts))
return url;
}
/**
* Convert a possible URL to a link URL, or throw `RequiredError` if conversion fails.
* - A valid link URL is a `URL` instance with a scheme matching the `schemes` array, and `host` matching the optional `hosts` array.
*/
export function requireLinkURL(value, base, schemes, hosts, caller = requireLinkURL) {
const url = getLinkURL(value, base, schemes, hosts);
if (!url)
throw new RequiredError("Invalid link", { received: value, base, schemes, hosts, caller });
return url;
}
/**
* Convert a possible URL to an link URL string, or return `undefined` if conversion fails.
* - A valid link URL string is an absolute URL string with a scheme matching the `schemes` array, and `host` matching the optional `hosts` array.
*/
export function getLink(value, base, schemes = SCHEMES, hosts) {
return getLinkURL(value, base, schemes, hosts)?.href;
}
/**
* Convert a possible URL to an link URL string, or throw `RequiredError` if conversion fails.
* - A valid link URL string is an absolute URL string with a scheme matching the `schemes` array, and `host` matching the optional `hosts` array.
*/
export function requireLink(value, base, schemes, hosts, caller = requireLink) {
return requireLinkURL(value, base, schemes, hosts, caller).href;
}