Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

scripts/codegen.repository.test.ts

Raw
import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join, relative } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestSession } from "../test/harness";
import { CONFIG_PATH, expectedGenerated } from "./codegen.mjs";
import { ROOT } from "./lib/common.mjs";

const PI_PROVIDED = /^(node:|@earendil-works\/pi-[a-z-]+(\/|$)|typebox(\/|$))/;

function importSpecifiers(source: string): string[] {
	return [
		...source.matchAll(/\bfrom\s+"([^"]+)"|\bimport\s*\(\s*"([^"]+)"\s*\)/g),
	].map((match) => match[1] ?? match[2]);
}

describe("repository codegen", () => {
	const generated = expectedGenerated(ROOT);

	it("regenerates identical bytes and matches committed output", () => {
		const again = expectedGenerated(ROOT);
		expect(again.map((file) => file.output)).toEqual(
			generated.map((file) => file.output),
		);
		for (const [index, file] of generated.entries()) {
			const label = relative(ROOT, file.output);
			expect(again[index]?.bytes.equals(file.bytes), label).toBe(true);
			expect(readFileSync(file.output).equals(file.bytes), label).toBe(true);
		}
	});

	it("emits leaf helpers importing only Node built-ins and Pi-provided modules", () => {
		for (const file of generated) {
			const specifiers = importSpecifiers(file.bytes.toString("utf8"));
			for (const specifier of specifiers)
				expect(specifier, relative(ROOT, file.output)).toMatch(PI_PROVIDED);
		}
	});

	const settings = (
		JSON.parse(readFileSync(join(ROOT, CONFIG_PATH), "utf8")) as {
			targets: { name: string; extensions: string[] }[];
		}
	).targets.find((target) => target.name === "pi-ext-settings");

	it.each(settings?.extensions ?? [])(
		"%s loads alone from a copy outside the checkout",
		async (slug) => {
			const root = mkdtempSync(join(tmpdir(), `pi-ext-relocated-${slug}-`));
			const copy = join(root, slug);
			cpSync(join(ROOT, "extensions", slug), copy, {
				recursive: true,
				filter: (path) =>
					!["__tests__", "__bench__", "__e2e__", "node_modules"].includes(
						basename(path),
					),
			});
			const t = await createTestSession({
				cwd: root,
				extensions: [join(copy, "index.ts")],
			});
			try {
				expect(t.session.extensionRunner.extensions).toHaveLength(1);
				expect(t.session.extensionRunner.extensions[0]?.path).toBe(
					join(copy, "index.ts"),
				);
			} finally {
				// Pi emits shutdown before disposal; extensions cancel deferred startup work here.
				await t.session.extensionRunner.emit({
					type: "session_shutdown",
					reason: "quit",
				});
				t.dispose();
				rmSync(root, { recursive: true, force: true });
			}
		},
	);
});