decode static method

WsFrame decode(
  1. String text
)

Parses a control frame.

Throws FormatException on anything malformed or from an incompatible protocol version — a hub must not guess at frames it does not understand.

Implementation

static WsFrame decode(String text) {
  final Object? raw = jsonDecode(text);
  if (raw is! Map<String, dynamic>) {
    throw const FormatException('Control frame must be a JSON object');
  }
  final version = raw['v'];
  if (version != wsProtocolVersion) {
    throw FormatException(
      'Unsupported protocol version $version '
      '(this build speaks $wsProtocolVersion)',
    );
  }
  final typeName = raw['t'];
  final type = WsControl.values.where((c) => c.name == typeName).firstOrNull;
  if (type == null) {
    throw FormatException('Unknown control frame type: $typeName');
  }
  final payload = raw['p'];
  return WsFrame(type, payload is Map<String, dynamic> ? payload : const {});
}