1 | import { toByteArray } from 'base64-js';
|
2 | import { UnavailabilityError } from 'expo-modules-core';
|
3 | import ExpoRandom from './ExpoRandom';
|
4 | const warnIsDeprecated = (functionName) => console.warn(`expo-random is deprecated in favor of expo-crypto: use ExpoCrypto.${functionName}()instead. https://docs.expo.dev/versions/latest/sdk/crypto/`);
|
5 | function assertByteCount(value, methodName) {
|
6 | warnIsDeprecated('assertByteCount');
|
7 | if (typeof value !== 'number' ||
|
8 | isNaN(value) ||
|
9 | Math.floor(value) < 0 ||
|
10 | Math.floor(value) > 1024) {
|
11 | throw new TypeError(`expo-random: ${methodName}(${value}) expected a valid number from range 0...1024`);
|
12 | }
|
13 | }
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | export function getRandomBytes(byteCount) {
|
23 | warnIsDeprecated('getRandomBytes');
|
24 | assertByteCount(byteCount, 'getRandomBytes');
|
25 | const validByteCount = Math.floor(byteCount);
|
26 | if (__DEV__) {
|
27 | if (!global.nativeCallSyncHook || global.__REMOTEDEV__) {
|
28 |
|
29 | const array = new Uint8Array(validByteCount);
|
30 | for (let i = 0; i < validByteCount; i++) {
|
31 | array[i] = Math.floor(Math.random() * 256);
|
32 | }
|
33 | return array;
|
34 | }
|
35 | }
|
36 | if (ExpoRandom.getRandomBytes) {
|
37 | return ExpoRandom.getRandomBytes(validByteCount);
|
38 | }
|
39 | else if (ExpoRandom.getRandomBase64String) {
|
40 | const base64 = ExpoRandom.getRandomBase64String(validByteCount);
|
41 | return toByteArray(base64);
|
42 | }
|
43 | else {
|
44 | throw new UnavailabilityError('expo-random', 'getRandomBytes');
|
45 | }
|
46 | }
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | export async function getRandomBytesAsync(byteCount) {
|
55 | warnIsDeprecated('getRandomBytesAsync');
|
56 | assertByteCount(byteCount, 'getRandomBytesAsync');
|
57 | const validByteCount = Math.floor(byteCount);
|
58 | if (ExpoRandom.getRandomBytesAsync) {
|
59 | return await ExpoRandom.getRandomBytesAsync(validByteCount);
|
60 | }
|
61 | else if (ExpoRandom.getRandomBase64StringAsync) {
|
62 | const base64 = await ExpoRandom.getRandomBase64StringAsync(validByteCount);
|
63 | return toByteArray(base64);
|
64 | }
|
65 | else {
|
66 | throw new UnavailabilityError('expo-random', 'getRandomBytesAsync');
|
67 | }
|
68 | }
|
69 |
|
\ | No newline at end of file |