All files / src/preview compose-generator.ts

98.07% Statements 51/52
79.41% Branches 27/34
100% Functions 4/4
97.95% Lines 48/49

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                                                                                          9x             9x     9x 10x 10x           10x 9x 8x         1x             1x 1x       10x 1x       10x       10x       9x 9x             9x     9x     9x   9x 9x     9x   9x                   18x   18x 23x 21x               18x 4x 3x 1x     18x   18x 21x 18x 18x 18x     3x 3x 3x 3x       18x 18x                           7x                 7x 2x     7x    
/**
 * Docker Compose Generator
 *
 * Generates docker-compose.preview.yml and Caddyfile for preview deployments.
 * All services share a Docker network; only Caddy publishes a host port.
 */
 
import yaml from 'js-yaml';
import type { PreviewConfig, PreviewServiceConfig } from './types.js';
import { PREVIEW_LABELS } from './types.js';
 
export interface ComposeGeneratorOptions {
  projectPath: string;
  port: number;
  deploymentId: string;
  labels: Record<string, string>;
}
 
interface ComposeService {
  build?: { context: string; dockerfile: string } | string;
  image?: string;
  environment?: Record<string, string>;
  volumes?: string[];
  labels?: Record<string, string>;
  networks?: string[];
  depends_on?: string[];
}
 
interface ComposeFile {
  services: Record<string, ComposeService>;
  networks: Record<string, { driver: string }>;
}
 
/**
 * Generate a Docker Compose YAML string for the preview deployment.
 *
 * Structure:
 * - User-defined services with build contexts
 * - Caddy reverse proxy publishing the single host port
 * - Shared `preview` network
 */
export function generateComposeFile(
  config: PreviewConfig,
  opts: ComposeGeneratorOptions,
): string {
  const compose: ComposeFile = {
    services: {},
    networks: {
      preview: { driver: 'bridge' },
    },
  };
 
  const serviceNames: string[] = [];
 
  // Add user-defined services
  for (const [name, svc] of Object.entries(config.services)) {
    serviceNames.push(name);
    const service: ComposeService = {
      labels: { ...opts.labels },
      networks: ['preview'],
    };
 
    // Build config
    if (svc.build) {
      if (typeof svc.build === 'string') {
        service.build = {
          context: opts.projectPath,
          dockerfile: svc.build === '.' ? 'Dockerfile' : svc.build,
        };
      } else {
        service.build = {
          context: svc.build.context.startsWith('/')
            ? svc.build.context
            : `${opts.projectPath}/${svc.build.context}`,
          dockerfile: svc.build.dockerfile,
        };
      }
    E} else if (svc.image) {
      service.image = svc.image;
    }
 
    // Environment
    if (svc.env && Object.keys(svc.env).length > 0) {
      service.environment = svc.env;
    }
 
    // Volumes
    Iif (svc.volumes && svc.volumes.length > 0) {
      service.volumes = svc.volumes;
    }
 
    compose.services[name] = service;
  }
 
  // Generate and add Caddy proxy service
  const caddyfile = generateCaddyfile(config);
  const caddyService: ComposeService = {
    image: 'caddy:2-alpine',
    networks: ['preview'],
    labels: { ...opts.labels },
  };
 
  // Caddy publishes the single host port
  (caddyService as Record<string, unknown>).ports = [`${opts.port}:80`];
 
  // Mount Caddyfile via inline config
  (caddyService as Record<string, unknown>).command = ['caddy', 'run', '--config', '/etc/caddy/Caddyfile'];
 
  // Caddy config will be written to the deployment directory and mounted
  (caddyService as Record<string, unknown>).volumes = ['./Caddyfile:/etc/caddy/Caddyfile:ro'];
 
  Eif (serviceNames.length > 0) {
    caddyService.depends_on = serviceNames;
  }
 
  compose.services['caddy-proxy'] = caddyService;
 
  return yaml.dump(compose, { lineWidth: 120, noRefs: true });
}
 
/**
 * Generate a Caddyfile from route mappings in the preview config.
 *
 * Routes are sorted by specificity (longest path first) to ensure
 * more specific routes match before catch-all.
 */
export function generateCaddyfile(config: PreviewConfig): string {
  const routes: Array<{ name: string; route: string; port: number }> = [];
 
  for (const [name, svc] of Object.entries(config.services)) {
    if (svc.internal) continue;
    routes.push({
      name,
      route: svc.route ?? '/',
      port: svc.port,
    });
  }
 
  // Sort by route specificity (longer paths first, root last)
  routes.sort((a, b) => {
    if (a.route === '/') return 1;
    if (b.route === '/') return -1;
    return b.route.length - a.route.length;
  });
 
  const lines: string[] = [':80 {'];
 
  for (const route of routes) {
    if (route.route === '/') {
      lines.push(`  handle {`);
      lines.push(`    reverse_proxy ${route.name}:${route.port}`);
      lines.push(`  }`);
    } else {
      // Strip trailing slash for handle_path
      const path = route.route.endsWith('/') ? route.route.slice(0, -1) : route.route;
      lines.push(`  handle_path ${path}/* {`);
      lines.push(`    reverse_proxy ${route.name}:${route.port}`);
      lines.push(`  }`);
    }
  }
 
  lines.push('}');
  return lines.join('\n');
}
 
/**
 * Generate compose labels for a preview deployment.
 */
export function generateLabels(opts: {
  initiativeId: string;
  phaseId?: string;
  projectId: string;
  branch: string;
  port: number;
  previewId: string;
}): Record<string, string> {
  const labels: Record<string, string> = {
    [PREVIEW_LABELS.preview]: 'true',
    [PREVIEW_LABELS.initiativeId]: opts.initiativeId,
    [PREVIEW_LABELS.projectId]: opts.projectId,
    [PREVIEW_LABELS.branch]: opts.branch,
    [PREVIEW_LABELS.port]: String(opts.port),
    [PREVIEW_LABELS.previewId]: opts.previewId,
  };
 
  if (opts.phaseId) {
    labels[PREVIEW_LABELS.phaseId] = opts.phaseId;
  }
 
  return labels;
}