Suite of AT Protocol TypeScript libraries built on web standards
1import * as noble from "@noble/hashes/utils.js";
2import { type SupportedEncodings, toString } from "@atp/bytes";
3import { sha256 } from "./sha.ts";
4
5/** Generate random bytes using noble hashes' randomBytes function. */
6export const randomBytes = noble.randomBytes;
7
8/** Generate random string from {@linkcode randomBytes}. */
9export const randomStr = (
10 byteLength: number,
11 encoding: SupportedEncodings,
12): string => {
13 const bytes = randomBytes(byteLength);
14 return toString(bytes, encoding);
15};
16
17export const randomIntFromSeed = (
18 seed: string,
19 high: number,
20 low = 0,
21): number => {
22 const hash = sha256(seed);
23 const view = new DataView(hash.buffer, hash.byteOffset, hash.byteLength);
24 // Read 6 bytes as big-endian unsigned integer (similar to Buffer.readUintBE(0, 6))
25 let number = 0;
26 for (let i = 0; i < 6; i++) {
27 number = number * 256 + view.getUint8(i);
28 }
29 const range = high - low;
30 const normalized = number % range;
31 return normalized + low;
32};