import { dirname, isAbsolute, join, normalize, resolve } from "../../../../pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs";
import { resolveModulePath } from "../../../../exsolve@1.0.8/node_modules/exsolve/dist/index.mjs";
import { h, x } from "../../../../confbox@0.2.2/node_modules/confbox/dist/shared/confbox.DnMsyigM.mjs";
import { promises, statSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";

//#region ../../node_modules/.pnpm/pkg-types@2.3.0/node_modules/pkg-types/dist/index.mjs
const defaultFindOptions = {
	startingFrom: ".",
	rootPattern: /^node_modules$/,
	reverse: false,
	test: (filePath) => {
		try {
			if (statSync(filePath).isFile()) return true;
		} catch {}
	}
};
async function findFile(filename, _options = {}) {
	const filenames = Array.isArray(filename) ? filename : [filename];
	const options = {
		...defaultFindOptions,
		..._options
	};
	const basePath = resolve(options.startingFrom);
	const leadingSlash = basePath[0] === "/";
	const segments = basePath.split("/").filter(Boolean);
	if (filenames.includes(segments.at(-1)) && await options.test(basePath)) return basePath;
	if (leadingSlash) segments[0] = "/" + segments[0];
	let root = segments.findIndex((r) => r.match(options.rootPattern));
	if (root === -1) root = 0;
	if (options.reverse) for (let index = root + 1; index <= segments.length; index++) for (const filename2 of filenames) {
		const filePath = join(...segments.slice(0, index), filename2);
		if (await options.test(filePath)) return filePath;
	}
	else for (let index = segments.length; index > root; index--) for (const filename2 of filenames) {
		const filePath = join(...segments.slice(0, index), filename2);
		if (await options.test(filePath)) return filePath;
	}
	throw new Error(`Cannot find matching ${filename} in ${options.startingFrom} or parent directories`);
}
function findNearestFile(filename, options = {}) {
	return findFile(filename, options);
}
function _resolvePath(id, opts = {}) {
	if (id instanceof URL || id.startsWith("file://")) return normalize(fileURLToPath(id));
	if (isAbsolute(id)) return normalize(id);
	return resolveModulePath(id, {
		...opts,
		from: opts.from || opts.parent || opts.url
	});
}
const lockFiles = [
	"yarn.lock",
	"package-lock.json",
	"pnpm-lock.yaml",
	"npm-shrinkwrap.json",
	"bun.lockb",
	"bun.lock",
	"deno.lock"
];
const packageFiles = [
	"package.json",
	"package.json5",
	"package.yaml"
];
const workspaceFiles = [
	"pnpm-workspace.yaml",
	"lerna.json",
	"turbo.json",
	"rush.json",
	"deno.json",
	"deno.jsonc"
];
const FileCache = /* @__PURE__ */ new Map();
async function readPackageJSON(id, options = {}) {
	const resolvedPath = await resolvePackageJSON(id, options);
	const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache;
	if (options.cache && cache.has(resolvedPath)) return cache.get(resolvedPath);
	const blob = await promises.readFile(resolvedPath, "utf8");
	let parsed;
	try {
		parsed = x(blob);
	} catch {
		parsed = h(blob);
	}
	cache.set(resolvedPath, parsed);
	return parsed;
}
async function resolvePackageJSON(id = process.cwd(), options = {}) {
	return findNearestFile("package.json", {
		...options,
		startingFrom: _resolvePath(id, options)
	});
}
const workspaceTests = {
	workspaceFile: (opts) => findFile(workspaceFiles, opts).then((r) => dirname(r)),
	gitConfig: (opts) => findFile(".git/config", opts).then((r) => resolve(r, "../..")),
	lockFile: (opts) => findFile(lockFiles, opts).then((r) => dirname(r)),
	packageJson: (opts) => findFile(packageFiles, opts).then((r) => dirname(r))
};
async function findWorkspaceDir(id = process.cwd(), options = {}) {
	const startingFrom = _resolvePath(id, options);
	const tests = options.tests || [
		"workspaceFile",
		"gitConfig",
		"lockFile",
		"packageJson"
	];
	for (const testName of tests) {
		const test = workspaceTests[testName];
		if (options[testName] === false || !test) continue;
		const direction = options[testName] || (testName === "gitConfig" ? "closest" : "furthest");
		const detected = await test({
			...options,
			startingFrom,
			reverse: direction === "furthest"
		}).catch(() => {});
		if (detected) return detected;
	}
	throw new Error(`Cannot detect workspace root from ${id}`);
}

//#endregion
export { findWorkspaceDir, readPackageJSON };
//# sourceMappingURL=index.mjs.map