Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix JS value to Dart conversion when receiving from a web socket #298

Merged
merged 10 commits into from
Dec 9, 2023
10 changes: 7 additions & 3 deletions lib/html.dart
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,17 @@ class HtmlWebSocketChannel extends StreamChannelMixin
}

void _innerListen(MessageEvent event) {
// Event data will be ArrayBuffer, Blob, or String.
final eventData = event.data;
Object? data;
if (eventData.typeofEquals('object') &&
final Object? data;
if (eventData.typeofEquals('string')) {
data = (eventData as JSString).toDart;
} else if (eventData.typeofEquals('object') &&
(eventData as JSObject).instanceOfString('ArrayBuffer')) {
data = (eventData as JSArrayBuffer).toDart.asUint8List();
} else {
data = event.data;
// Blobs are passed directly.
data = eventData;
}
_controller.local.sink.add(data);
}
Expand Down
11 changes: 9 additions & 2 deletions test/html_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,19 @@ import 'dart:js_interop';
import 'dart:typed_data';

import 'package:async/async.dart';
import 'package:stream_channel/stream_channel.dart';
osa1 marked this conversation as resolved.
Show resolved Hide resolved
import 'package:test/test.dart';
import 'package:web/helpers.dart' hide BinaryType;
import 'package:web_socket_channel/html.dart';
import 'package:web_socket_channel/src/web_helpers.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

extension on StreamChannel {
/// Handles the Wasm case where the runtime type is actually [double] instead
/// of the JS case where its [int].
Future<int> get firstAsInt async => ((await stream.first) as num).toInt();
}

void main() {
late int port;
setUpAll(() async {
Expand All @@ -35,7 +42,7 @@ void main() {
}
''', stayAlive: true);

port = await channel.stream.first as int;
port = await channel.firstAsInt;
});

test('communicates using an existing WebSocket', () async {
Expand Down Expand Up @@ -169,7 +176,7 @@ void main() {
// TODO(nweiz): Make this channel use a port number that's guaranteed to be
// invalid.
final channel = HtmlWebSocketChannel.connect(
'ws://localhost:${await serverChannel.stream.first}');
'ws://localhost:${await serverChannel.firstAsInt}');
expect(channel.ready, throwsA(isA<WebSocketChannelException>()));
expect(channel.stream.toList(), throwsA(isA<WebSocketChannelException>()));
});
Expand Down