session-uuid.test.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { uuidv7 } from "../../src/harness/session/uuid.ts";
  3. const UUID_V7_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
  4. const TIMESTAMP = 0x0123456789ab;
  5. function parseTimestamp(uuid: string): number {
  6. return Number.parseInt(uuid.replaceAll("-", "").slice(0, 12), 16);
  7. }
  8. afterEach(() => {
  9. vi.unstubAllGlobals();
  10. });
  11. describe("uuidv7", () => {
  12. it("uses the RFC 9562 layout and preserves monotonic order", () => {
  13. const randomValues = [
  14. new Uint8Array([0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xfe, 0x01, 0x11, 0x22, 0x33, 0x44, 0x55]),
  15. new Uint8Array(16),
  16. new Uint8Array(16),
  17. ];
  18. const getRandomValues = vi.fn((bytes: Uint8Array) => {
  19. bytes.set(randomValues.shift() ?? new Uint8Array(bytes.length));
  20. return bytes;
  21. });
  22. vi.stubGlobal("crypto", { getRandomValues });
  23. const dateNow = vi.spyOn(Date, "now").mockReturnValue(TIMESTAMP);
  24. try {
  25. const first = uuidv7();
  26. const second = uuidv7();
  27. const third = uuidv7();
  28. expect(first).toBe("01234567-89ab-7fff-bfff-f91122334455");
  29. expect(second).toBe("01234567-89ab-7fff-bfff-fc0000000000");
  30. expect(third).toBe("01234567-89ac-7000-8000-000000000000");
  31. expect(first).toMatch(UUID_V7_RE);
  32. expect(second).toMatch(UUID_V7_RE);
  33. expect(third).toMatch(UUID_V7_RE);
  34. expect(parseTimestamp(first)).toBe(TIMESTAMP);
  35. expect(parseTimestamp(second)).toBe(TIMESTAMP);
  36. expect(parseTimestamp(third)).toBe(TIMESTAMP + 1);
  37. expect(first < second).toBe(true);
  38. expect(second < third).toBe(true);
  39. expect(getRandomValues).toHaveBeenCalledTimes(3);
  40. } finally {
  41. dateNow.mockRestore();
  42. }
  43. });
  44. });