Skip to content

Commit caaa4d7

Browse files
Check for Node + Dart2JS.
1 parent d5a56dd commit caaa4d7

1 file changed

Lines changed: 26 additions & 9 deletions

File tree

lib/src/core/random_bytes_js.dart

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,29 @@ import 'dart:typed_data';
33

44
import 'package:ipcrypt/src/core/random_bytes_vm.dart' as vm;
55

6+
const bool isWASM = bool.fromEnvironment('dart.tool.dart2wasm');
7+
8+
@JS()
9+
@staticInterop
10+
class Process {}
11+
12+
@JS()
13+
@staticInterop
14+
class Versions {}
15+
16+
@JS('process')
17+
external Process? get _process;
18+
19+
extension on Process {
20+
external Versions? get versions;
21+
}
22+
23+
extension on Versions {
24+
external JSAny get node;
25+
}
26+
27+
bool get isNodeDart2JS => _process?.versions?.node != null && !isWASM;
28+
629
@JS()
730
external NodeCrypto require(final String id);
831

@@ -11,12 +34,6 @@ extension type NodeCrypto._(JSObject _) implements JSObject {
1134
}
1235

1336
/// Generate [size] cryptographically secure random bytes.
14-
Uint8List randomBytes(final int size) {
15-
try {
16-
// Web browser (more commonly used Dart platform than Node.js)
17-
return vm.randomBytes(size);
18-
} catch (_) {
19-
// Node.js
20-
return require('crypto').randomBytes(size).toDart;
21-
}
22-
}
37+
Uint8List randomBytes(final int size) => isNodeDart2JS
38+
? require('crypto').randomBytes(size).toDart
39+
: vm.randomBytes(size);

0 commit comments

Comments
 (0)