import assert from 'node:assert/strict' import { createUuid } from '../src/lib/uuid.ts' const originalCrypto = Object.getOwnPropertyDescriptor(globalThis, 'crypto') const realCrypto = globalThis.crypto const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ const useCrypto = value => Object.defineProperty(globalThis, 'crypto', { configurable: true, value }) try { // 安全上下文沿用浏览器原生方法,并保留 Crypto 接收者,防止 Illegal invocation。 const nativeCrypto = { randomUUID() { assert.equal(this, nativeCrypto) return '12345678-1234-4234-8234-123456789abc' }, getRandomValues() { assert.fail('支持原生 UUID 时不应走兼容分支') }, } useCrypto(nativeCrypto) assert.equal(createUuid(), '12345678-1234-4234-8234-123456789abc') // 模拟普通 HTTP 环境:crypto 存在,但没有 randomUUID;检查补零、版本位与变体位。 for (const [fill, expected] of [ [0, '00000000-0000-4000-8000-000000000000'], [255, 'ffffffff-ffff-4fff-bfff-ffffffffffff'], ]) { const httpCrypto = { getRandomValues(bytes) { assert.equal(this, httpCrypto) assert.ok(bytes instanceof Uint8Array) assert.equal(bytes.length, 16) return bytes.fill(fill) }, } useCrypto(httpCrypto) assert.equal(createUuid(), expected) } // 用真实随机源验证兼容分支连续生成的格式与唯一性,避免固定键让不同提交相互覆盖。 useCrypto({ getRandomValues: bytes => realCrypto.getRandomValues(bytes) }) const ids = Array.from({ length: 1000 }, () => createUuid()) assert.ok(ids.every(id => uuidV4.test(id))) assert.equal(new Set(ids).size, ids.length) } finally { Object.defineProperty(globalThis, 'crypto', originalCrypto) } console.log('UUID 兼容性检查通过(原生方法、HTTP 兼容分支、格式与唯一性)')