UNPKG

@automattic/calypso-url

Version:

This library provides both generic and Calypso-specific utilities for handling URLs.

57 lines 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const url_type_1 = require("./url-type"); const BASE_URL = 'http://__domain__.invalid/'; /** * Format a URL as a particular type. * Does not support formatting invalid or path-relative URLs. * * @param url The URL to format. * @param urlType The URL type into which to format. If not provided, defaults to the same type as `url`, which effectively results in the URL being normalized. * @returns The formatted URL. */ function format(url, urlType) { let parsed; let originalType; if (!(url instanceof URL) && typeof url !== 'string') { throw new Error('`url` should be a string or URL instance'); } if (url instanceof URL) { // The native URL object can only represent absolute URLs. parsed = url; originalType = url_type_1.URL_TYPE.ABSOLUTE; } else { originalType = (0, url_type_1.determineUrlType)(url); if (originalType === url_type_1.URL_TYPE.INVALID) { throw new Error('Cannot format an invalid URL.'); } if (originalType === url_type_1.URL_TYPE.PATH_RELATIVE) { throw new Error('Cannot format path-relative URLs.'); } parsed = new URL(url, BASE_URL); } if (urlType === undefined) { urlType = originalType; } switch (urlType) { case url_type_1.URL_TYPE.PATH_RELATIVE: throw new Error('Cannot format into path-relative URLs.'); case url_type_1.URL_TYPE.PATH_ABSOLUTE: return parsed.href.replace(parsed.origin, ''); case url_type_1.URL_TYPE.SCHEME_RELATIVE: if (originalType === url_type_1.URL_TYPE.PATH_ABSOLUTE) { throw new Error('Cannot format a path-absolute URL as a scheme-relative URL.'); } return parsed.href.replace(parsed.protocol, ''); case url_type_1.URL_TYPE.ABSOLUTE: if (originalType !== url_type_1.URL_TYPE.ABSOLUTE) { throw new Error('Cannot format a partial URL as an absolute URL.'); } return parsed.href; default: throw new Error(`Cannot format as \`${urlType}\` URL type.`); } } exports.default = format; //# sourceMappingURL=format.js.map