id.ts 1.1 KB

123456789101112131415161718192021222324
  1. let fallbackCounter = 0
  2. export function createId(prefix = 'web'): string {
  3. const uuid = globalThis.crypto?.randomUUID?.()
  4. if (uuid) return uuid.toLowerCase()
  5. fallbackCounter += 1
  6. return `${prefix}-${Date.now().toString(36)}-${fallbackCounter.toString(36)}-${Math.random().toString(36).slice(2, 10)}`
  7. }
  8. export function createUuid(): string {
  9. const native = globalThis.crypto?.randomUUID?.()
  10. if (native) return native.toLowerCase()
  11. const bytes = new Uint8Array(16)
  12. if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(bytes)
  13. else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.floor(Math.random() * 256)
  14. bytes[6] = (bytes[6] & 0x0f) | 0x40
  15. bytes[8] = (bytes[8] & 0x3f) | 0x80
  16. const hex = [...bytes].map(value => value.toString(16).padStart(2, '0')).join('')
  17. return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
  18. }
  19. export function routeKey(profile: string, sessionId: string): string {
  20. return `${encodeURIComponent(profile)}::${encodeURIComponent(sessionId)}`
  21. }