import { existsSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
function pathFromInput(from) {
    if (from instanceof URL) {
        return fileURLToPath(from);
    }
    if (from.startsWith("file:")) {
        return fileURLToPath(from);
    }
    return path.resolve(from);
}
function getSearchDirectory(from) {
    const resolved = pathFromInput(from);
    try {
        return statSync(resolved).isDirectory() ? resolved : path.dirname(resolved);
    }
    catch {
        return path.dirname(resolved);
    }
}
function readPackageMetadata(packageJsonPath) {
    const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
    const metadata = { path: packageJsonPath };
    if (typeof parsed.name === "string") {
        metadata.name = parsed.name;
    }
    if (typeof parsed.version === "string") {
        metadata.version = parsed.version;
    }
    return metadata;
}
export function findPackageMetadata(from) {
    let current = getSearchDirectory(from);
    while (true) {
        const packageJsonPath = path.join(current, "package.json");
        if (existsSync(packageJsonPath)) {
            return readPackageMetadata(packageJsonPath);
        }
        const parent = path.dirname(current);
        if (parent === current) {
            return undefined;
        }
        current = parent;
    }
}
export function packageMetadata(from = process.cwd()) {
    const metadata = findPackageMetadata(from);
    if (metadata === undefined) {
        throw new Error(`No package.json found from ${pathFromInput(from)}.`);
    }
    return metadata;
}
export function findEntrypointPackageMetadata(entrypoint) {
    if (entrypoint === undefined || entrypoint.length === 0) {
        return undefined;
    }
    if (!path.isAbsolute(entrypoint) && !entrypoint.startsWith("file:")) {
        return undefined;
    }
    return findPackageMetadata(entrypoint);
}
