()
| 7 | * to `crypto.getRandomValues()`, which does not require a secure context. |
| 8 | */ |
| 9 | export function generateId(): string { |
| 10 | if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { |
| 11 | return crypto.randomUUID() |
| 12 | } |
| 13 | |
| 14 | const bytes = new Uint8Array(16) |
| 15 | crypto.getRandomValues(bytes) |
| 16 | |
| 17 | bytes[6] = (bytes[6] & 0x0f) | 0x40 |
| 18 | bytes[8] = (bytes[8] & 0x3f) | 0x80 |
| 19 | |
| 20 | const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('') |
| 21 | return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` |
| 22 | } |
| 23 | |
| 24 | const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i |
| 25 |
no test coverage detected