|
| 1 | +import { test } from "node:test"; |
| 2 | +import assert from "node:assert/strict"; |
| 3 | +import { uuid, uuidFallback } from "./uuid"; |
| 4 | + |
| 5 | +// Standard v4 shape: 8-4-4-4-12 hex groups, version nibble "4", variant nibble in [89ab]. |
| 6 | +const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; |
| 7 | + |
| 8 | +test("uuidFallback returns v4-format ids", () => { |
| 9 | + assert.match(uuidFallback(), V4); |
| 10 | +}); |
| 11 | + |
| 12 | +test("uuidFallback: successive calls differ", () => { |
| 13 | + assert.notEqual(uuidFallback(), uuidFallback()); |
| 14 | +}); |
| 15 | + |
| 16 | +test("uuid: falls back to v4 format when crypto.randomUUID is absent", () => { |
| 17 | + const original = crypto.randomUUID; |
| 18 | + // @ts-expect-error — simulating an insecure context, where randomUUID is undefined. |
| 19 | + crypto.randomUUID = undefined; |
| 20 | + try { |
| 21 | + assert.match(uuid(), V4); |
| 22 | + } finally { |
| 23 | + crypto.randomUUID = original; |
| 24 | + } |
| 25 | +}); |
| 26 | + |
| 27 | +test("uuid: uses the native implementation when available", () => { |
| 28 | + const original = crypto.randomUUID; |
| 29 | + const sentinel = |
| 30 | + "11111111-1111-4111-8111-111111111111" as `${string}-${string}-${string}-${string}-${string}`; |
| 31 | + crypto.randomUUID = () => sentinel; |
| 32 | + try { |
| 33 | + assert.equal(uuid(), sentinel); |
| 34 | + } finally { |
| 35 | + crypto.randomUUID = original; |
| 36 | + } |
| 37 | +}); |
0 commit comments