UNPKG

964 BPlain TextView Raw
1import { UnavailabilityError } from '@unimodules/core';
2import { toByteArray } from 'base64-js';
3
4import ExpoRandom from './ExpoRandom';
5
6function assertByteCount(value: any): void {
7 if (
8 typeof value !== 'number' ||
9 isNaN(value) ||
10 Math.floor(value) < 0 ||
11 Math.floor(value) > 1024
12 ) {
13 throw new TypeError(
14 `expo-random: getRandomBytesAsync(${value}) expected a valid number from range 0...1024`
15 );
16 }
17}
18
19export async function getRandomBytesAsync(byteCount: number): Promise<Uint8Array> {
20 assertByteCount(byteCount);
21 const validByteCount = Math.floor(byteCount);
22 if (ExpoRandom.getRandomBytesAsync) {
23 return await ExpoRandom.getRandomBytesAsync(validByteCount);
24 } else if (ExpoRandom.getRandomBase64StringAsync) {
25 const base64 = await ExpoRandom.getRandomBase64StringAsync(validByteCount);
26 return toByteArray(base64);
27 } else {
28 throw new UnavailabilityError('expo-random', 'getRandomBytesAsync');
29 }
30}