Skip to content

Commit bea1bd6

Browse files
author
brizental
committed
Provide a fallback for when cryptop is not present
1 parent c0d2288 commit bea1bd6

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

src/metrics/types/uuid.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,32 @@ import { Metric, MetricType, CommonMetricData } from "metrics";
99
import { isString } from "utils";
1010
import Glean from "glean";
1111

12+
/**
13+
* Generates a UUIDv4.
14+
*
15+
* Will provide a fallback in case `crypto` is not available,
16+
* which makes the "uuid" package generator not work.
17+
*
18+
* # Important
19+
*
20+
* This workaround is here for usage in Qt/QML environments, where `crypto` is not available.
21+
* Bug 1688015 was opened to figure out a less hacky way to do this.
22+
*
23+
* @returns A randomly generated UUIDv4.
24+
*/
25+
function generateUUIDv4(): string {
26+
if (typeof crypto !== "undefined") {
27+
return UUIDv4();
28+
} else {
29+
// Copied from https://stackoverflow.com/a/2117523/261698
30+
// and https://stackoverflow.com/questions/105034/how-to-create-guid-uuid
31+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
32+
const r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
33+
return v.toString(16);
34+
});
35+
}
36+
}
37+
1238
export class UUIDMetric extends Metric<string, string> {
1339
constructor(v: unknown) {
1440
super(v);
@@ -54,7 +80,7 @@ class UUIDMetricType extends MetricType {
5480
}
5581

5682
if (!value) {
57-
value = UUIDv4();
83+
value = generateUUIDv4();
5884
}
5985

6086
let metric: UUIDMetric;
@@ -79,7 +105,7 @@ class UUIDMetricType extends MetricType {
79105
return;
80106
}
81107

82-
const value = UUIDv4();
108+
const value = generateUUIDv4();
83109
await this.set(value);
84110

85111
return value;

0 commit comments

Comments
 (0)