| 1 | import { randomBytes } from 'node:crypto'; |
| 2 | |
| 3 | const ENCODING = ' |
| 4 | const ULID_BYTES = 16 |
| 5 | const ULID_CHARS = 26 |
| 6 | |
| 7 | export function createUlid(now |
| 8 | const bytes = |
| 9 | bytes.writeUIntBE(now |
| 10 | randomBytes(10).copy |
| 11 | return bytesToUlid(bytes |
| 12 | } |
| 13 | |
| 14 | export function ulidToBytes(ulid |
| 15 | if (ulid.length |
| 16 | throw new TypeError( |
| 17 | `ulid must be ${ULID_CHARS} characters, got ${ |
| 18 | ); |
| 19 | } |
| 20 | let bits = |
| 21 | for (const char |
| 22 | const value = |
| 23 | if (value === |
| 24 | bits = (bits |
| 25 | } |
| 26 | const bytes = |
| 27 | for (let i |
| 28 | bytes[i] = |
| 29 | bits >>= 8n |
| 30 | } |
| 31 | return bytes; |
| 32 | } |
| 33 | |
| 34 | export function bytesToUlid(bytes |
| 35 | if (bytes.length |
| 36 | throw new TypeError( |
| 37 | `ulid must be ${ULID_BYTES} bytes, got ${ |
| 38 | ); |
| 39 | } |
| 40 | let bits = |
| 41 | for (const byte |
| 42 | // 26 base32 characters hold 130 bits; the leading 2 are always zero. |
| 43 | let ulid = |
| 44 | for (let i |
| 45 | ulid = ENCODING[ |
| 46 | bits >>= 5n |
| 47 | } |
| 48 | return ulid; |
| 49 | } |