🌳
pt0/sharedF/randomBytesF.mts
1const urlSafeCharset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
3export const randomUrlSafeBytes = (noBytes: number): string => {
4 const maxUnbiased = 256 - (256 % urlSafeCharset.length) // 248 for 62 chars
5 const result: string[] = []
6 while (result.length < noBytes) {
7 const buf = new Uint8Array(noBytes - result.length)
8 crypto.getRandomValues(buf)
9 for (const v of buf) {
10 if (v < maxUnbiased && result.length < noBytes) result.push(urlSafeCharset[v % urlSafeCharset.length])
11 }
12 }
13 return result.join('')