|
1 | 1 | export class RandomGenerator { |
| 2 | + /** |
| 3 | + * Generates a RFC 4122 version 4 UUID. |
| 4 | + * Uses native crypto.randomUUID() if available, otherwise falls back to |
| 5 | + * a custom implementation using crypto.getRandomValues(). |
| 6 | + * |
| 7 | + * @returns A version 4 UUID string |
| 8 | + */ |
| 9 | + static uuidv4(): string { |
| 10 | + // Try native crypto.randomUUID() (available in Node.js 19+ and modern browsers) |
| 11 | + const uuid = globalThis.crypto?.randomUUID?.() |
| 12 | + if (uuid) { |
| 13 | + return uuid |
| 14 | + } |
| 15 | + |
| 16 | + // Custom implementation using crypto.getRandomValues() |
| 17 | + // Based on RFC 4122 version 4 UUID specification |
| 18 | + const randomBytes = new Uint8Array(16) |
| 19 | + |
| 20 | + if (globalThis.crypto?.getRandomValues) { |
| 21 | + globalThis.crypto.getRandomValues(randomBytes) |
| 22 | + } else { |
| 23 | + // Fallback for React Native/Hermes and environments without crypto support |
| 24 | + // Hermes (React Native's JavaScript engine) does not provide crypto APIs |
| 25 | + // Math.random() is permitted by RFC 4122 for UUID v4 ("pseudo-randomly") |
| 26 | + // This approach is also used by expo-crypto and other RN libraries |
| 27 | + // Note: For TypeORM's use case (DB IDs, cache IDs), uniqueness is sufficient |
| 28 | + for (let i = 0; i < 16; i++) { |
| 29 | + randomBytes[i] = Math.floor(Math.random() * 256) |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Set version (4) and variant bits according to RFC 4122 |
| 34 | + randomBytes[6] = (randomBytes[6] & 0x0f) | 0x40 // Version 4 |
| 35 | + randomBytes[8] = (randomBytes[8] & 0x3f) | 0x80 // Variant 10 |
| 36 | + |
| 37 | + // Convert to UUID string format (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) |
| 38 | + const hexValues: string[] = [] |
| 39 | + randomBytes.forEach((byte) => { |
| 40 | + hexValues.push(byte.toString(16).padStart(2, "0")) |
| 41 | + }) |
| 42 | + |
| 43 | + return [ |
| 44 | + hexValues.slice(0, 4).join(""), |
| 45 | + hexValues.slice(4, 6).join(""), |
| 46 | + hexValues.slice(6, 8).join(""), |
| 47 | + hexValues.slice(8, 10).join(""), |
| 48 | + hexValues.slice(10, 16).join(""), |
| 49 | + ].join("-") |
| 50 | + } |
| 51 | + |
2 | 52 | /** |
3 | 53 | * discuss at: http://locutus.io/php/sha1/ |
4 | 54 | * original by: Webtoolkit.info (http://www.webtoolkit.info/) |
|
0 commit comments