GitHub Actions Validator — JavaScript source
Check a workflow YAML before you push: on-shape, jobs, runs-on, steps with run or uses, and the needs graph including cycle detection — every issue reported at its path. Runs locally in your browser.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* gh-actions-validator — GitHub Actions workflow structural validator.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno —
* standard library only: the platform ships no YAML parser, so the
* minimal block-map/sequence parser the rule checks need is
* hand-rolled, like the sibling python.py in this directory)
* Source: CosmoDev polyglot showcase port of the `gh-actions-validator`
* tool, ported from src/lib/gh-actions-validator.ts (the canonical
* TypeScript implementation, which parses with the `yaml` npm
* package); Go twin: cli/gh-actions-validator/gh-actions-validator.go
* (yaml.v3). The rule set and message texts are the shared contract.
* License: display source — part of CosmoDev's polyglot tool pages.
*
* Parses a workflow YAML document and checks structural rules: root shape,
* `on:` event shape, jobs with a needs-graph (unknown needs, acyclicity),
* runs-on (unless the job delegates to a reusable workflow via uses:), and
* steps that are exactly one of run/uses. Not checked (by design, mirroring
* the TS header): action versions, expressions (${{ }}) beyond syntax-free
* presence, runner label validity, duplicate YAML keys, `permissions`
* granularity.
*
* The hand-rolled subset covers block mappings/sequences (including child
* sequences at the parent key's indent and `- key: value` inline map items),
* flow sequences/maps, quoted and plain scalars, block scalars | and >
* (clip/strip; folded `>` joins lines with spaces) and comments — real
* workflow files stay inside it. No anchors/aliases, merge keys, multi-doc,
* or complex keys. Scalar resolution is YAML 1.2 as the `yaml` npm package
* and yaml.v3 resolve it: only true/false are booleans, so the unquoted `on`
* key stays a string. Mappings are plain prototype-less objects, so key
* insertion order (JS Object.keys parity) drives issue ordering — the
* needs-cycle message names the DFS chain, pinned to start with the
* first-declared job. Unterminated flow collections raise and surface as the
* fixed 'Invalid YAML' error. Never throws on its own — errors travel in the
* result's `error` field.
*/
const EVENTS = new Set([
'push', 'pull_request', 'pull_request_target', 'workflow_dispatch', 'schedule', 'release',
'issues', 'issue_comment', 'watch', 'fork', 'create', 'delete', 'deployment', 'page_build',
'public', 'pull_request_review', 'pull_request_review_comment', 'push_tag', 'registry_package',
'repository_dispatch', 'status', 'workflow_run', 'check_run', 'check_suite', 'label',
]);
function isMap(v) {
return v !== null && typeof v === 'object' && !Array.isArray(v);
}
/** Own-property test, prototype-safe even for plain-object inputs. */
function has(o, k) {
return Object.prototype.hasOwnProperty.call(o, k);
}
/** `#` starts a comment only at line start or after whitespace; quoted spans are skipped. */
function stripComment(line) {
let out = '';
let quote = null;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (quote) {
out += c;
if (c === quote) quote = null;
continue;
}
if (c === "'" || c === '"') {
quote = c;
out += c;
continue;
}
if (c === '#' && (i === 0 || line[i - 1] === ' ' || line[i - 1] === '\t')) break;
out += c;
}
return out.replace(/[ \t]+$/, '');
}
/** YAML 1.2 core resolution: only true/false are booleans, so unquoted `on` stays a string. */
function resolveScalar(s) {
if (s === 'true' || s === 'True' || s === 'TRUE') return true;
if (s === 'false' || s === 'False' || s === 'FALSE') return false;
if (s === 'null' || s === 'Null' || s === 'NULL' || s === '~') return null;
if (/^[+-]?[0-9]+$/.test(s)) return Number(s);
if (/^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(s)) return Number(s);
return s;
}
function unquote(s) {
if (s.length >= 2 && s[0] === s[s.length - 1] && (s[0] === "'" || s[0] === '"')) {
const body = s.slice(1, -1);
if (s[0] === "'") return body.replace(/''/g, "'");
const esc = { n: '\n', t: '\t', r: '\r', '"': '"', '\\': '\\' };
let out = '';
let i = 0;
while (i < body.length) {
if (body[i] === '\\' && i + 1 < body.length) {
out += esc[body[i + 1]] !== undefined ? esc[body[i + 1]] : body[i + 1];
i += 2;
} else {
out += body[i];
i += 1;
}
}
return out;
}
return s;
}
/** Split a flow collection body on top-level commas (quotes/brackets respected). */
function splitFlow(s) {
const parts = [];
let depth = 0;
let quote = null;
let cur = '';
for (const c of s) {
if (quote) {
cur += c;
if (c === quote) quote = null;
continue;
}
if (c === "'" || c === '"') quote = c;
else if (c === '[' || c === '{') depth += 1;
else if (c === ']' || c === '}') depth -= 1;
else if (c === ',' && depth === 0) {
parts.push(cur.trim());
cur = '';
continue;
}
cur += c;
}
const last = cur.trim();
if (last) parts.push(last);
return parts;
}
class YamlError extends Error {}
/** Parse a flow collection / scalar. Raises on unterminated flow collections. */
function parseFlow(s) {
if (s.startsWith('[')) {
if (!s.endsWith(']')) throw new YamlError();
return splitFlow(s.slice(1, -1)).map(parseFlow);
}
if (s.startsWith('{')) {
if (!s.endsWith('}')) throw new YamlError();
const m = {};
for (const item of splitFlow(s.slice(1, -1))) {
const [key, rest] = splitKey(item);
m[key] = parseFlow(rest);
}
return m;
}
if (s.length >= 2 && (s[0] === "'" || s[0] === '"') && s[s.length - 1] === s[0]) return unquote(s);
return resolveScalar(s);
}
/** Split 'key: rest' at the first top-level colon (followed by space or end of line). */
function splitKey(text) {
let quote = null;
let depth = 0;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (quote) {
if (c === quote) quote = null;
continue;
}
if (c === "'" || c === '"') quote = c;
else if (c === '[' || c === '{') depth += 1;
else if (c === ']' || c === '}') depth -= 1;
else if (c === ':' && depth === 0 && (i + 1 === text.length || text[i + 1] === ' ' || text[i + 1] === '\t')) {
return [unquote(text.slice(0, i).trim()), text.slice(i + 1).trim()];
}
}
// fallback: quoted key immediately followed by a colon, e.g. 'key':value
if (text[0] === "'" || text[0] === '"') {
const end = text.indexOf(text[0], 1);
if (end !== -1 && end + 1 < text.length && text[end + 1] === ':') {
return [unquote(text.slice(0, end + 1)), text.slice(end + 2).trim()];
}
}
return [unquote(text.trim()), ''];
}
/** Prepare (indent, text) pairs: tabs normalized, `---`/`...` markers, comments, blanks out. */
function prepareLines(raw) {
const lines = [];
for (const rawLine of raw.split('\n')) {
const bare = rawLine.trim();
if (bare === '---' || bare === '...') continue;
const text = stripComment(rawLine.replace(/\t/g, ' '));
if (!text.trim()) continue;
const indent = text.length - text.replace(/^ +/, '').length;
lines.push([indent, text.trim()]);
}
return lines;
}
function isSeqMarker(text) {
return text === '-' || text.startsWith('- ');
}
/** Consume a | or > block scalar body; returns [value, nextI]. */
function blockScalar(lines, i, indent, rest) {
const fold = rest[0] === '>';
const chompStrip = rest.endsWith('-');
const body = [];
let j = i;
while (j < lines.length) {
const [ind, text] = lines[j];
if (ind <= indent) break;
body.push(text);
j += 1;
}
let joined = body.join(fold ? ' ' : '\n');
if (!chompStrip && body.length > 0) joined += '\n';
return [joined, j];
}
/** Resolve a rest-of-line value, consuming block scalar bodies. */
function inlineValue(lines, i, indent, rest) {
if (rest[0] === '|' || rest[0] === '>') return blockScalar(lines, i + 1, indent, rest);
return [parseFlow(rest), i + 1];
}
function parseMap(lines, i, indent) {
const m = {};
while (i < lines.length && lines[i][0] === indent && !isSeqMarker(lines[i][1])) {
const [key, rest] = splitKey(lines[i][1]);
if (rest) {
[m[key], i] = inlineValue(lines, i, indent, rest);
} else {
const j = i + 1;
if (j < lines.length && lines[j][0] > indent) {
[m[key], i] = parseBlock(lines, j, lines[j][0]);
} else if (j < lines.length && lines[j][0] === indent && isSeqMarker(lines[j][1])) {
[m[key], i] = parseSeq(lines, j, indent);
} else {
m[key] = null;
i = j;
}
}
}
return [m, i];
}
function parseSeq(lines, i, indent) {
const seq = [];
while (i < lines.length && lines[i][0] === indent && isSeqMarker(lines[i][1])) {
const text = lines[i][1];
const rest = text.slice(1).replace(/^ +/, '');
const restCol = indent + (text.length - rest.length);
if (!rest) {
const j = i + 1;
if (j < lines.length && lines[j][0] > indent) {
[seq[seq.length], i] = parseBlock(lines, j, lines[j][0]);
} else {
seq.push(null);
i = j;
}
} else if ((rest.includes(':') && splitKey(rest)[1] !== '') || rest.endsWith(':')) {
// inline map start ("- key: value", more pairs may follow at restCol)
const m = {};
const [key, r2] = splitKey(rest);
if (r2) {
[m[key]] = inlineValue(lines, i, restCol, r2);
} else {
const j = i + 1;
if (j < lines.length && lines[j][0] > restCol) {
[m[key]] = parseBlock(lines, j, lines[j][0]);
} else {
m[key] = null;
}
}
i += 1;
while (i < lines.length && lines[i][0] === restCol && !isSeqMarker(lines[i][1])) {
const [k2, r3] = splitKey(lines[i][1]);
if (r3) {
[m[k2]] = inlineValue(lines, i, restCol, r3);
i += 1;
} else {
const j = i + 1;
if (j < lines.length && lines[j][0] > restCol) {
[m[k2], i] = parseBlock(lines, j, lines[j][0]);
} else {
m[k2] = null;
i = j;
}
}
}
seq.push(m);
} else {
[seq[seq.length], i] = inlineValue(lines, i, restCol, rest);
}
}
return [seq, i];
}
function parseBlock(lines, i, indent) {
if (i >= lines.length || lines[i][0] < indent) return [null, i];
if (isSeqMarker(lines[i][1])) return parseSeq(lines, i, indent);
return parseMap(lines, i, indent);
}
function parseYaml(raw) {
const lines = prepareLines(raw);
if (lines.length === 0) return null;
const [root] = parseBlock(lines, 0, lines[0][0]);
return root;
}
/** Validate a parsed workflow document; the TS check() in JS form. */
function check(root, out) {
if (!isMap(root)) {
out.push({ path: '$', message: 'workflow root must be a mapping' });
return;
}
if (!has(root, 'jobs')) out.push({ path: '$', message: 'missing required key "jobs"' });
if (!has(root, 'on')) out.push({ path: '$', message: 'missing required key "on"' });
// on: string | array of strings | map of event -> config
if (has(root, 'on')) {
const on = root.on;
if (typeof on === 'string') {
if (!EVENTS.has(on)) out.push({ path: '$.on', message: `unknown event "${on}"` });
} else if (Array.isArray(on)) {
on.forEach((e, i) => {
if (typeof e !== 'string') out.push({ path: `$.on[${i}]`, message: 'event list entries must be strings' });
else if (!EVENTS.has(e)) out.push({ path: `$.on[${i}]`, message: `unknown event "${e}"` });
});
} else if (isMap(on)) {
for (const name of Object.keys(on)) {
if (!EVENTS.has(name)) out.push({ path: `$.on.${name}`, message: `unknown event "${name}"` });
const cfg = on[name];
if (isMap(cfg) && has(cfg, 'branches') && !Array.isArray(cfg.branches) && typeof cfg.branches !== 'string') {
out.push({ path: `$.on.${name}.branches`, message: 'branches must be a string or a list' });
}
}
} else {
out.push({ path: '$.on', message: 'on must be a string, list or mapping' });
}
}
const jobs = root.jobs;
if (!isMap(jobs)) {
if (has(root, 'jobs')) out.push({ path: '$.jobs', message: 'jobs must be a mapping' });
return;
}
const jobIds = Object.keys(jobs);
if (jobIds.length === 0) out.push({ path: '$.jobs', message: 'jobs must not be empty' });
for (const id of jobIds) {
const job = jobs[id];
const at = `$.jobs.${id}`;
if (!isMap(job)) {
out.push({ path: at, message: 'job must be a mapping' });
continue;
}
const reusable = typeof job.uses === 'string';
if (!reusable && typeof job['runs-on'] !== 'string' && !Array.isArray(job['runs-on'])) {
out.push({ path: `${at}.runs-on`, message: 'job needs runs-on (or a reusable-workflow uses)' });
}
if (!reusable && !has(job, 'steps')) {
out.push({ path: `${at}.steps`, message: 'job needs steps' });
}
if (Array.isArray(job.steps)) {
if (job.steps.length === 0) out.push({ path: `${at}.steps`, message: 'steps must not be empty' });
job.steps.forEach((step, i) => {
const sat = `${at}.steps[${i}]`;
if (!isMap(step)) {
out.push({ path: sat, message: 'step must be a mapping' });
return;
}
const hasRun = typeof step.run === 'string';
const hasUses = typeof step.uses === 'string';
if (!hasRun && !hasUses) out.push({ path: sat, message: 'step needs run or uses' });
if (hasRun && hasUses) out.push({ path: sat, message: 'step has both run and uses - pick one' });
});
} else if (has(job, 'steps')) {
out.push({ path: `${at}.steps`, message: 'steps must be a list' });
}
if (has(job, 'needs')) {
const needs = Array.isArray(job.needs) ? job.needs : [job.needs];
if (!Array.isArray(job.needs) && typeof job.needs !== 'string') {
out.push({ path: `${at}.needs`, message: 'needs must be a string or a list' });
} else {
needs.forEach((n, i) => {
if (typeof n !== 'string') out.push({ path: `${at}.needs[${i}]`, message: 'needs entries must be strings' });
else if (!has(jobs, n)) out.push({ path: `${at}.needs[${i}]`, message: `unknown job "${n}"` });
});
}
}
}
// needs-graph cycle detection: DFS from every job over declared, known edges.
const color = new Map(); // 1 = visiting, 2 = done
const visit = (id, stack) => {
if (color.get(id) === 2) return;
if (color.get(id) === 1) {
const from = stack.indexOf(id);
out.push({ path: '$.jobs', message: `needs cycle: ${stack.slice(from).concat(id).join(' -> ')}` });
return;
}
color.set(id, 1);
const job = has(jobs, id) ? jobs[id] : null;
if (isMap(job) && (typeof job.needs === 'string' || Array.isArray(job.needs))) {
const needs = Array.isArray(job.needs) ? job.needs : [job.needs];
for (const n of needs) {
if (typeof n === 'string' && has(jobs, n)) visit(n, [...stack, id]);
}
}
color.set(id, 2);
};
for (const id of jobIds) visit(id, []);
}
/** Validate a GitHub Actions workflow YAML document. */
export function validateGhActions(raw) {
if (!raw.trim()) return { valid: false, issues: [], error: 'A workflow document is required' };
let root;
try {
root = parseYaml(raw);
} catch {
return { valid: false, issues: [], error: 'Invalid YAML' };
}
const issues = [];
check(root, issues);
return issues.length === 0
? { valid: true, issues: [], error: null }
: { valid: false, issues, error: null };
}
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 →