Skip to content

Docker Compose Validator — JavaScript source

Validate a compose file in the browser: image or build per service, port syntax and ranges, environment shape, volumes, and the depends_on graph with cycle detection. Runs locally with a shareable link.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// compose-validator — structural checks for a Docker Compose file. JavaScript
// port (canonical TS: src/lib/compose-validator.ts; Go twin:
// cli/compose-validator). Checks: root/services mappings, per-service image or
// build, port syntax ("8080", "80:8080", "127.0.0.1:80:8080", "6053:53/udp"),
// environment shape (mapping or KEY=value list), volumes lists, depends_on
// references and acyclicity — same rules, paths and message texts as the TS
// contract. The canonical lib parses with the npm `yaml` package; here, as in
// every port of this set, a minimal hand-rolled parser covers the compose
// subset instead: block mappings/sequences, single-line flow collections,
// quoted and plain scalars, comments. Anchors/aliases/merge keys, block
// scalars (| >), multi-line plain scalars and multi-document streams are
// outside the subset. Never throws; parse errors travel in result.error.
'use strict';

const INT_RE = /^[-+]?[0-9]+$/;
const FLOAT_RE = /^[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?$/;

function plainScalar(t) {
  if (t === '' || t === '~' || t === 'null' || t === 'Null' || t === 'NULL') return null;
  if (t === 'true' || t === 'True' || t === 'TRUE') return true;
  if (t === 'false' || t === 'False' || t === 'FALSE') return false;
  if (INT_RE.test(t) || FLOAT_RE.test(t)) return Number(t);
  return t;
}

function quotedAt(s, i) {
  const q = s[i];
  i += 1;
  let out = '';
  while (i < s.length) {
    const ch = s[i];
    if (q === '"' && ch === '\\') {
      const nxt = s[i + 1] || '';
      out += ({ n: '\n', t: '\t', r: '\r' })[nxt] || nxt;
      i += 2;
    } else if (ch === q) {
      if (q === "'" && s[i + 1] === "'") { out += "'"; i += 2; } else return [out, i + 1];
    } else { out += ch; i += 1; }
  }
  throw new Error('Invalid YAML: unterminated quoted scalar');
}

function flowAt(s, i) {
  while (s[i] === ' ') i += 1;
  if (s[i] === '[') {
    const out = [];
    i += 1;
    for (;;) {
      while (s[i] === ' ') i += 1;
      if (i >= s.length) throw new Error('Invalid YAML: unterminated flow sequence');
      if (s[i] === ']') return [out, i + 1];
      let v;
      [v, i] = flowAt(s, i);
      out.push(v);
      while (i < s.length && (s[i] === ' ' || s[i] === ',')) i += 1;
    }
  }
  if (s[i] === '{') {
    const out = {};
    i += 1;
    for (;;) {
      while (s[i] === ' ') i += 1;
      if (i >= s.length) throw new Error('Invalid YAML: unterminated flow mapping');
      if (s[i] === '}') return [out, i + 1];
      let k;
      if (s[i] === '"' || s[i] === "'") {
        [k, i] = quotedAt(s, i);
      } else {
        let j = i;
        while (j < s.length && s[j] !== ':' && s[j] !== ',' && s[j] !== '}') j += 1;
        if (s[j] !== ':') throw new Error('Invalid YAML: flow mapping entry without a colon');
        k = s.slice(i, j).trim();
        i = j + 1;
      }
      while (s[i] === ' ') i += 1;
      let v = null;
      if (i < s.length && s[i] !== ',' && s[i] !== '}') [v, i] = flowAt(s, i);
      out[k] = v;
      while (i < s.length && (s[i] === ' ' || s[i] === ',')) i += 1;
    }
  }
  if (s[i] === '"' || s[i] === "'") return quotedAt(s, i);
  let j = i;
  while (j < s.length && s[j] !== ',' && s[j] !== ']' && s[j] !== '}') j += 1;
  return [plainScalar(s.slice(i, j).trim()), j];
}

function keySplit(s) {
  if (s[0] === '"' || s[0] === "'") {
    let key, j;
    try { [key, j] = quotedAt(s, 0); } catch { return null; }
    const rest = s.slice(j).replace(/^ +/, '');
    return rest[0] === ':' ? [key, rest.slice(1)] : null;
  }
  for (let j = 0; j < s.length; j++) {
    if (s[j] === ':' && (j + 1 === s.length || s[j + 1] === ' ')) {
      return [s.slice(0, j).replace(/ +$/, ''), s.slice(j + 1)];
    }
  }
  return null;
}

function contentLines(text) {
  const out = [];
  for (const raw of text.split('\n')) {
    const crlf = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
    const indented = crlf.replace(/^ +/, '');
    const indent = crlf.length - indented.length;
    const body = indented.replace(/ +$/, '');
    if (body === '' || body.startsWith('#') || body.startsWith('%') || body === '---') continue;
    if (crlf.slice(0, indent).includes('\t')) throw new Error('Invalid YAML: tab in indentation');
    out.push([indent, body]);
  }
  return out;
}

function isItem(s) { return s === '-' || s.startsWith('- '); }

function blockAt(ls, i, indent) {
  if (isItem(ls[i][1])) {
    const out = [];
    while (i < ls.length && ls[i][0] === indent && isItem(ls[i][1])) {
      const content = ls[i][1].slice(2);
      let v;
      if (content.trim() === '' || content.trimStart().startsWith('#')) {
        i += 1;
        if (i < ls.length && ls[i][0] > indent) [v, i] = blockAt(ls, i, ls[i][0]);
        else v = null;
      } else {
        ls[i] = [indent + 2, content];
        [v, i] = blockAt(ls, i, indent + 2);
      }
      out.push(v);
    }
    return [out, i];
  }
  if (keySplit(ls[i][1]) === null) return [inlineValue(ls[i][1]), i + 1];
  const out = {};
  while (i < ls.length && ls[i][0] === indent && !isItem(ls[i][1]) && keySplit(ls[i][1]) !== null) {
    const [key, rest0] = keySplit(ls[i][1]);
    const rest = rest0.trim();
    i += 1;
    if (rest !== '') out[key] = inlineValue(rest);
    else if (i < ls.length && ls[i][0] > indent) {
      const [v, next] = blockAt(ls, i, ls[i][0]);
      out[key] = v;
      i = next;
    } else if (i < ls.length && ls[i][0] === indent && isItem(ls[i][1])) {
      const [v, next] = blockAt(ls, i, indent);
      out[key] = v;
      i = next;
    } else out[key] = null;
  }
  return [out, i];
}

function inlineValue(rest) {
  if (rest[0] === '[' || rest[0] === '{') {
    const [v, j] = flowAt(rest, 0);
    if (rest.slice(j).replace(/[ #]/g, '') !== '') throw new Error('Invalid YAML: trailing content after flow value');
    return v;
  }
  if (rest[0] === '"' || rest[0] === "'") {
    const [v, j] = quotedAt(rest, 0);
    if (rest.slice(j).replace(/[ #]/g, '') !== '') throw new Error('Invalid YAML: trailing content after quoted value');
    return v;
  }
  const cut = rest.indexOf(' #');
  return plainScalar((cut >= 0 ? rest.slice(0, cut) : rest).trim());
}

function parseYaml(text) {
  const ls = contentLines(text);
  if (ls.length === 0) return null;
  const [v, i] = blockAt(ls, 0, ls[0][0]);
  if (i !== ls.length) throw new Error('Invalid YAML: inconsistent indentation');
  return v;
}

function isMap(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); }

/** Port entries: "8080", "80:8080", "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp". */
function portIssue(entry) {
  if (typeof entry === 'number') {
    if (!Number.isInteger(entry)) return 'port must be a string or integer';
    if (entry < 0 || entry > 65535) return `port ${entry} out of range 0-65535`;
    return null;
  }
  if (typeof entry !== 'string') return 'port must be a string or integer';
  const proto = entry.includes('/') ? entry.slice(entry.indexOf('/') + 1) : '';
  if (proto !== '' && proto !== 'tcp' && proto !== 'udp') return `unknown protocol "${proto}" (use tcp or udp)`;
  const body = proto === '' ? entry : entry.slice(0, entry.indexOf('/'));
  const parts = body.split(':');
  // Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
  if (!parts.every((p) => /^\d+$/.test(p))) return null;
  if (parts.length < 1 || parts.length > 3) return 'port must have 1-3 colon-separated parts';
  for (const p of parts) {
    if (Number(p) < 0 || Number(p) > 65535) return `port ${p} out of range 0-65535`;
  }
  return null;
}

function check(root, out) {
  const push = (path, message) => out.push({ path, message });
  if (!isMap(root)) { push('$', 'compose root must be a mapping'); return; }
  const services = root.services;
  if (!isMap(services)) { push('$.services', 'missing or invalid "services" mapping'); return; }
  const ids = Object.keys(services);
  if (ids.length === 0) push('$.services', 'services must not be empty');
  for (const id of ids) {
    const svc = services[id];
    const at = `$.services.${id}`;
    if (!isMap(svc)) { push(at, 'service must be a mapping'); continue; }
    if (svc.image === undefined && svc.build === undefined) push(at, 'service needs image or build');
    if (svc.ports !== undefined) {
      if (!Array.isArray(svc.ports)) push(`${at}.ports`, 'ports must be a list');
      else svc.ports.forEach((p, i) => { const msg = portIssue(p); if (msg) push(`${at}.ports[${i}]`, msg); });
    }
    if (svc.environment !== undefined) {
      const env = svc.environment;
      if (isMap(env)) {
        for (const [k, v] of Object.entries(env)) {
          if (v !== null && typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') {
            push(`${at}.environment.${k}`, 'environment values must be scalars');
          }
        }
      } else if (Array.isArray(env)) {
        env.forEach((e, i) => {
          if (typeof e !== 'string' || !/^[^=]+=/.test(e)) {
            push(`${at}.environment[${i}]`, 'list environment entries must look like KEY=value');
          }
        });
      } else push(`${at}.environment`, 'environment must be a mapping or a list');
    }
    if (svc.volumes !== undefined && !Array.isArray(svc.volumes)) push(`${at}.volumes`, 'volumes must be a list');
    if (svc.depends_on !== undefined) {
      const dep = svc.depends_on;
      if (!Array.isArray(dep) && typeof dep !== 'string' && !isMap(dep)) {
        push(`${at}.depends_on`, 'depends_on must be a string, list or mapping');
      } else {
        const names = isMap(dep) ? Object.keys(dep) : Array.isArray(dep) ? dep.map(String) : [dep];
        names.forEach((n, i) => {
          if (!(n in services)) push(`${at}.depends_on[${i}]`, `unknown service "${n}"`);
        });
      }
    }
  }
  // depends_on cycle detection (map-form conditions do not affect the graph).
  const color = new Map();
  const visit = (id, stack) => {
    if (color.get(id) === 2) return;
    if (color.get(id) === 1) {
      const chain = stack.slice(stack.indexOf(id)).concat(id);
      push('$.services', `depends_on cycle: ${chain.join(' -> ')}`);
      return;
    }
    color.set(id, 1);
    const svc = services[id];
    if (isMap(svc) && svc.depends_on !== undefined) {
      const raw = svc.depends_on;
      const names = typeof raw === 'string' ? [raw] : Array.isArray(raw) ? raw : isMap(raw) ? Object.keys(raw) : [];
      for (const n of names) if (typeof n === 'string' && n in services) visit(n, [...stack, id]);
    }
    color.set(id, 2);
  };
  for (const id of ids) visit(id, []);
}

/** Validate a Docker Compose file. */
function validateCompose(raw) {
  if (raw.trim() === '') return { valid: false, issues: [], error: 'A compose document is required' };
  let root;
  try {
    root = parseYaml(raw);
  } catch (e) {
    return { valid: false, issues: [], error: e.message };
  }
  const issues = [];
  check(root, issues);
  return issues.length === 0 ? { valid: true, issues: [], error: null } : { valid: false, issues, error: null };
}

// Example:
// validateCompose('services:\n  web:\n    image: nginx:1.25\n    ports:\n      - "8080:80"\n  db:\n    image: postgres:16\n    depends_on: web').valid
// → true
// validateCompose('services:\n  web:\n    image: nginx\n    ports: ["99999"]').issues
// → [{ path: '$.services.web.ports[0]', message: 'port 99999 out of range 0-65535' }]
// validateCompose('services:\n  a:\n    image: x\n    depends_on: b\n  b:\n    image: y\n    depends_on: a').issues
// → [{ path: '$.services', message: 'depends_on cycle: a -> b -> a' }]

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →