File size: 1,245 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import stripAnsi from 'strip-ansi';
import type { SessionMetrics } from '../telemetry/uiTelemetry.js';
import { getErrorType } from '../utils/errors.js';
import type { JsonError, JsonOutput } from './types.js';

export class JsonFormatter {
  format(
    sessionId?: string,
    response?: string,
    stats?: SessionMetrics,
    error?: JsonError,
    warnings?: string[],
  ): string {
    const output: JsonOutput = {};

    if (sessionId) {
      output.session_id = sessionId;
    }

    if (response !== undefined) {
      output.response = stripAnsi(response);
    }

    if (stats) {
      output.stats = stats;
    }

    if (error) {
      output.error = error;
    }

    if (warnings && warnings.length > 0) {
      output.warnings = warnings.map((w) => stripAnsi(w));
    }

    return JSON.stringify(output, null, 2);
  }

  formatError(
    error: Error,
    code?: string | number,
    sessionId?: string,
  ): string {
    const jsonError: JsonError = {
      type: getErrorType(error),
      message: stripAnsi(error.message),
      ...(code && { code }),
    };

    return this.format(sessionId, undefined, undefined, jsonError);
  }
}