toastflow-core 1.1.4 → 1.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/util.ts +18 -7
package/package.json
CHANGED
package/src/util.ts
CHANGED
|
@@ -2,22 +2,33 @@
|
|
|
2
2
|
* Generate a UUID v4 using `crypto.randomUUID` when available; otherwise fall back
|
|
3
3
|
* to the classic template with random nibbles (uses `crypto.getRandomValues` when possible).
|
|
4
4
|
*/
|
|
5
|
+
type CryptoLike = {
|
|
6
|
+
randomUUID?: () => string;
|
|
7
|
+
getRandomValues?: (arr: Uint8Array) => Uint8Array;
|
|
8
|
+
};
|
|
9
|
+
|
|
5
10
|
export function generateUuid(): string {
|
|
6
|
-
const
|
|
7
|
-
typeof crypto !== "undefined" ? (crypto as Crypto) : undefined;
|
|
11
|
+
const cryptoApi: CryptoLike | undefined = (globalThis as any)?.crypto;
|
|
8
12
|
|
|
9
|
-
if (typeof
|
|
13
|
+
if (typeof cryptoApi?.randomUUID === "function") {
|
|
10
14
|
try {
|
|
11
|
-
return
|
|
15
|
+
return cryptoApi.randomUUID();
|
|
12
16
|
} catch {
|
|
13
17
|
// ignore and use fallback
|
|
14
18
|
}
|
|
15
19
|
}
|
|
16
20
|
|
|
21
|
+
function randomNibble(): number {
|
|
22
|
+
if (typeof cryptoApi?.getRandomValues === "function") {
|
|
23
|
+
const bytes = new Uint8Array(1);
|
|
24
|
+
cryptoApi.getRandomValues(bytes);
|
|
25
|
+
return (bytes[0] ?? 0) & 0xf;
|
|
26
|
+
}
|
|
27
|
+
return Math.floor(Math.random() * 16);
|
|
28
|
+
}
|
|
29
|
+
|
|
17
30
|
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
|
|
18
|
-
const rand =
|
|
19
|
-
? cryptoSource.getRandomValues(new Uint8Array(1))[0] & 0xf
|
|
20
|
-
: Math.floor(Math.random() * 16);
|
|
31
|
+
const rand = randomNibble();
|
|
21
32
|
const value = c === "x" ? rand : (rand & 0x3) | 0x8;
|
|
22
33
|
return value.toString(16);
|
|
23
34
|
});
|