import { randomBytes } from "node:crypto"; import { isShareSlug } from "../sharePaths"; import { prisma } from "./db"; /** Unambiguous lowercase alphabet (no 0/o/1/i/l). */ const SHARE_SLUG_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789"; function randomChunk(length: number): string { const bytes = randomBytes(length); let out = ""; for (let i = 0; i < length; i += 1) { out += SHARE_SLUG_ALPHABET[bytes[i]! % SHARE_SLUG_ALPHABET.length]; } return out; } export function generateShareSlug(): string { return `${randomChunk(4)}-${randomChunk(4)}`; } export async function allocateShareSlug(): Promise { for (let attempt = 0; attempt < 8; attempt += 1) { const shareSlug = generateShareSlug(); if (!isShareSlug(shareSlug)) continue; const existing = await prisma.publishedRule.findUnique({ where: { shareSlug }, select: { id: true }, }); if (!existing) return shareSlug; } throw new Error("Could not allocate a unique share slug"); }