import { n as resolveConfig } from "./config-FJViU9hJ.mjs";
import { defineCommand } from "citty";
import { get } from "node:http";
import { get as get$1 } from "node:https";
//#region src/commands/status.ts
const VITE_MARKER = "/@vite/client";
const PLANNAR_MARKER = "name=\"plannar-editor\"";
const MAX_BODY_BYTES = 256 * 1024;
const UNCONNECTABLE_HOSTS = new Set([
	"0.0.0.0",
	"::",
	"::0",
	"0:0:0:0:0:0:0:0"
]);
function normalizeHost(host) {
	if (UNCONNECTABLE_HOSTS.has(host)) return "127.0.0.1";
	return host;
}
function checkPort(host, port, timeout, options = {}) {
	return new Promise((resolve) => {
		const protocol = options.https ? "https" : "http";
		const req = (options.https ? get$1 : get)(`${protocol}://${host}:${port}`, {
			timeout,
			rejectUnauthorized: false
		}, (res) => {
			if (res.statusCode !== 200) {
				res.resume();
				resolve(false);
				return;
			}
			let body = "";
			let received = 0;
			res.on("data", (chunk) => {
				received += chunk.length;
				body += chunk.toString();
				if (body.includes(VITE_MARKER) && body.includes(PLANNAR_MARKER)) {
					req.destroy();
					resolve(true);
					return;
				}
				if (received >= MAX_BODY_BYTES) {
					req.destroy();
					resolve(false);
				}
			});
			res.on("end", () => resolve(false));
		});
		req.on("timeout", () => {
			req.destroy();
			resolve(false);
		});
		req.on("error", () => resolve(false));
	});
}
async function findEditorPort(host, startPort, scanCount = 10, options = {}) {
	if (await checkPort(host, startPort, 2e3, options)) return startPort;
	const idx = (await Promise.all(Array.from({ length: scanCount - 1 }, (_, i) => checkPort(host, startPort + 1 + i, 1e3, options)))).indexOf(true);
	return idx >= 0 ? startPort + 1 + idx : null;
}
var status_default = defineCommand({
	meta: {
		name: "status",
		description: "Find which port the plan editor is running on"
	},
	args: {
		port: {
			type: "string",
			description: "Port to start scanning from",
			default: "5173"
		},
		host: {
			type: "string",
			description: "Host to check",
			default: "localhost"
		}
	},
	async run({ args }) {
		const config = await resolveConfig(process.cwd());
		let port = Number(args.port);
		let host = args.host;
		let https = false;
		const editorConfig = config.viteConfig?.editor;
		if (editorConfig?.server) {
			const serverConfig = editorConfig.server;
			if (typeof serverConfig.port === "string" || typeof serverConfig.port === "number") port = Number(serverConfig.port);
			if (typeof serverConfig.host === "string") host = serverConfig.host;
			if (serverConfig.https) https = true;
		}
		const connectHost = normalizeHost(host);
		const foundPort = await findEditorPort(connectHost, port, 10, { https });
		const protocol = https ? "https" : "http";
		if (foundPort !== null) console.log(`✓ Editor is running at ${protocol}://${connectHost}:${foundPort}`);
		else console.log(`✗ Editor is not running`);
	}
});
//#endregion
export { status_default as default };
