repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

scripts/build/collection.ts

Raw
File outline
// Collection manifest `dist/package.json`: one Pi package entry loads every
// built extension package. pfui and footer load first so they own prompt
// sections and footer slots before the rest register. Pi reads nested
// manifests only for extensions, so declared skills, prompts, and themes are
// lifted here under `<name>/`.
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join, posix } from "node:path";
import { allExtensionNames, DIST_ROOT, ROOT, rootVersion } from "./build.ts";

const FIRST = ["pfui", "footer"];
const RESOURCES = ["skills", "prompts", "themes"] as const;

type Resource = "extensions" | (typeof RESOURCES)[number];

export interface CollectionManifest {
	name: "pi-ext";
	version: string;
	private: true;
	type: "module";
	pi: Partial<Record<Resource, string[]>>;
}

export function collectionManifest(
	names: string[],
	distRoot: string,
	version: string,
): CollectionManifest {
	const built = names.filter((name) =>
		existsSync(join(distRoot, name, "package.json")),
	);
	const extensions = [
		...FIRST.filter((name) => built.includes(name)),
		...built.filter((name) => !FIRST.includes(name)),
	];
	const pi: CollectionManifest["pi"] = { extensions };
	for (const name of extensions) {
		const { pi: declared } = JSON.parse(
			readFileSync(join(distRoot, name, "package.json"), "utf8"),
		) as { pi?: Partial<Record<Resource, string[]>> };
		for (const field of RESOURCES) {
			const entries = declared?.[field] ?? [];
			if (!entries.length) continue;
			pi[field] = [
				...(pi[field] ?? []),
				...entries.map((entry) =>
					entry.startsWith("!")
						? `!${posix.join(name, entry.slice(1))}`
						: posix.join(name, entry),
				),
			];
		}
	}
	return { name: "pi-ext", version, private: true, type: "module", pi };
}

/** Rewrite `<distRoot>/package.json` atomically from the built packages. */
export function writeCollectionManifest(
	distRoot: string = DIST_ROOT,
	root: string = ROOT,
): CollectionManifest {
	const manifest = collectionManifest(
		allExtensionNames(root),
		distRoot,
		rootVersion(root),
	);
	const target = join(distRoot, "package.json");
	const temporary = `${target}.${process.pid}.tmp`;
	writeFileSync(temporary, `${JSON.stringify(manifest, null, "\t")}\n`);
	renameSync(temporary, target);
	return manifest;
}