Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/cost/__tests__/debug.test.ts

Raw
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createTestSession,
	sandboxEnv,
	type TestSession,
	withProcessEnv,
} from "../../../test/harness";

describe("cost debug", () => {
	let root: string | undefined;
	let session: TestSession | undefined;

	afterEach(() => {
		session?.dispose();
		if (root) rmSync(root, { recursive: true, force: true });
		session = undefined;
		root = undefined;
	});

	it("writes its lifecycle JSONL through the standalone factory", async () => {
		root = mkdtempSync(path.join(tmpdir(), "pi-ext-cost-debug-"));
		const env = sandboxEnv(root, { env: { PI_COST_DEBUG: "1" } });
		vi.resetModules();
		const factory = await withProcessEnv(
			env,
			async () => (await import("../index.ts")).default,
		);
		session = await createTestSession({
			cwd: root,
			extensionFactories: [factory],
			env: { PI_COST_DEBUG: "1" },
		});
		await session.session.extensionRunner.emit({
			type: "session_start",
			reason: "startup",
		});
		await session.session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "quit",
		});

		if (!env.XDG_STATE_HOME) throw new Error("missing sandbox state home");
		const directory = path.join(env.XDG_STATE_HOME, "pi-ext", "debug", "cost");
		const [file] = readdirSync(directory);
		const events = readFileSync(path.join(directory, file), "utf8")
			.trim()
			.split("\n")
			.map((line) => JSON.parse(line).event);
		expect(events).toEqual(
			expect.arrayContaining(["session.start", "session.shutdown"]),
		);
	});
});