uuid.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. function byteToHex(byte: number): string {
  2. return byte.toString(16).padStart(2, "0");
  3. }
  4. /** 普通 main command 与 background wake 共用 UUID v7(48-bit 时间戳 + 随机位)。 */
  5. export function uuidv7(now: number = Date.now()): string {
  6. const bytes = new Uint8Array(16);
  7. crypto.getRandomValues(bytes);
  8. const ts = BigInt(now);
  9. bytes[0] = Number((ts >> 40n) & 0xffn);
  10. bytes[1] = Number((ts >> 32n) & 0xffn);
  11. bytes[2] = Number((ts >> 24n) & 0xffn);
  12. bytes[3] = Number((ts >> 16n) & 0xffn);
  13. bytes[4] = Number((ts >> 8n) & 0xffn);
  14. bytes[5] = Number(ts & 0xffn);
  15. bytes[6] = 0x70 | (bytes[6]! & 0x0f);
  16. bytes[8] = 0x80 | (bytes[8]! & 0x3f);
  17. const hex = Array.from(bytes, byteToHex).join("");
  18. return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
  19. }
  20. function formatUuid(bytes: Uint8Array): string {
  21. const normalized = new Uint8Array(bytes);
  22. normalized[6] = (normalized[6]! & 0x0f) | 0x40;
  23. normalized[8] = (normalized[8]! & 0x3f) | 0x80;
  24. const segments = [
  25. normalized.slice(0, 4),
  26. normalized.slice(4, 6),
  27. normalized.slice(6, 8),
  28. normalized.slice(8, 10),
  29. normalized.slice(10, 16),
  30. ];
  31. return segments.map((segment) => Array.from(segment, byteToHex).join("")).join("-");
  32. }
  33. export function createUuid(): string {
  34. const runtimeCrypto = globalThis.crypto;
  35. if (runtimeCrypto?.randomUUID) {
  36. return runtimeCrypto.randomUUID();
  37. }
  38. if (runtimeCrypto?.getRandomValues) {
  39. const bytes = new Uint8Array(16);
  40. runtimeCrypto.getRandomValues(bytes);
  41. return formatUuid(bytes);
  42. }
  43. // 部分移动端 WebView 只有 `crypto` 对象但没有 `randomUUID()`,
  44. // 之前 UI 初始化直接调用会在首屏崩掉。这里退回到最小可用的随机实现,
  45. // 保证移动端至少能生成 tab / history / request 所需的临时 ID。
  46. const bytes = new Uint8Array(16);
  47. for (let index = 0; index < bytes.length; index += 1) {
  48. bytes[index] = Math.floor(Math.random() * 256);
  49. }
  50. return formatUuid(bytes);
  51. }