fix(web): support request IDs over HTTP (#182)

This commit is contained in:
QiuSW
2026-09-01 00:51:29 +08:00
parent 7be57bfe6b
commit dce4a4fc2a
11 changed files with 103 additions and 32 deletions
+34
View File
@@ -0,0 +1,34 @@
function fillWithPseudoRandomBytes(bytes) {
for (let index = 0; index < bytes.length; index += 1) {
bytes[index] = Math.floor(Math.random() * 256)
}
return bytes
}
function formatUuidV4(bytes) {
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = Array.from(bytes, value => value.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)}`
}
function browserCrypto() {
return typeof window === 'undefined' ? undefined : window.crypto
}
export function createRequestId(cryptoApi = browserCrypto()) {
if (typeof cryptoApi?.randomUUID === 'function') {
return cryptoApi.randomUUID()
}
const bytes = new Uint8Array(16)
if (typeof cryptoApi?.getRandomValues === 'function') {
cryptoApi.getRandomValues(bytes)
} else {
// requestId is an idempotency key, not a secret. Public HTTP contexts can
// expose neither Web Crypto method, so retain a UUID-shaped local fallback.
fillWithPseudoRandomBytes(bytes)
}
return formatUuidV4(bytes)
}