38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
|
|
/**
|
||
|
|
* RFC4122 v4 UUID that also works in a NON-secure context (plain `http://` on a LAN
|
||
|
|
* IP, e.g. when localhost is unavailable), where `crypto.randomUUID` is undefined.
|
||
|
|
*
|
||
|
|
* Order of preference: crypto.randomUUID (secure contexts) → crypto.getRandomValues
|
||
|
|
* (available over http too) → Math.random fallback.
|
||
|
|
*/
|
||
|
|
export function uuid(): string {
|
||
|
|
const c: Crypto | undefined =
|
||
|
|
typeof globalThis !== "undefined" ? (globalThis.crypto as Crypto | undefined) : undefined;
|
||
|
|
|
||
|
|
if (c && typeof c.randomUUID === "function") {
|
||
|
|
return c.randomUUID();
|
||
|
|
}
|
||
|
|
|
||
|
|
const bytes = new Uint8Array(16);
|
||
|
|
if (c && typeof c.getRandomValues === "function") {
|
||
|
|
c.getRandomValues(bytes);
|
||
|
|
} else {
|
||
|
|
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
||
|
|
}
|
||
|
|
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
|
||
|
|
bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC4122 variant
|
||
|
|
|
||
|
|
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
|
||
|
|
return (
|
||
|
|
hex.slice(0, 4).join("") +
|
||
|
|
"-" +
|
||
|
|
hex.slice(4, 6).join("") +
|
||
|
|
"-" +
|
||
|
|
hex.slice(6, 8).join("") +
|
||
|
|
"-" +
|
||
|
|
hex.slice(8, 10).join("") +
|
||
|
|
"-" +
|
||
|
|
hex.slice(10, 16).join("")
|
||
|
|
);
|
||
|
|
}
|