# All files / src/preview docker-client.ts

1.92% Statements 1/52
0% Branches 0/19
0% Functions 0/10
1.92% Lines 1/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207

    8x

     /**
     * Docker Client
     *
     * Thin wrapper around Docker CLI via execa for preview lifecycle management.
     * No SDK dependency — uses `docker compose` subprocess calls.
     */

    import { execa } from 'execa';
    import { createModuleLogger } from '../logger/index.js';
    import { COMPOSE_PROJECT_PREFIX, PREVIEW_LABELS } from './types.js';

    const log = createModuleLogger('preview:docker');

    /**
     * Service status from `docker compose ps`.
     */
    export interface ServiceStatus {
      name: string;
      state: string;
      health: string;
    }

    /**
     * Compose project from `docker compose ls`.
     */
    export interface ComposeProject {
      Name: string;
      Status: string;
      ConfigFiles: string;
    }

    /**
     * Check if Docker is available and running.
     */
    export async function isDockerAvailable(): Promise<boolean> {
      try {
        await execa('docker', ['info'], { timeout: 10000 });
        return true;
      } catch {
        return false;
      }
    }

    /**
     * Start a compose project (build and run in background).
     */
    export async function composeUp(composePath: string, projectName: string): Promise<void> {
      log.info({ composePath, projectName }, 'starting compose project');
      const cwd = composePath.substring(0, composePath.lastIndexOf('/'));

      await execa('docker', [
        'compose',
        '-p', projectName,
        '-f', composePath,
        'up',
        '--build',
        '-d',
      ], {
        cwd,
        timeout: 600000, // 10 minutes for builds
      });
    }

    /**
     * Stop and remove a compose project.
     */
    export async function composeDown(projectName: string): Promise<void> {
      log.info({ projectName }, 'stopping compose project');
      await execa('docker', [
        'compose',
        '-p', projectName,
        'down',
        '--volumes',
        '--remove-orphans',
      ], {
        timeout: 60000,
      });
    }

    /**
     * Get service statuses for a compose project.
     */
    export async function composePs(projectName: string): Promise<ServiceStatus[]> {
      try {
        const result = await execa('docker', [
          'compose',
          '-p', projectName,
          'ps',
          '--format', 'json',
        ], {
          timeout: 15000,
        });

        if (!result.stdout.trim()) {
          return [];
        }

        // docker compose ps --format json outputs one JSON object per line
        const lines = result.stdout.trim().split('\n');
        return lines.map((line) => {
          const container = JSON.parse(line);
          return {
            name: container.Service || container.Name || '',
            state: container.State || 'unknown',
            health: container.Health || 'none',
          };
        });
      } catch (error) {
        log.warn({ projectName, err: error }, 'failed to get compose ps');
        return [];
      }
    }

    /**
     * List all preview compose projects.
     */
    export async function listPreviewProjects(): Promise<ComposeProject[]> {
      try {
        const result = await execa('docker', [
          'compose',
          'ls',
          '--filter', `name=${COMPOSE_PROJECT_PREFIX}`,
          '--format', 'json',
        ], {
          timeout: 15000,
        });

        if (!result.stdout.trim()) {
          return [];
        }

        return JSON.parse(result.stdout);
      } catch (error) {
        log.warn({ err: error }, 'failed to list preview projects');
        return [];
      }
    }

    /**
     * Get container labels for a compose project.
     * Returns labels from the first container that has cw.preview=true.
     */
    export async function getContainerLabels(projectName: string): Promise<Record<string, string>> {
      try {
        const result = await execa('docker', [
          'ps',
          '--filter', `label=${PREVIEW_LABELS.preview}=true`,
          '--filter', `label=com.docker.compose.project=${projectName}`,
          '--format', '{{json .Labels}}',
        ], {
          timeout: 15000,
        });

        if (!result.stdout.trim()) {
          return {};
        }

        // Parse the first line's label string: "key=val,key=val,..."
        const firstLine = result.stdout.trim().split('\n')[0];
        const labelStr = firstLine.replace(/^"|"$/g, '');
        const labels: Record<string, string> = {};

        for (const pair of labelStr.split(',')) {
          const eqIdx = pair.indexOf('=');
          if (eqIdx > 0) {
            const key = pair.substring(0, eqIdx);
            const value = pair.substring(eqIdx + 1);
            if (key.startsWith('cw.')) {
              labels[key] = value;
            }
          }
        }

        return labels;
      } catch (error) {
        log.warn({ projectName, err: error }, 'failed to get container labels');
        return {};
      }
    }

    /**
     * Get the ports of running preview containers by reading their cw.port labels.
     */
    export async function getPreviewPorts(): Promise<number[]> {
      try {
        const result = await execa('docker', [
          'ps',
          '--filter', `label=${PREVIEW_LABELS.preview}=true`,
          '--format', `{{.Label "${PREVIEW_LABELS.port}"}}`,
        ], {
          timeout: 15000,
        });

        if (!result.stdout.trim()) {
          return [];
        }

        return result.stdout
          .trim()
          .split('\n')
          .map((s) => parseInt(s, 10))
          .filter((n) => !isNaN(n));
      } catch {
        return [];
      }
    }