import { readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; const PONY_PACKAGE_NAME = "@whitespace/pony"; interface PonyPackageJson { name?: unknown; version?: unknown; } export interface PonyPackageInfo { changelog: string; version: string; } function isMissingFile(error: unknown): boolean { return (error as NodeJS.ErrnoException).code === "ENOENT"; } async function readPackageJson( packageRoot: string, ): Promise { try { return JSON.parse( await readFile(path.join(packageRoot, "package.json"), "utf8"), ) as PonyPackageJson; } catch (error) { if (isMissingFile(error)) return null; throw error; } } /** * Resolves from the executing module instead of the workspace cwd because the * workspace belongs to the consumer while package metadata belongs to the Pony * installation serving or building the web interface. */ export async function resolvePonyPackageRoot( startUrl: string | URL = import.meta.url, ): Promise { let current = path.dirname(fileURLToPath(startUrl)); while (true) { const packageJson = await readPackageJson(current); if (packageJson?.name === PONY_PACKAGE_NAME) return current; const parent = path.dirname(current); if (parent === current) { throw new Error( `Could not locate the ${PONY_PACKAGE_NAME} package root.`, ); } current = parent; } } export async function loadPonyPackageInfo( startUrl: string | URL = import.meta.url, ): Promise { const packageRoot = await resolvePonyPackageRoot(startUrl); const [packageJson, changelog] = await Promise.all([ readPackageJson(packageRoot), readFile(path.join(packageRoot, "CHANGELOG.md"), "utf8"), ]); if (typeof packageJson?.version !== "string") { throw new Error("Pony package version is missing or invalid."); } return { changelog, version: packageJson.version, }; }