Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/runtime/__tests__/settings.test.ts

Raw
import {
	chmodSync,
	mkdirSync,
	mkdtempSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";

import { writeWindowsExecutable } from "../../../test/fixture/windows-executable.ts";

const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
const ENV = "PI_RUNTIME_VERSION_TIMEOUT_MS";

interface UiCall {
	args: unknown[];
}

interface RecordingUi {
	statusCalls: UiCall[];
	notifyCalls: UiCall[];
}

/**
 * Install a recording UI context so `hasUI` is true (the extension sees an
 * interactive UI) and `ctx.ui.setStatus` / `ctx.ui.notify` calls are captured.
 */
function installRecordingUi(session: PiSession): RecordingUi {
	const statusCalls: UiCall[] = [];
	const notifyCalls: UiCall[] = [];
	session.session.extensionRunner.setUIContext(
		{
			setStatus: (...args: unknown[]) => statusCalls.push({ args }),
			notify: (...args: unknown[]) => notifyCalls.push({ args }),
		} as never,
		"print",
	);
	return { statusCalls, notifyCalls };
}

type Case = {
	user?: unknown;
	project?: unknown;
	env?: string;
	untrusted?: boolean;
};

describe("runtime.versionTimeoutMs resolution", () => {
	let session: PiSession | undefined;
	let root: string | undefined;
	afterEach(async () => {
		await session?.dispose();
		session = undefined;
		if (root) rmSync(root, { recursive: true, force: true });
		root = undefined;
	});

	/** Fake `bun` answers after 500 ms; the status shows its version only within the timeout. */
	async function start(input: Case) {
		root = mkdtempSync(path.join(tmpdir(), "pi-ext-runtime-settings-"));
		if ("project" in input) {
			mkdirSync(path.join(root, ".pi"), { recursive: true });
			writeFileSync(
				path.join(root, ".pi", "settings.json"),
				JSON.stringify({ runtime: { versionTimeoutMs: input.project } }),
			);
		}
		const bin = path.join(root, "bin");
		mkdirSync(bin);
		if (process.platform === "win32")
			writeWindowsExecutable(bin, "bun", "9.9.9\n", 500);
		else {
			writeFileSync(
				path.join(bin, "bun"),
				"#!/bin/sh\nsleep 0.5\necho 9.9.9\n",
			);
			chmodSync(path.join(bin, "bun"), 0o755);
		}
		writeFileSync(path.join(root, "bun.lock"), "");
		session = await createPiSession({
			cwd: root,
			extensionPaths: [extensionPath],
			env: {
				PATH: `${bin}${path.delimiter}${process.env["PATH"]}`,
				[ENV]: input.env,
			},
			...("user" in input
				? { userSettings: { runtime: { versionTimeoutMs: input.user } } }
				: {}),
		});
		if (input.untrusted)
			session.session.settingsManager.setProjectTrusted(false);
		const ui = installRecordingUi(session);
		await session.session.extensionRunner.emit({
			type: "session_start",
			reason: "startup",
		});
		await vi.waitFor(() => expect(ui.statusCalls.length).toBeGreaterThan(0), {
			timeout: 5000,
		});
		const text = ui.statusCalls.at(-1)?.args[1] as string | undefined;
		const warnings = ui.notifyCalls
			.filter((call) => call.args[1] === "warning")
			.map((call) => call.args[0]);
		return { version: text?.endsWith(" v9.9.9") ?? false, warnings };
	}

	it.each([
		["default 2500 waits for version", {}, true],
		["user value applied", { user: 100 }, false],
		["env over user", { user: 100, env: "2500" }, true],
		["env over project", { project: 2500, env: "100" }, false],
		["trusted project over user", { user: 100, project: 2500 }, true],
		[
			"untrusted project ignored",
			{ user: 100, project: 2500, untrusted: true },
			false,
		],
	] satisfies [string, Case, boolean][])(
		"%s",
		async (_name, input, expected) => {
			const { version, warnings } = await start(input);
			expect(version).toBe(expected);
			expect(warnings).toEqual([]);
		},
	);

	it.each([
		["string project", { user: 100, project: "100" }, "project settings", ""],
		[
			"zero user",
			{ user: 0 },
			"user settings",
			": expected an integer from 1 to 2147483647",
		],
		[
			"fractional user",
			{ user: 100.5 },
			"user settings",
			": expected an integer from 1 to 2147483647",
		],
		[
			"oversized project",
			{ user: 100, project: 2 ** 31 },
			"project settings",
			": expected an integer from 1 to 2147483647",
		],
		[
			"non-numeric env",
			{ user: 100, env: "fast" },
			`environment variable ${ENV}`,
			"",
		],
	] satisfies [string, Case, string, string][])(
		"rejects %s without falling through",
		async (_name, input, source, detail) => {
			const { version, warnings } = await start(input);
			expect(version).toBe(true);
			expect(warnings).toEqual([
				`Invalid runtime.versionTimeoutMs from ${source}${detail}; using 2500 ms`,
			]);
		},
	);
});