All files / apps/developer-portal/tools/collect graph.ts

75% Statements 15/20
100% Branches 4/4
83.33% Functions 10/12
75% Lines 15/20

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                                          2x 8x   2x       2x   4x   2x 5x         9x 3x 1x   9x 3x     3x   2x     2x                        
import { mkdir, readFile } from "node:fs/promises";
import { resolve } from "node:path";
import type { ProjectNode } from "#layers/snapshot/shared/types/ProjectNode.ts";
import type { ProjectsArtifact } from "#layers/snapshot/shared/types/ProjectsArtifact.ts";
import { SNAPSHOT_DIR } from "../lib/paths.ts";
import { run } from "../lib/run.ts";
 
interface RawGraph {
    graph: {
        nodes: Record<
            string,
            {
                name: string;
                data: { root: string; tags?: string[]; targets?: Record<string, unknown> };
            }
        >;
        dependencies: Record<string, { source: string; target: string; type: string }[]>;
    };
}
 
/** Nx auto-adds `npm:private`; the tag table only ever talks about `type:` and `scope:`. */
export const isDeclaredTag = (tag: string): boolean =>
    tag.startsWith("type:") || tag.startsWith("scope:");
 
export const normalizeGraph = (
    raw: RawGraph,
    generatedAt: string,
): Omit<ProjectsArtifact, "retired"> => {
    const edges = Object.values(raw.graph.dependencies)
        .flat()
        .filter((edge) => edge.target in raw.graph.nodes);
 
    const projects: ProjectNode[] = Object.values(raw.graph.nodes)
        .map((node) => ({
            name: node.name,
            root: node.data.root,
            tags: (node.data.tags ?? []).filter(isDeclaredTag),
            dependsOn: edges
                .filter((edge) => edge.source === node.name)
                .map((edge) => edge.target)
                .sort((a, b) => a.localeCompare(b)),
            dependedOnBy: edges
                .filter((edge) => edge.target === node.name)
                .map((edge) => edge.source)
                .sort((a, b) => a.localeCompare(b)),
        }))
        .sort((a, b) => a.name.localeCompare(b.name));
 
    return { generatedAt, projects };
};
 
export const collectGraph = async (
    generatedAt: string,
): Promise<Omit<ProjectsArtifact, "retired">> => {
    const jsonPath = resolve(SNAPSHOT_DIR, "nx-graph.raw.json");
 
    // `nx graph --file` resolves a relative path against the workspace root, not cwd, and the JSON
    // branch writes the file directly without creating its parent.
    await mkdir(SNAPSHOT_DIR, { recursive: true });
    await run("pnpm", ["exec", "nx", "graph", "--file", jsonPath]);
 
    return normalizeGraph(JSON.parse(await readFile(jsonPath, "utf8")) as RawGraph, generatedAt);
};