From c71e65cbc95e742c847ec0cfe8b9d607354896e9 Mon Sep 17 00:00:00 2001 From: David Angulo Date: Tue, 5 Dec 2023 01:15:45 +0800 Subject: [PATCH] fix: build warning on web --- src/generate-random-bytes.ts | 10 +++++----- src/generate-random-bytes.web.ts | 8 ++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) create mode 100644 src/generate-random-bytes.web.ts diff --git a/src/generate-random-bytes.ts b/src/generate-random-bytes.ts index 09568f7..3cc5709 100644 --- a/src/generate-random-bytes.ts +++ b/src/generate-random-bytes.ts @@ -1,15 +1,15 @@ import { BYTE_LENGTH } from './utils'; export default function generateRandomBytes(): string { - if (typeof window !== 'undefined') { - const buffer = window.crypto.getRandomValues(new Uint8Array(BYTE_LENGTH)); - const bytes = btoa(String.fromCharCode(...new Uint8Array(buffer))); + if (typeof window === 'undefined') { + const buffer = require('crypto').randomBytes(BYTE_LENGTH); + const bytes = buffer.toString('base64'); return bytes; } - const buffer = require('crypto').randomBytes(BYTE_LENGTH); - const bytes = buffer.toString('base64'); + const buffer = window.crypto.getRandomValues(new Uint8Array(BYTE_LENGTH)); + const bytes = btoa(String.fromCharCode(...new Uint8Array(buffer))); return bytes; } diff --git a/src/generate-random-bytes.web.ts b/src/generate-random-bytes.web.ts new file mode 100644 index 0000000..c7fbc5f --- /dev/null +++ b/src/generate-random-bytes.web.ts @@ -0,0 +1,8 @@ +import { BYTE_LENGTH } from './utils'; + +export default function generateRandomBytes(): string { + const buffer = window.crypto.getRandomValues(new Uint8Array(BYTE_LENGTH)); + const bytes = btoa(String.fromCharCode(...new Uint8Array(buffer))); + + return bytes; +}