Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/the-system/project-index.ts

Raw
import { readFileSync } from "node:fs";
import path from "node:path";
import {
	type Diagnostic,
	discoverDocumentBundles,
	indexBundleDocuments,
	parseSystemConfig,
	readCurrentPhase,
	requireProjectRoot,
} from "./documents.ts";

export function loadProjectIndex(cwd: string) {
	const root = requireProjectRoot(cwd);
	const config = parseSystemConfig(
		readFileSync(path.join(root, ".system/config.json"), "utf8"),
	);
	const discovery = discoverDocumentBundles(root);
	const indexed = indexBundleDocuments(discovery.sources, config.prefix);
	const phaseDiagnostics: Diagnostic[] = [];
	try {
		readCurrentPhase(root, config);
	} catch (error) {
		phaseDiagnostics.push({
			code: "config.current-phase",
			path: ".system/config.json",
			message: error instanceof Error ? error.message : String(error),
		});
	}
	return {
		root,
		prefix: config.prefix,
		...(config.currentPhase ? { currentPhase: config.currentPhase } : {}),
		documents: indexed.documents.map((document) => ({
			...document,
			markdown:
				discovery.sources.find((source) => source.path === document.path)
					?.markdown ?? "",
		})),
		diagnostics: [
			...discovery.diagnostics,
			...indexed.diagnostics,
			...phaseDiagnostics,
		],
	};
}

export type ProjectIndex = ReturnType<typeof loadProjectIndex>;