fix: polifyll performance for crypto randomuuid

This commit is contained in:
Amin Yahyaabadi 2025-03-10 01:56:25 -07:00
parent a2dc2bcd46
commit 7fee45544a
7 changed files with 39 additions and 7 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -193,7 +193,8 @@
"util.types",
"web-streams-polyfill",
"timers-browserify",
"fs-extra"
"fs-extra",
"randomuuid-polyfill"
],
"engines": {
"node": ">=12.x",

View File

@ -3,4 +3,4 @@ export * from "crypto"
import * as crypto from "crypto"
export default crypto
export { randomUUID } from "randomuuid-polyfill"
export { randomUUID } from "./randomuuid.mjs"

View File

@ -0,0 +1,31 @@
// from https://www.npmjs.com/package/randomuuid-polyfill
import { performance } from "perf_hooks"
// Adapted from https://stackoverflow.com/a/8809472/2993077
if (!global.crypto?.randomUUID) {
if (!global.crypto) {
global.crypto = {}
}
global.crypto.randomUUID = () => {
let date = new Date().getTime()
let performanceNow = performance.now() * 1000
// cspell:disable-next-line
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, char => {
let random = Math.random() * 16
if (date > 0) {
random = (date + random) % 16 | 0
date = Math.floor(date / 16)
} else {
random = (performanceNow + random) % 16 | 0
performanceNow = Math.floor(performanceNow / 16)
}
return (char === "x" ? random : (random & 0x3 | 0x8)).toString(16)
})
}
}
const randomUUID = global.crypto.randomUUID.bind(global.crypto)
export { randomUUID }