import { customAlphabet } from 'nanoid' /** Base62 alphabet: `_` and `-` excluded so the prefix separator stays unambiguous. */ const segment = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 24) /** * Generates a prefixed resource id (`{prefix}_{24 base62 chars}`, ~143 bits). * * @param prefix - The resource-type prefix (e.g. `usr`, `org`). * @returns The generated id. */ export function generate(prefix: string): string { return `${prefix}_${random()}` } /** * Generates the random segment of an id (24 base62 chars) without a prefix, * for ids composing extra parts (e.g. `wh_{timestamp}_{random}`). * * @returns The generated segment. */ export function random(): string { return segment() } /** * Generates a time-prefixed resource id (`{prefix}_{epoch ms}_{24 base62 * chars}`). The epoch-ms is zero-padded to 15 digits (headroom past the year * 5138) so lexical id order is chronological, letting newest-first lists page * by keyset on the id alone. * * @param prefix - The resource-type prefix (e.g. `wh`, `ftr`). * @param now - The timestamp to embed. * @returns The generated id. */ export function generateSortable(prefix: string, now: Date = new Date()): string { return `${prefix}_${now.getTime().toString().padStart(15, '0')}_${random()}` }