Skip to content

Commit

Permalink
Immediately resolve crypto in browser environment. Resolves #1
Browse files Browse the repository at this point in the history
  • Loading branch information
coreybutler committed Feb 14, 2022
1 parent 6e7a063 commit 9418189
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ngnjs/libdata",
"version": "1.0.0-alpha.2",
"version": "1.0.0-alpha.3",
"description": "A plugin module for NGN.",
"main": "src/index.js",
"module": "index.js",
Expand Down
17 changes: 10 additions & 7 deletions src/identifiers/nanoid.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

// Cross-runtime buffer fill
let fill
;(async () => {
const available = globalThis.crypto !== undefined
const CRYPTO = await (globalThis.crypto || import('crypto'))
fill = size => available ? CRYPTO.getRandomValues(new Uint8Array(size)) : CRYPTO.randomBytes(size)
})()
let CRYPTO = globalThis.crypto
if (!CRYPTO) {
;(async () => {
CRYPTO = await import('crypto')
fill = size => CRYPTO.randomBytes(size)
})()
} else {
fill = size => CRYPTO.getRandomValues(new Uint8Array(size))
}

function NANOID (size = 21) {
export default function NANOID (size = 21) {
const bytes = fill(size)
let id = ''

Expand All @@ -21,6 +25,5 @@ function NANOID (size = 21) {
}

export {
NANOID as default,
NANOID
}

0 comments on commit 9418189

Please sign in to comment.