import { spawn } from "node:child_process"; import { createRequire } from "node:module"; import { readFile, realpath, writeFile } from "node:fs/promises"; import path from "node:path"; import semver from "semver"; import { pathExists } from "../core/index.js"; export const PONY_PACKAGE_NAME = "@whitespace/pony"; export interface PackageJson { bin?: string | Record; dependencies?: Record; devDependencies?: Record; name?: string; packageManager?: string; version?: string; } export interface LocalPonyPackage { binPath: string; packageRoot: string; version: string; } export type CompatibilityResult = { compatible: true } | { compatible: false; reason: string }; export type PackageManagerName = "bun" | "npm" | "pnpm" | "yarn"; export type PonyDependencySection = "dependencies" | "devDependencies"; export interface PackageCommandResult { status: number; } export type PackageCommandRunner = ( command: string, args: string[], cwd: string, ) => Promise; const lockfiles: Array = [ ["npm", "package-lock.json"], ["pnpm", "pnpm-lock.yaml"], ["yarn", "yarn.lock"], ["bun", "bun.lock"], ["bun", "bun.lockb"], ]; export async function readPackageJson( packageRoot: string, ): Promise { return JSON.parse( await readFile(path.join(packageRoot, "package.json"), "utf8"), ) as PackageJson; } export async function readPackageVersion(packageRoot: string): Promise { const { version } = await readPackageJson(packageRoot); if (typeof version !== "string") { throw new Error("Pony package version is missing or invalid."); } return version; } export async function resolveLocalPonyPackage( projectRoot: string, ): Promise { const requireFromProject = createRequire( path.join(projectRoot, ".pony-launcher.cjs"), ); let packageJsonPath: string; try { packageJsonPath = requireFromProject.resolve( `${PONY_PACKAGE_NAME}/package.json`, ); } catch (error) { const code = (error as NodeJS.ErrnoException).code; if ( code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ) { return null; } throw error; } const packageRoot = path.dirname(packageJsonPath); const packageJson = await readPackageJson(packageRoot); const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.pony; if (typeof packageJson.version !== "string" || typeof bin !== "string") { throw new Error( `The local ${PONY_PACKAGE_NAME} package has invalid package metadata.`, ); } const resolvedPackageRoot = await realpath(packageRoot); const resolvedProjectRoot = await realpath(projectRoot); const binPath = path.resolve(resolvedPackageRoot, bin); if (!(await pathExists(binPath))) { if (resolvedPackageRoot === resolvedProjectRoot) { throw new Error( `Pony found this source checkout, but its CLI runtime is missing at ${binPath}. Run \`npm run build:cli\`, then run \`npm link\` after \`nvm use\` to refresh the launcher for the active Node.js version.`, ); } throw new Error( `The local ${PONY_PACKAGE_NAME} runtime is missing at ${binPath}. Reinstall the project package and retry.`, ); } return { binPath, packageRoot: resolvedPackageRoot, version: packageJson.version, }; } /** * The launcher only delegates to runtimes it can safely understand. A local * patch or minor may lag behind the launcher, but it may not lead it or cross a * major boundary because either case can change launcher/runtime assumptions. */ export function checkPackageCompatibility( launcherVersion: string, localVersion: string, ): CompatibilityResult { if (!semver.valid(launcherVersion)) { return { compatible: false, reason: `launcher version ${launcherVersion} is not valid semver`, }; } if (!semver.valid(localVersion)) { return { compatible: false, reason: `local version ${localVersion} is not valid semver`, }; } if (semver.major(launcherVersion) !== semver.major(localVersion)) { return { compatible: false, reason: `major version mismatch: launcher ${launcherVersion}, local ${localVersion}`, }; } if (semver.gt(localVersion, launcherVersion)) { return { compatible: false, reason: `local version ${localVersion} is newer than launcher ${launcherVersion}`, }; } return { compatible: true }; } export async function detectPackageManager( projectRoot: string, packageJson: PackageJson, ): Promise { const declared = packageJson.packageManager?.split("@")[0]; if ( declared === "npm" || declared === "pnpm" || declared === "yarn" || declared === "bun" ) { return declared; } const detected = new Set(); for (const [manager, filename] of lockfiles) { if (await pathExists(path.join(projectRoot, filename))) detected.add(manager); } if (detected.size > 1) { throw new Error( `Multiple package-manager lockfiles found (${[...detected].join(", ")}). Set packageManager in package.json before retrying.`, ); } return detected.values().next().value ?? "npm"; } function addCommand( manager: PackageManagerName, range: string, section: PonyDependencySection = "devDependencies", ): { command: string; args: string[] } { const specification = `${PONY_PACKAGE_NAME}@${range}`; const development = section === "devDependencies"; switch (manager) { case "pnpm": return { command: "pnpm", args: [ "add", development ? "--save-dev" : "--save-prod", specification, ], }; case "yarn": return { command: "yarn", args: development ? ["add", "--dev", specification] : ["add", specification], }; case "bun": return { command: "bun", args: development ? ["add", "--dev", specification] : ["add", specification], }; default: return { command: "npm", args: [ "install", development ? "--save-dev" : "--save-prod", specification, ], }; } } export function ponyDependencySection( packageJson: PackageJson, ): PonyDependencySection | null { if (packageJson.devDependencies?.[PONY_PACKAGE_NAME]) return "devDependencies"; if (packageJson.dependencies?.[PONY_PACKAGE_NAME]) return "dependencies"; return null; } export function localPonyUpgradeCommand( manager: PackageManagerName, version: string, section: PonyDependencySection, ): { command: string; args: string[] } { return addCommand(manager, version, section); } function installCommand(manager: PackageManagerName): { command: string; args: string[]; } { return { command: manager, args: ["install"] }; } export function formatPackageCommand(command: string, args: string[]): string { return [ command, ...args.map((value) => /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `'${value.replaceAll("'", "\\'")}'`, ), ].join(" "); } export async function runPackageCommand( command: string, args: string[], cwd: string, ): Promise { return new Promise((resolve, reject) => { const child = spawn(command, args, { cwd, stdio: "inherit" }); child.once("error", reject); child.once("exit", (code, signal) => { resolve({ status: code ?? (signal === "SIGINT" ? 130 : 1) }); }); }); } async function ensureNodeModulesIgnored(projectRoot: string): Promise { const ignorePath = path.join(projectRoot, ".gitignore"); const current = (await pathExists(ignorePath)) ? await readFile(ignorePath, "utf8") : ""; const ignoresNodeModules = current .split(/\r?\n/u) .map((line) => line.trim()) .some( (line) => line === "node_modules" || line === "node_modules/" || line === "/node_modules" || line === "/node_modules/", ); if (ignoresNodeModules) return; const separator = current.length > 0 && !current.endsWith("\n") ? "\n" : ""; await writeFile(ignorePath, `${current}${separator}node_modules/\n`, "utf8"); } export interface EnsureLocalPackageResult { command: string | null; installed: boolean; localPackage: LocalPonyPackage; } /** * Non-JavaScript repositories receive only the minimal Node manifest required * to pin Pony. This makes the local runtime reproducible without imposing a * JavaScript application structure on the host project. */ export async function ensureLocalPonyPackage( projectRoot: string, launcherVersion: string, runner: PackageCommandRunner = runPackageCommand, ): Promise { const existingLocal = await resolveLocalPonyPackage(projectRoot); if (existingLocal) { const compatibility = checkPackageCompatibility( launcherVersion, existingLocal.version, ); if (!compatibility.compatible) { throw new Error(`Local Pony is incompatible: ${compatibility.reason}.`); } return { command: null, installed: false, localPackage: existingLocal }; } const packageJsonPath = path.join(projectRoot, "package.json"); if (!(await pathExists(packageJsonPath))) { await writeFile(packageJsonPath, '{\n "private": true\n}\n', "utf8"); } await ensureNodeModulesIgnored(projectRoot); const packageJson = await readPackageJson(projectRoot); const manager = await detectPackageManager(projectRoot, packageJson); const declaredRange = packageJson.devDependencies?.[PONY_PACKAGE_NAME] ?? packageJson.dependencies?.[PONY_PACKAGE_NAME]; const selected = declaredRange ? installCommand(manager) : addCommand(manager, `^${launcherVersion}`); const retry = formatPackageCommand(selected.command, selected.args); const result = await runner(selected.command, selected.args, projectRoot); if (result.status !== 0) { throw new Error( `Pony project state was initialized, but the local package installation failed. Retry with: ${retry}`, ); } const installed = await resolveLocalPonyPackage(projectRoot); if (!installed) { throw new Error( `The package manager completed without installing ${PONY_PACKAGE_NAME}. Retry with: ${retry}`, ); } const compatibility = checkPackageCompatibility( launcherVersion, installed.version, ); if (!compatibility.compatible) { throw new Error(`Installed Pony is incompatible: ${compatibility.reason}.`); } return { command: retry, installed: true, localPackage: installed }; }