All files / lib utils.ts

100% Statements 64/64
100% Branches 32/32
100% Functions 18/18
100% Lines 57/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                  187x                   332x 17x   315x               77x               12x 12x 12x 12x     72x   12x               6x 6x 6x                   2x 2x 4x 3x     2x                   2x 2x 1x   2x             4x             87x 87x 87x 87x                     174x 174x                             197x 195x 195x 150x                       185x 185x 144x             7x   6x 6x                             3x 2x       1x 1x                             15x 2x     13x 13x 4x     9x 9x                   45x 44x                 26x                             10x 8x 11x      
import { UnauthorizedError, ValidationError } from "./errors";
import { generateSlug as sharedGenerateSlug } from "@interioring/utils/format/slug";
 
// Utility functions
 
/**
 * Generate a UUID v4
 */
export function generateId(): string {
	return crypto.randomUUID();
}
 
/**
 * Ensure user is present (for use in authenticated routes)
 * Throws UnauthorizedError if user is null
 */
export function requireUser<T extends { id: string }>(
	user: T | null | undefined,
): T {
	if (!user) {
		throw new UnauthorizedError("User session not found");
	}
	return user;
}
 
/**
 * Generate a URL-safe slug from a string. Delegates to the shared package
 * so portal + api stay in sync. Prefer importing directly from
 * `@interioring/utils/format/slug` in new code.
 */
export const generateSlug = sharedGenerateSlug;
 
/**
 * Generate a cryptographically random base36 suffix of the given length.
 * Uses Web Crypto (available in Cloudflare Workers, no import needed) instead
 * of Math.random() to avoid predictable / collision-prone outputs.
 */
export function randomBase36Suffix(length: number): string {
	const bytes = new Uint8Array(length);
	crypto.getRandomValues(bytes);
	let out = "";
	for (let i = 0; i < length; i++) {
		// Map byte (0-255) to base36 char (0-9a-z). 36 does not divide 256 evenly,
		// so there is a tiny modulo bias, but it's acceptable for non-secret IDs.
		out += (bytes[i] % 36).toString(36);
	}
	return out;
}
 
/**
 * Generate a unique slug by appending a crypto-random base36 suffix.
 * Suffix widened from 4 to 6 chars for collision resistance at scale.
 */
export function generateUniqueSlug(text: string): string {
	const baseSlug = generateSlug(text);
	const suffix = randomBase36Suffix(6);
	return `${baseSlug}-${suffix}`;
}
 
/**
 * Pick specific fields from an object
 */
export function pick<T extends object, K extends keyof T>(
	obj: T,
	keys: K[],
): Pick<T, K> {
	const result = {} as Pick<T, K>;
	for (const key of keys) {
		if (key in obj) {
			result[key] = obj[key];
		}
	}
	return result;
}
 
/**
 * Omit specific fields from an object
 */
export function omit<T extends object, K extends keyof T>(
	obj: T,
	keys: K[],
): Omit<T, K> {
	const result = { ...obj };
	for (const key of keys) {
		delete result[key];
	}
	return result as Omit<T, K>;
}
 
/**
 * Check if a value is defined (not null or undefined)
 */
export function isDefined<T>(value: T | null | undefined): value is T {
	return value !== null && value !== undefined;
}
 
/**
 * Pagination helper
 */
export function getPagination(page = 1, limit = 20) {
	const safePage = Math.max(1, page);
	const safeLimit = Math.min(100, Math.max(1, limit));
	const offset = (safePage - 1) * safeLimit;
	return { offset, limit: safeLimit, page: safePage };
}
 
/**
 * Build pagination metadata
 */
export function buildPaginationMeta(
	total: number,
	page: number,
	limit: number,
) {
	const totalPages = Math.ceil(total / limit);
	return {
		total,
		page,
		limit,
		totalPages,
		hasNext: page < totalPages,
		hasPrev: page > 1,
	};
}
 
/**
 * Parse and validate integer ID from string
 * Returns the parsed number or null if invalid
 */
export function parseIntId(value: string | undefined): number | null {
	if (!value) return null;
	const parsed = parseInt(value, 10);
	if (Number.isNaN(parsed) || parsed < 1) return null;
	return parsed;
}
 
/**
 * Parse and validate a required integer ID from a route param.
 * Throws ValidationError if missing or invalid — eliminates the
 * repetitive parseIntId + null-check + throw pattern in route handlers.
 */
export function parseRequiredId(
	value: string | undefined,
	resource: string,
): number {
	const id = parseIntId(value);
	if (!id) throw new ValidationError(`Invalid ${resource} ID`);
	return id;
}
 
/**
 * Validate UUID format
 */
export function isValidUuid(value: string | undefined): boolean {
	if (!value) return false;
	const uuidRegex =
		/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
	return uuidRegex.test(value);
}
 
/**
 * Build a safe LIKE pattern for searching a UUID within a JSON array string.
 * This function validates the UUID format and escapes any LIKE special characters.
 * Returns null if the value is not a valid UUID.
 *
 * @example
 * // For searching if "abc-123" is in a JSON array like '["abc-123","def-456"]'
 * buildJsonArrayLikePattern("abc-123") // returns '%"abc-123"%'
 */
export function buildJsonArrayLikePattern(
	value: string | undefined,
): string | null {
	if (!value || !isValidUuid(value)) {
		return null;
	}
	// UUID only contains hex chars and hyphens, so no LIKE escaping needed,
	// but we escape % and _ just in case for defense in depth
	const escaped = value.replace(/%/g, "\\%").replace(/_/g, "\\_");
	return `%"${escaped}"%`;
}
 
/**
 * Build a safe LIKE pattern for searching any valid identifier within a JSON array string.
 * Accepts UUIDs and simple identifiers (alphanumeric with underscores/hyphens).
 * Returns null if the value is empty or contains dangerous characters.
 *
 * @example
 * buildJsonArrayLikePatternSafe("full_home") // returns '%"full_home"%'
 * buildJsonArrayLikePatternSafe("abc-123-def") // returns '%"abc-123-def"%'
 */
export function buildJsonArrayLikePatternSafe(
	value: string | undefined,
): string | null {
	if (!value) {
		return null;
	}
	// Allow alphanumeric, underscores, and hyphens only
	const safeIdRegex = /^[a-zA-Z0-9_-]+$/;
	if (!safeIdRegex.test(value)) {
		return null;
	}
	// Escape LIKE special characters for safety
	const escaped = value.replace(/%/g, "\\%").replace(/_/g, "\\_");
	return `%"${escaped}"%`;
}
 
/**
 * Check if value is in allowed enum array
 */
export function isValidEnum<T extends readonly string[]>(
	value: string | undefined,
	allowedValues: T,
): value is T[number] {
	if (!value) return false;
	return allowedValues.includes(value as T[number]);
}
 
/**
 * Sanitize search input for SQL LIKE queries
 * Escapes special characters: %, _, \
 * This prevents users from crafting malicious search patterns
 */
export function sanitizeSearchInput(search: string): string {
	return search
		.trim()
		.replace(/\\/g, "\\\\") // Escape backslashes first
		.replace(/%/g, "\\%") // Escape percent signs for LIKE queries
		.replace(/_/g, "\\_") // Escape underscores for LIKE queries
		.substring(0, 200); // Limit length to prevent DoS
}
 
/**
 * Validate an array contains only allowed enum values
 */
export function isValidEnumArray<T extends readonly string[]>(
	values: unknown,
	allowedValues: T,
): values is T[number][] {
	if (!Array.isArray(values)) return false;
	return values.every(
		(v) => typeof v === "string" && allowedValues.includes(v as T[number]),
	);
}