Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/devdocs/src/settings.ts

Raw
import { homedir } from "node:os";
import { isAbsolute, posix, win32 } from "node:path";
import { formatReaders } from "./catalog.ts";
import {
	defineIntegerSetting,
	parseBooleanSetting,
	type SettingDeclaration,
} from "./pi-ext-settings.ts";
import type { RegisteredSource } from "./types.ts";

export function defaultDatabasePath(
	platform: string = process.platform,
	home: string = homedir(),
	env: NodeJS.ProcessEnv = process.env,
): string {
	const path = platform === "win32" ? win32 : posix;
	const absolute = (value: string | undefined): value is string =>
		!!value && path.isAbsolute(value);
	const root =
		platform === "win32"
			? absolute(env["LOCALAPPDATA"])
				? env["LOCALAPPDATA"]
				: path.join(home, "AppData", "Local")
			: platform === "darwin"
				? path.join(home, "Library", "Caches")
				: absolute(env["XDG_CACHE_HOME"])
					? env["XDG_CACHE_HOME"]
					: path.join(home, ".cache");
	return path.join(root, "pi", "devdocs", "cache.db");
}
export function parsePath(value: unknown): string {
	if (
		typeof value !== "string" ||
		!value.trim() ||
		value.length > 4096 ||
		!isAbsolute(value) ||
		/[\x00-\x1f]/u.test(value)
	)
		throw new Error("expected a nonempty absolute database file path");
	return value;
}
export const DATABASE: SettingDeclaration<string> = {
	key: "devdocs.databasePath",
	env: "PI_DEVDOCS_DATABASE_PATH",
	default: "OS user-cache directory/pi/devdocs/cache.db",
	parse: parsePath,
};
export const OFFLINE: SettingDeclaration<boolean> = {
	key: "devdocs.offline",
	env: "PI_DEVDOCS_OFFLINE",
	default: false,
	parse: parseBooleanSetting,
};
export const CAPACITY: SettingDeclaration<number> = defineIntegerSetting({
	key: "devdocs.cacheBytes",
	default: 268435456,
	range: { min: 1048576, max: 1073741824 },
});
export const TTL: SettingDeclaration<number> = defineIntegerSetting({
	key: "devdocs.ttlSeconds",
	default: 86400,
	range: { min: 0, max: 2592000 },
});
export const ENABLED: SettingDeclaration<string[]> = {
	key: "devdocs.enabledSources",
	default: ["local", "devdocs", "upstream", "context7"],
	parse(value) {
		if (
			!Array.isArray(value) ||
			value.length > 100 ||
			value.some(
				(x) => typeof x !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(x),
			) ||
			new Set(value).size !== value.length
		)
			throw new Error("expected unique source IDs");
		return value;
	},
};
export const SOURCES: SettingDeclaration<RegisteredSource[]> = {
	key: "devdocs.sources",
	default: [],
	parse(value) {
		if (!Array.isArray(value) || value.length > 100)
			throw new Error("expected at most 100 documentation sources");
		const seen = new Set<string>();
		return value.map((raw) => {
			if (!raw || typeof raw !== "object")
				throw new Error("invalid documentation source");
			const r = raw as Record<string, unknown>;
			if (
				typeof r["id"] !== "string" ||
				!/^[a-z][a-z0-9-]{0,63}$/.test(r["id"]) ||
				["local", "devdocs", "upstream", "context7"].includes(r["id"]) ||
				seen.has(r["id"])
			)
				throw new Error("source requires unique non-reserved id");
			seen.add(r["id"]);
			if (
				typeof r["target"] !== "string" ||
				!r["target"].trim() ||
				r["target"].length > 200
			)
				throw new Error("source requires target");
			const url = r["url"];
			if (
				url !== undefined &&
				(typeof url !== "string" ||
					!/^https:\/\//.test(url) ||
					url.length > 4096)
			)
				throw new Error("source URL must be HTTPS");
			if ((url === undefined) === (r["path"] === undefined))
				throw new Error("source requires exactly one path or URL");
			if (typeof url === "string") {
				const parsed = new URL(url);
				if (parsed.username || parsed.password || parsed.search)
					throw new Error(
						"source URL cannot contain credentials or query parameters",
					);
			}
			const path = url === undefined ? parsePath(r["path"]) : "";
			const format = r["format"] ?? "markdown";
			if (!formatReaders.some((reader) => reader.id === format))
				throw new Error("unsupported documentation format");
			if (
				r["version"] !== undefined &&
				(typeof r["version"] !== "string" || r["version"].length > 100)
			)
				throw new Error("invalid documentation version");
			if (r["private"] !== undefined && typeof r["private"] !== "boolean")
				throw new Error("invalid private marker");
			return {
				id: r["id"],
				target: r["target"],
				path,
				url: typeof url === "string" ? url : null,
				format: format as RegisteredSource["format"],
				version: typeof r["version"] === "string" ? r["version"] : null,
				private: r["private"] === true,
			};
		});
	},
};