From c290a12ce13075ec665b936709d31896e896b463 Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Thu, 21 Nov 2024 13:03:08 +0100 Subject: [PATCH] Simplify the `getUuid` helper function We can remove most feature testing from this helper function, with the exception of `randomUUID` since that's only available in "secure contexts", and also remove the fallback code-path. Note that this code was only added for Node.js compatibility, and it's no longer necessary now that the minimum support version is `20`; see also https://developer.mozilla.org/en-US/docs/Web/API/Crypto#browser_compatibility Finally, this patch also adds a basic unit-test for the helper function. --- src/shared/util.js | 13 ++----------- test/unit/util_spec.js | 9 +++++++++ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/shared/util.js b/src/shared/util.js index c4752522f..006c416b0 100644 --- a/src/shared/util.js +++ b/src/shared/util.js @@ -1075,21 +1075,12 @@ function normalizeUnicode(str) { function getUuid() { if ( (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) || - (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") + typeof crypto.randomUUID === "function" ) { return crypto.randomUUID(); } const buf = new Uint8Array(32); - if ( - typeof crypto !== "undefined" && - typeof crypto?.getRandomValues === "function" - ) { - crypto.getRandomValues(buf); - } else { - for (let i = 0; i < 32; i++) { - buf[i] = Math.floor(Math.random() * 255); - } - } + crypto.getRandomValues(buf); return bytesToString(buf); } diff --git a/test/unit/util_spec.js b/test/unit/util_spec.js index c5a9e07da..9d96e118e 100644 --- a/test/unit/util_spec.js +++ b/test/unit/util_spec.js @@ -18,6 +18,7 @@ import { bytesToString, createValidAbsoluteUrl, getModificationDate, + getUuid, string32, stringToBytes, stringToPDFString, @@ -248,4 +249,12 @@ describe("util", function () { expect(getModificationDate(date)).toEqual("31410609020653"); }); }); + + describe("getUuid", function () { + it("should get uuid string", function () { + const uuid = getUuid(); + expect(typeof uuid).toEqual("string"); + expect(uuid.length).toBeGreaterThanOrEqual(32); + }); + }); });