All files / lib ids.ts

100% Statements 12/12
100% Branches 0/0
100% Functions 3/3
100% Lines 11/11

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      193x         81x         12x 12x 12x 12x 72x   12x       6x 6x 6x    
import { generateSlug as sharedGenerateSlug } from "@interioring/utils/format/slug";
 
export function generateId(): string {
	return crypto.randomUUID();
}
 
// Re-export the shared slug generator so call sites can still import it from
// here while we transition; prefer `@interioring/utils/format/slug` in new code.
export const generateSlug = sharedGenerateSlug;
 
// Cryptographically random base36 suffix. 36 doesn't divide 256 evenly so the
// final char has a tiny modulo bias — acceptable for non-secret IDs.
export function randomBase36Suffix(length: number): string {
	const bytes = new Uint8Array(length);
	crypto.getRandomValues(bytes);
	let out = "";
	for (let i = 0; i < length; i++) {
		out += (bytes[i] % 36).toString(36);
	}
	return out;
}
 
export function generateUniqueSlug(text: string): string {
	const baseSlug = generateSlug(text);
	const suffix = randomBase36Suffix(6);
	return `${baseSlug}-${suffix}`;
}