toJson method

Map<String, Object?> toJson()

Encodes this object into a JSON representation.

This method normalizes identifiers and constants for storage efficiency.

Implementation

Map<String, Object?> toJson() {
  final constants =
      {
        ...callsForDefinition.values
            .expand((element) => element)
            .whereType<CallWithArguments>()
            .expand(
              (call) => [
                ...call.positionalArguments,
                ...call.namedArguments.values,
              ],
            )
            .nonNulls,
        ...instancesForDefinition.values
            .expand((element) => element)
            .expand(
              (instance) => {
                ...instance.instanceConstant.fields.values,
                instance.instanceConstant,
              },
            ),
      }.flatten().asMapToIndices;
  final locations =
      {
        ...callsForDefinition.values
            .expand((calls) => calls)
            .map((call) => call.location),
        ...instancesForDefinition.values
            .expand((instances) => instances)
            .map((instance) => instance.location),
      }.asMapToIndices;
  return {
    _metadataKey: metadata.json,
    if (constants.isNotEmpty)
      _constantsKey:
          constants.keys
              .map((constant) => constant.toJson(constants))
              .toList(),
    if (locations.isNotEmpty)
      _locationsKey:
          locations.keys.map((location) => location.toJson()).toList(),
    if (callsForDefinition.isNotEmpty || instancesForDefinition.isNotEmpty)
      _recordingsKey: [
        if (callsForDefinition.isNotEmpty)
          ...callsForDefinition.entries.map(
            (entry) => {
              _definitionKey: entry.key.toJson(),
              _callsKey:
                  entry.value
                      .map((call) => call.toJson(constants, locations))
                      .toList(),
            },
          ),
        if (instancesForDefinition.isNotEmpty)
          ...instancesForDefinition.entries.map(
            (entry) => {
              _definitionKey: entry.key.toJson(),
              _instancesKey:
                  entry.value
                      .map(
                        (instance) => instance.toJson(constants, locations),
                      )
                      .toList(),
            },
          ),
      ],
  };
}