fromJson static method

ZapMessage fromJson(
  1. Map<String, Object?> json
)

Parses json (already decoded) into a typed ZapMessage.

Throws ZapSchemaException — with the validator's path-precise issues — when the message is not structurally valid, or a version-classified exception when zap is not a version this implementation speaks.

Implementation

static ZapMessage fromJson(Map<String, Object?> json) {
  // Version FIRST: a future/mismatched version must never be parsed as
  // a half-understood message (the contract's §2 rule).
  final version = json['zap'];
  if (version != zapProtocolVersion) {
    throw ZapSchemaException(
      'unsupported ZAP protocol version "$version" '
      '(this host speaks $zapProtocolVersion)',
      [
        ZapValidationIssue(
          path: 'zap',
          message: 'must be "$zapProtocolVersion"; got "$version"',
        ),
      ],
      classification: 'version',
    );
  }

  final validation = ZapValidator.validate(json);
  if (!validation.ok) {
    throw ZapSchemaException(
      'message rejected: ${validation.issues.length} schema '
      'violation(s)',
      validation.issues,
      classification: 'schema',
    );
  }

  final type = json['type'] as String;
  return switch (type) {
    'mission' => MissionEnvelope.fromValidated(json),
    'evidence' => EvidencePacket.fromValidated(json),
    'checkpoint' => CheckpointMessage.fromValidated(json),
    'receipt' => ZapReceipt.fromValidated(json),
    'error' => ZapError.fromValidated(json),
    _ => throw ZapSchemaException('unknown message type "$type"', [
      ZapValidationIssue(
        path: 'type',
        message: 'must be one of ${zapMessageTypes.join('|')}',
      ),
    ], classification: 'schema'),
  };
}