All files / apps/developer-portal/layers/workflows/server/utils workflowFiles.ts

95.83% Statements 23/24
50% Branches 1/2
91.66% Functions 11/12
100% Lines 19/19

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                        3x   94x 14x   3x         104x 104x   1x               3x 47x 47x 47x       108x 61x   47x 47x 50x 7x     47x       7x        
import { readdir, readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { parse } from "yaml";
import type { ParsedFile } from "../../shared/workflows.ts";
 
interface WorkflowFiles {
    templates: ParsedFile[];
    projects: ParsedFile[];
    /** Keyed by project id; a project that was never synced has no entry. */
    snapshots: Record<string, ParsedFile>;
}
 
const SNAPSHOT_SUFFIX = ".snapshot.json";
 
const namesIn = async (dir: string): Promise<string[]> =>
    (await readdir(dir).catch(() => [] as string[])).sort((a, b) => a.localeCompare(b));
 
const parseFile = async (
    dir: string,
    file: string,
    parser: (text: string) => unknown,
): Promise<ParsedFile> => {
    try {
        return { file, ok: true, value: parser(await readFile(resolve(dir, file), "utf8")) };
    } catch (cause) {
        return { file, ok: false, error: cause instanceof Error ? cause.message : "unreadable" };
    }
};
 
/**
 * Every file under `data/workflows`, parsed but not yet checked. Node-only and free of Nitro
 * globals, because the server route and the `tools/` invariant pass both read through it.
 */
export const readWorkflowFiles = async (dir: string): Promise<WorkflowFiles> => {
    const templatesDir = resolve(dir, "templates");
    const projectsDir = resolve(dir, "projects");
    const [templateNames, projectNames] = await Promise.all([
        namesIn(templatesDir),
        namesIn(projectsDir),
    ]);
    const yamlIn = (names: string[]) => names.filter((name) => name.endsWith(".yaml"));
    const snapshotNames = projectNames.filter((name) => name.endsWith(SNAPSHOT_SUFFIX));
 
    const [templates, projects, snapshots] = await Promise.all([
        Promise.all(yamlIn(templateNames).map((file) => parseFile(templatesDir, file, parse))),
        Promise.all(yamlIn(projectNames).map((file) => parseFile(projectsDir, file, parse))),
        Promise.all(snapshotNames.map((file) => parseFile(projectsDir, file, JSON.parse))),
    ]);
 
    return {
        templates,
        projects,
        snapshots: Object.fromEntries(
            snapshots.map((parsed) => [parsed.file.slice(0, -SNAPSHOT_SUFFIX.length), parsed]),
        ),
    };
};