| 344 | * generateCompactId('msg-') // => "msg-1a2b3c4d5e6" |
| 345 | */ |
| 346 | export const generateCompactId = (prefix?: string): string => { |
| 347 | // Get the last 32 bits of the timestamp |
| 348 | const timestamp = (Date.now() & 0xffffffff) >>> 0 |
| 349 | // Generate a 32-bit random number |
| 350 | const random = Math.floor(Math.random() * 0x100000000) >>> 0 |
| 351 | |
| 352 | // Combine them into a 64-bit representation as two 32-bit numbers |
| 353 | const high = timestamp |
| 354 | const low = random |
| 355 | |
| 356 | // Convert to a hex string, pad if necessary, and combine |
| 357 | const highHex = high.toString(16).padStart(8, '0') |
| 358 | const lowHex = low.toString(16).padStart(8, '0') |
| 359 | |
| 360 | const combinedHex = highHex + lowHex |
| 361 | |
| 362 | // Convert hex to a Buffer and then to base64url |
| 363 | const bytes = Buffer.from(combinedHex, 'hex') |
| 364 | const str = bytes.toString('base64url').replace(/=/g, '') |
| 365 | |
| 366 | return prefix ? `${prefix}${str}` : str |
| 367 | } |
| 368 | |
| 369 | /** |
| 370 | * Removes null characters from a string |