/** * 为提交幂等键、命令 ID 和新会话链接生成 UUID v4。 * randomUUID 只在安全上下文及受支持浏览器中提供;通过普通 HTTP 访问时, * 使用同样具备安全随机性的 getRandomValues,避免请求尚未发出就抛出异常。 * 重试是否复用同一个 ID 仍由调用方的 pending 状态控制,这里只负责生成。 */ export function createUuid(): string { if (typeof globalThis.crypto.randomUUID === 'function') return globalThis.crypto.randomUUID() const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16)) // UUID v4 的第 7 字节高四位固定为 0100,第 9 字节高两位固定为 10。 // 其余 122 位保留随机值;不能用时间戳或 Math.random 替代,避免幂等键碰撞。 bytes[6] = (bytes[6] & 0x0f) | 0x40 bytes[8] = (bytes[8] & 0x3f) | 0x80 const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` }