Files
faunosteo/apps/app/src/editor/ids.ts
T

22 lines
593 B
TypeScript

const ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567'
const SUFFIX_LENGTH = 10
export type IdPrefix =
| 'view'
| 'anno'
| 'cat'
| 'ref'
| 'zone'
| 'fcat'
| 'node'
/**
* A new element id, `<prefix>-<10 chars a-z2-7>`. 32 symbols: a byte masked to 5 bits
* is unbiased. No document walk; a `duplicate_key` answer is the caller's one retry.
*/
export function newElementId(prefix: IdPrefix): string {
const bytes = crypto.getRandomValues(new Uint8Array(SUFFIX_LENGTH))
const suffix = Array.from(bytes, (byte) => ALPHABET[byte & 31]).join('')
return `${prefix}-${suffix}`
}