@catbee/utils
Version:
A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.
360 lines • 12 kB
JavaScript
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { URL, URLSearchParams } from "url";
/**
* Appends query parameters to a given URL.
*
* @param {string} url - The base URL to which query parameters will be appended.
* @param {Record<string, string | number>} params - Key-value pairs to add as query parameters.
* @returns {string} The new URL string with query parameters appended.
*
* @example
* appendQueryParams('https://example.com', { page: 1, limit: 10 });
* // → 'https://example.com/?page=1&limit=10'
*/
export function appendQueryParams(url, params) {
var e_1, _a;
var urlObj = new URL(url);
try {
for (var _b = __values(Object.entries(params)), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), key = _d[0], value = _d[1];
urlObj.searchParams.set(key, value.toString());
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return urlObj.toString();
}
/**
* Parses a query string into a key-value object.
*
* @param {string} query - The query string (with or without leading '?').
* @returns {Record<string, string>} Object representing parsed query parameters.
*
* @example
* parseQueryString('?page=1&limit=10');
* // → { page: '1', limit: '10' }
*/
export function parseQueryString(query) {
var cleanQuery = query.startsWith("?") ? query.slice(1) : query;
// Object.fromEntries guarantees string values in result
return Object.fromEntries(new URLSearchParams(cleanQuery));
}
/**
* Validates if a string is a valid URL.
*
* @param {string} url - The URL string to validate.
* @param {boolean} [requireHttps=false] - If true, requires the URL to use HTTPS.
* @returns {boolean} True if the URL is valid, false otherwise.
*/
export function isValidUrl(url, requireHttps) {
if (requireHttps === void 0) { requireHttps = false; }
try {
var parsedUrl = new URL(url);
if (!parsedUrl.protocol || !parsedUrl.hostname)
return false;
if (requireHttps && parsedUrl.protocol !== "https:")
return false;
return true;
}
catch (_a) {
return false;
}
}
/**
* Extracts the domain name from a URL.
*
* @param {string} url - The URL to extract the domain from.
* @param {boolean} [removeSubdomains=false] - If true, removes subdomains (returns root domain only).
* @returns {string} The domain name.
*
* @example
* getDomain('https://api.example.com/path');
* // → 'api.example.com'
*
* getDomain('https://api.example.com/path', true);
* // → 'example.com'
*/
export function getDomain(url, removeSubdomains) {
if (removeSubdomains === void 0) { removeSubdomains = false; }
try {
var hostname = new URL(url).hostname;
if (!removeSubdomains) {
return hostname;
}
// Extract root domain (remove subdomains)
var parts = hostname.split(".");
if (parts.length <= 2)
return hostname;
// Handle special cases like co.in, com.au
var secondLevelDomains = ["co", "com", "org", "net", "gov", "edu", "ac"];
var sld = parts[parts.length - 2];
if (secondLevelDomains.includes(sld) && parts.length > 2) {
return parts.slice(-3).join(".");
}
return parts.slice(-2).join(".");
}
catch (_a) {
return "";
}
}
/**
* Joins URL paths properly handling slashes.
*
* @param {...string[]} segments - URL path segments to join.
* @returns {string} Joined URL path.
*
* @example
* joinPaths('https://example.com/', '/api/', '/users');
* // → 'https://example.com/api/users'
*/
export function joinPaths() {
var segments = [];
for (var _i = 0; _i < arguments.length; _i++) {
segments[_i] = arguments[_i];
}
var result = segments
.filter(function (s) { return s !== undefined && s !== null; })
.map(function (segment, index) {
if (index === 0)
return segment.replace(/\/+$/, "");
return segment.replace(/^\/+|\/+$/g, "");
})
.filter(Boolean)
.join("/");
if (segments[0] === "" && !result.startsWith("/"))
result = "/" + result;
return result;
}
/**
* Normalizes a URL by resolving relative paths, handling protocol-relative URLs, etc.
*
* @param {string} url - The URL to normalize.
* @param {string} [base] - Optional base URL for resolving relative URLs.
* @returns {string} Normalized URL.
*
* @example
* normalizeUrl('HTTP://Example.COM/foo/../bar');
* // → 'http://example.com/bar'
*/
export function normalizeUrl(url, base) {
try {
// Handle protocol-relative URLs
if (url.startsWith("//")) {
url = "https:".concat(url);
}
// Resolve relative URLs against a base
var parsedUrl = base ? new URL(url, base) : new URL(url);
// Normalize
parsedUrl.pathname = parsedUrl.pathname.replace(/\/+/g, "/"); // Collapse multiple slashes
parsedUrl.pathname = parsedUrl.pathname.replace(/\/+$/, ""); // Remove trailing slash
parsedUrl.hostname = parsedUrl.hostname.toLowerCase();
return parsedUrl.toString();
}
catch (_a) {
return url; // Return original if invalid
}
}
/**
* Creates a URL builder for constructing URLs with a base URL.
*
* @param {string} baseUrl - The base URL to build upon.
* @returns {Object} URL builder methods.
*
* @example
* const api = createUrlBuilder('https://api.example.com');
* api.path('/users', { active: true });
* // → 'https://api.example.com/users?active=true'
*/
export function createUrlBuilder(baseUrl) {
return {
/**
* Creates a full URL with the given path and query parameters.
*
* @param {string} path - The path to append to the base URL.
* @param {Record<string, any>} [params] - Query parameters to add.
* @returns {string} The complete URL.
*/
path: function (path, params) {
var url = joinPaths(baseUrl, path);
return params
? appendQueryParams(url, params)
: url;
},
/**
* Creates a full URL with query parameters but no additional path.
*
* @param {Record<string, any>} params - Query parameters to add.
* @returns {string} The complete URL with query parameters.
*/
query: function (params) {
return appendQueryParams(baseUrl, params);
},
};
}
/**
* Extracts specific query parameters from a URL.
*
* @param {string} url - The URL to extract parameters from.
* @param {string[]} paramNames - Names of parameters to extract.
* @returns {Record<string, string>} Object containing the extracted parameters.
*/
export function extractQueryParams(url, paramNames) {
var e_2, _a;
try {
var parsedUrl = new URL(url);
var result = {};
try {
for (var paramNames_1 = __values(paramNames), paramNames_1_1 = paramNames_1.next(); !paramNames_1_1.done; paramNames_1_1 = paramNames_1.next()) {
var name_1 = paramNames_1_1.value;
var value = parsedUrl.searchParams.get(name_1);
if (value !== null) {
result[name_1] = value;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (paramNames_1_1 && !paramNames_1_1.done && (_a = paramNames_1.return)) _a.call(paramNames_1);
}
finally { if (e_2) throw e_2.error; }
}
return result;
}
catch (_b) {
return {};
}
}
/**
* Removes specified query parameters from a URL.
*
* @param {string} url - The URL to modify.
* @param {string[]} paramsToRemove - Names of parameters to remove.
* @returns {string} URL with parameters removed.
*/
export function removeQueryParams(url, paramsToRemove) {
var e_3, _a;
try {
var parsedUrl = new URL(url);
try {
for (var paramsToRemove_1 = __values(paramsToRemove), paramsToRemove_1_1 = paramsToRemove_1.next(); !paramsToRemove_1_1.done; paramsToRemove_1_1 = paramsToRemove_1.next()) {
var param = paramsToRemove_1_1.value;
parsedUrl.searchParams.delete(param);
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (paramsToRemove_1_1 && !paramsToRemove_1_1.done && (_a = paramsToRemove_1.return)) _a.call(paramsToRemove_1);
}
finally { if (e_3) throw e_3.error; }
}
return parsedUrl.toString();
}
catch (_b) {
return url;
}
}
/**
* Gets the file extension from a URL path.
*
* @param {string} url - The URL to examine.
* @returns {string} The file extension (without dot) or empty string if none found.
*
* @example
* getExtension('https://example.com/document.pdf?v=1');
* // → 'pdf'
*/
export function getExtension(url) {
try {
var pathname = new URL(url).pathname;
var match = pathname.match(/\.([^./\\?#]+)$/);
return match ? match[1].toLowerCase() : "";
}
catch (_a) {
// If URL parsing fails, try a simpler approach
var match = url.match(/\.([^./\\?#]+)$/);
return match ? match[1].toLowerCase() : "";
}
}
/**
* Parses URL query parameters into a strongly-typed object.
*
* @template T Expected type of the query parameters
* @param {string} url - The URL to parse.
* @param {Record<keyof T, (val: string) => any>} [converters] - Type converters for params.
* @returns {Partial<T>} Typed query parameters.
*
* @example
* parseTypedQueryParams<{page: number, q: string}>('https://example.com?page=2&q=test', {
* page: Number,
* q: String
* });
* // → { page: 2, q: 'test' }
*/
export function parseTypedQueryParams(url, converters) {
var e_4, _a;
try {
var searchParams = new URL(url).searchParams;
var result = {};
try {
for (var _b = __values(searchParams.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), key = _d[0], value = _d[1];
if (converters && key in converters) {
try {
result[key] = converters[key](value);
}
catch (_e) {
// Skip on conversion error
}
}
else {
result[key] = value;
}
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_4) throw e_4.error; }
}
return result;
}
catch (_f) {
return {};
}
}
//# sourceMappingURL=url.utils.js.map