import type { AuditOutput, Config, FixOutput, ProjectAudit, ProjectFix, } from "../types.js"; import fs from "fs/promises"; import { promiseExec } from "../utils/helper.js"; export async function getProjectAudits(projects: any[]) { let audits = []; for (let project of projects) { let auditPromise = getAuditPromise(project.path, project.name); audits.push(auditPromise); } return audits; } export async function getProjectFixes(projects: any[], force: boolean) { let fixes = []; for (let project of projects) { let fixPromise = getFixPromise(project.path, project.name, force); fixes.push(fixPromise); } return fixes; } export async function goThroughProjects(config: Config) { let projects = []; try { const entries = await fs.readdir(config.path, { withFileTypes: true }); for (let entry of entries) { if (!entry.isDirectory()) { continue; } let dirFullPath = `${config.path}${entry.name}`; const projectDir = await fs.readdir(dirFullPath); if (projectDir.includes("package.json")) { projects.push({ path: dirFullPath, name: entry.name }); } } return projects; } catch (error) { throw error; } } async function getAuditPromise( path: string, dirname: string, ): Promise { let { stdout } = await promiseExec(`cd "${path}" && npm audit --json`); let output: AuditOutput = JSON.parse(stdout); let project: ProjectAudit = { projectName: dirname, ...output }; if (project.error) { throw new Error( `${dirname} could not be audited, maybe package lock is corrupted`, ); } return project; } async function getFixPromise( path: string, dirname: string, force: boolean, ): Promise { let { stdout } = await promiseExec( `cd "${path}" && npm audit fix --json ${force && "--force"}`, ); let output: FixOutput = JSON.parse(stdout); let project: ProjectFix = { projectName: dirname, ...output }; if (project.error) { throw new Error(`${dirname} could not be fixed`); } return project; }