import { a as __toESM, r as __name } from "./chunk-DbZtQ4qb.js";
import { t as require_react } from "./react--draJ5Pm.js";
import "./jsx-runtime-CQFBnRKx.js";
import { Fragment, jsx, jsxs } from "./jsx-runtime.js";
import { a as _classPrivateFieldInitSpec, i as _classPrivateFieldGet2, n as Runtime, o as Renderer, r as _classPrivateFieldSet2, s as Root, t as reactPlugin } from "./reactPlugin-DqJsInTf.js";
import { AppContext, FileContext, FileManager, FileProcessor, NodeTreeContext, RootContext, TreeNode, createContext, createFabric, createFabric as createFabric$1, createFile, createJSDoc, provide, useApp, useContext, useContext as useContext$1, useFile, useFile as useFile$1, useFileManager, useLifecycle, useNodeTree } from "@kubb/fabric-core";
import { execa } from "execa";
import { onExit } from "signal-exit";
import ws from "ws";
import { orderBy } from "natural-orderby";

//#region src/components/App.tsx
var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
/**
* App container containing the AppContext carrying `meta` and an `exit` hook.
*/
function App({ children, ...props }) {
	const { meta = {} } = props;
	const { exit } = useContext$1(RootContext);
	const nodeTree = useNodeTree();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "App",
		props
	}));
	provide(AppContext, {
		exit,
		meta
	});
	return /* @__PURE__ */ jsx(Fragment, { children });
}
App.displayName = "App";

//#endregion
//#region src/components/Const.tsx
/**
* Generates a TypeScript constant declaration.
*/
function Const({ children, ...props }) {
	const { name, export: canExport, type, JSDoc, asConst } = props;
	const nodeTree = useNodeTree();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "Const",
		props
	}));
	return /* @__PURE__ */ jsxs(Fragment, { children: [
		(JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments) && /* @__PURE__ */ jsxs(Fragment, { children: [createJSDoc({ comments: JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments }), /* @__PURE__ */ jsx("br", {})] }),
		canExport && /* @__PURE__ */ jsx(Fragment, { children: "export " }),
		"const ",
		name,
		type ? /* @__PURE__ */ jsxs(Fragment, { children: [
			":",
			type,
			" "
		] }) : " ",
		"= ",
		children,
		asConst && /* @__PURE__ */ jsx(Fragment, { children: " as const" })
	] });
}
Const.displayName = "Const";

//#endregion
//#region src/components/File.tsx
/**
* Adds files to the FileManager
*/
function File({ children, ...props }) {
	const { baseName, path, meta = {}, footer, banner } = props;
	const fileManager = useFileManager();
	const nodeTree = useNodeTree();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "File",
		props
	}));
	if (!baseName || !path) return /* @__PURE__ */ jsx(Fragment, { children });
	const file = {
		baseName,
		path,
		meta,
		banner,
		footer,
		sources: [],
		imports: [],
		exports: []
	};
	const [resolvedFile] = fileManager.add(file);
	provide(FileContext, resolvedFile);
	return /* @__PURE__ */ jsx("kubb-file", {
		...props,
		children
	});
}
File.displayName = "File";
/**
* File.Source
*
* Marks a block of source text to be associated with the current file when
* rendering with the FileCollector. Children are treated as the source string.
*/
function FileSource({ children, ...props }) {
	const { name, isExportable, isIndexable, isTypeOnly } = props;
	const nodeTree = useNodeTree();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "FileSource",
		props
	}));
	return /* @__PURE__ */ jsx("kubb-source", {
		name,
		isTypeOnly,
		isExportable,
		isIndexable,
		children
	});
}
FileSource.displayName = "FileSource";
/**
* File.Export
*
* Declares an export entry for the current file. This will be collected by
* the FileCollector for later emission.
*/
function FileExport(props) {
	const { name, path, isTypeOnly, asAlias } = props;
	const nodeTree = useNodeTree();
	const file = useFile$1();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "FileExport",
		props
	}));
	if (file) file.exports.push({
		name,
		path,
		asAlias,
		isTypeOnly
	});
	return /* @__PURE__ */ jsx("kubb-export", {
		name,
		path,
		isTypeOnly,
		asAlias
	});
}
FileExport.displayName = "FileExport";
/**
* File.Import
*
* Declares an import entry for the current file.
*/
function FileImport(props) {
	const { name, root, path, isTypeOnly, isNameSpace } = props;
	const nodeTree = useNodeTree();
	const file = useFile$1();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "FileImport",
		props
	}));
	if (file) file.imports.push({
		name,
		path,
		root,
		isNameSpace,
		isTypeOnly
	});
	return /* @__PURE__ */ jsx("kubb-import", {
		name,
		root,
		path,
		isNameSpace,
		isTypeOnly
	});
}
FileImport.displayName = "FileImport";
File.Export = FileExport;
File.Import = FileImport;
File.Source = FileSource;

//#endregion
//#region src/components/Function.tsx
/**
* Generates a TypeScript function declaration.
*/
function Function({ children, ...props }) {
	const { name, default: isDefault, export: canExport, async, generics, params, returnType, JSDoc } = props;
	const nodeTree = useNodeTree();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "Function",
		props
	}));
	return /* @__PURE__ */ jsxs(Fragment, { children: [
		(JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments) && /* @__PURE__ */ jsxs(Fragment, { children: [createJSDoc({ comments: JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments }), /* @__PURE__ */ jsx("br", {})] }),
		canExport && /* @__PURE__ */ jsx(Fragment, { children: "export " }),
		isDefault && /* @__PURE__ */ jsx(Fragment, { children: "default " }),
		async && /* @__PURE__ */ jsx(Fragment, { children: "async " }),
		"function ",
		name,
		generics && /* @__PURE__ */ jsxs(Fragment, { children: [
			"<",
			Array.isArray(generics) ? generics.join(", ").trim() : generics,
			">"
		] }),
		"(",
		params,
		")",
		returnType && !async && /* @__PURE__ */ jsxs(Fragment, { children: [": ", returnType] }),
		returnType && async && /* @__PURE__ */ jsxs(Fragment, { children: [
			": Promise",
			"<",
			returnType,
			">"
		] }),
		" {",
		/* @__PURE__ */ jsx("br", {}),
		/* @__PURE__ */ jsx("indent", {}),
		children,
		/* @__PURE__ */ jsx("br", {}),
		/* @__PURE__ */ jsx("dedent", {}),
		"}"
	] });
}
Function.displayName = "Function";
/**
* ArrowFunction
*
* Renders an arrow function definition. Supports the same flags as `Function`.
* Use `singleLine` to render the body as a single-line expression.
*/
function ArrowFunction({ children, ...props }) {
	const { name, default: isDefault, export: canExport, async, generics, params, returnType, JSDoc, singleLine } = props;
	const nodeTree = useNodeTree();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "ArrowFunction",
		props
	}));
	return /* @__PURE__ */ jsxs(Fragment, { children: [
		(JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments) && /* @__PURE__ */ jsxs(Fragment, { children: [createJSDoc({ comments: JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments }), /* @__PURE__ */ jsx("br", {})] }),
		canExport && /* @__PURE__ */ jsx(Fragment, { children: "export " }),
		isDefault && /* @__PURE__ */ jsx(Fragment, { children: "default " }),
		"const ",
		name,
		" = ",
		async && /* @__PURE__ */ jsx(Fragment, { children: "async " }),
		generics && /* @__PURE__ */ jsxs(Fragment, { children: [
			"<",
			Array.isArray(generics) ? generics.join(", ").trim() : generics,
			">"
		] }),
		"(",
		params,
		")",
		returnType && !async && /* @__PURE__ */ jsxs(Fragment, { children: [": ", returnType] }),
		returnType && async && /* @__PURE__ */ jsxs(Fragment, { children: [
			": Promise",
			"<",
			returnType,
			">"
		] }),
		singleLine && /* @__PURE__ */ jsxs(Fragment, { children: [
			" => ",
			children,
			/* @__PURE__ */ jsx("br", {})
		] }),
		!singleLine && /* @__PURE__ */ jsxs(Fragment, { children: [
			" => {",
			/* @__PURE__ */ jsx("br", {}),
			/* @__PURE__ */ jsx("indent", {}),
			children,
			/* @__PURE__ */ jsx("br", {}),
			/* @__PURE__ */ jsx("dedent", {}),
			"}",
			/* @__PURE__ */ jsx("br", {})
		] })
	] });
}
ArrowFunction.displayName = "ArrowFunction";
Function.Arrow = ArrowFunction;

//#endregion
//#region src/components/Type.tsx
/**
* Generates a TypeScript type declaration.
*/
function Type({ children, ...props }) {
	const { name, export: canExport, JSDoc } = props;
	const nodeTree = useNodeTree();
	if (nodeTree) provide(NodeTreeContext, nodeTree.addChild({
		type: "Type",
		props
	}));
	if (name.charAt(0).toUpperCase() !== name.charAt(0)) throw new Error("Name should start with a capital letter(see TypeScript types)");
	return /* @__PURE__ */ jsxs(Fragment, { children: [
		(JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments) && /* @__PURE__ */ jsxs(Fragment, { children: [createJSDoc({ comments: JSDoc === null || JSDoc === void 0 ? void 0 : JSDoc.comments }), /* @__PURE__ */ jsx("br", {})] }),
		canExport && /* @__PURE__ */ jsx(Fragment, { children: "export " }),
		"type ",
		name,
		" = ",
		children
	] });
}
Type.displayName = "Type";

//#endregion
//#region src/devtools.ts
let isOpen = false;
function openDevtools() {
	if (isOpen) return;
	const customGlobal = global;
	customGlobal.WebSocket || (customGlobal.WebSocket = ws);
	customGlobal.window || (customGlobal.window = global);
	customGlobal.self || (customGlobal.self = global);
	customGlobal.isDevtoolsEnabled = true;
	customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = [
		{
			type: 2,
			value: "Context.Provider",
			isEnabled: true,
			isValid: true
		},
		{
			type: 2,
			value: "Root",
			isEnabled: true,
			isValid: true
		},
		{
			type: 2,
			value: "ErrorBoundary",
			isEnabled: true,
			isValid: true
		},
		{
			type: 2,
			value: "kubb-file",
			isEnabled: true,
			isValid: true
		},
		{
			type: 2,
			value: "kubb-text",
			isEnabled: true,
			isValid: true
		},
		{
			type: 2,
			value: "kubb-import",
			isEnabled: true,
			isValid: true
		},
		{
			type: 2,
			value: "kubb-export",
			isEnabled: true,
			isValid: true
		},
		{
			type: 2,
			value: "kubb-source",
			isEnabled: true,
			isValid: true
		}
	];
	import("react-devtools-core").then(async (devtools) => {
		console.info("Opening devtools");
		const controller = new AbortController();
		if (!isOpen) execa({
			stdio: "pipe",
			preferLocal: true,
			cancelSignal: controller.signal,
			gracefulCancel: true
		})`npx react-devtools@6.1.5`;
		isOpen = true;
		const { initialize, connectToDevTools } = (devtools === null || devtools === void 0 ? void 0 : devtools.default) || devtools;
		initialize();
		console.info("Initializing devtools");
		Renderer.injectIntoDevTools({
			bundleType: 1,
			version: "19.2.3",
			rendererPackageName: "kubb",
			findFiberByHostInstance: () => null
		});
		console.info("Connecting devtools");
		try {
			connectToDevTools({
				host: "localhost",
				port: 8097,
				useHttps: false,
				isAppActive: () => true
			});
		} catch (e) {
			console.error(e);
			console.info("Error when connecting the devtools");
		}
		onExit(() => {
			console.info("Disconnecting devtools");
			controller.abort();
		}, { alwaysLast: false });
	});
}

//#endregion
//#region src/createReactFabric.ts
function createReactFabric(config = {}) {
	if (config.devtools) openDevtools();
	const fabric = createFabric$1({ mode: config.mode });
	fabric.use(reactPlugin, {
		stdout: config.stdout,
		stderr: config.stderr,
		debug: config.debug,
		stdin: config.stdin
	});
	return fabric;
}

//#endregion
//#region src/utils/getFunctionParams.ts
function order(items) {
	return orderBy(items.filter(Boolean), [([_key, item]) => {
		if (item === null || item === void 0 ? void 0 : item.children) return 0;
		if (item === null || item === void 0 ? void 0 : item.optional) return 1;
		if (item === null || item === void 0 ? void 0 : item.default) return 2;
		return 0;
	}], ["asc"]);
}
function parseChild(key, item, options) {
	const entries = order(Object.entries(item.children));
	const types = [];
	const names = [];
	const optional = entries.every(([_key, item]) => (item === null || item === void 0 ? void 0 : item.optional) || !!(item === null || item === void 0 ? void 0 : item.default));
	entries.forEach(([key, entryItem]) => {
		if (entryItem) {
			const name = parseItem(key, {
				...entryItem,
				type: void 0
			}, options);
			if (entryItem.children) {
				const subTypes = Object.entries(entryItem.children).map(([key]) => {
					return key;
				}).join(", ");
				if (subTypes) names.push(`${name}: { ${subTypes} }`);
				else names.push(name);
			} else if (options.type === "call" && options.transformName) names.push(`${key}: ${name}`);
			else names.push(name);
			if (entries.some(([_key, item]) => item === null || item === void 0 ? void 0 : item.type)) types.push(parseItem(key, {
				...entryItem,
				default: void 0
			}, options));
		}
	});
	const name = item.mode === "inline" ? key : names.length ? `{ ${names.join(", ")} }` : void 0;
	const type = item.type ? item.type : types.length ? `{ ${types.join("; ")} }` : void 0;
	if (!name) return null;
	return parseItem(name, {
		type,
		default: item.default,
		optional: !item.default ? optional : void 0
	}, options);
}
function parseItem(name, item, options) {
	const acc = [];
	const transformedName = options.transformName ? options.transformName(name) : name;
	const transformedType = options.transformType && item.type ? options.transformType(item.type) : item.type;
	if (options.type === "object") return transformedName;
	if (options.type === "objectValue") return item.value ? `${transformedName}: ${item.value}` : transformedName;
	if (item.type && options.type === "constructor") if (item.optional) if (transformedName.startsWith("{")) acc.push(`${transformedName}: ${transformedType} = {}`);
	else acc.push(`${transformedName}?: ${transformedType}`);
	else acc.push(`${transformedName}: ${transformedType}${item.default ? ` = ${item.default}` : ""}`);
	else if (item.default && options.type === "constructor") acc.push(`${transformedName} = ${item.default}`);
	else if (item.value) acc.push(`${transformedName} : ${item.value}`);
	else if (item.mode === "inlineSpread") acc.push(`... ${transformedName}`);
	else acc.push(transformedName);
	return acc[0];
}
function getFunctionParams(params, options) {
	return order(Object.entries(params)).reduce((acc, [key, item]) => {
		if (!item) return acc;
		if (item.children) {
			if (Object.keys(item.children).length === 0) return acc;
			if (item.mode === "inlineSpread") return [...acc, getFunctionParams(item.children, options)];
			const parsedItem = parseChild(key, item, options);
			if (!parsedItem) return acc;
			return [...acc, parsedItem];
		}
		const parsedItem = parseItem(key, item, options);
		return [...acc, parsedItem];
	}, []).join(", ");
}
function createFunctionParams(params) {
	return params;
}
var _params = /* @__PURE__ */ new WeakMap();
var FunctionParams = class FunctionParams {
	static factory(params) {
		return new FunctionParams(params);
	}
	constructor(params) {
		_classPrivateFieldInitSpec(this, _params, void 0);
		_classPrivateFieldSet2(_params, this, params);
	}
	get params() {
		return _classPrivateFieldGet2(_params, this);
	}
	get flatParams() {
		const flatter = (acc, [key, item]) => {
			if (item === null || item === void 0 ? void 0 : item.children) return Object.entries(item.children).reduce(flatter, acc);
			if (item) acc[key] = item;
			return acc;
		};
		return Object.entries(_classPrivateFieldGet2(_params, this)).reduce(flatter, {});
	}
	toCall({ transformName, transformType } = {}) {
		return getFunctionParams(_classPrivateFieldGet2(_params, this), {
			type: "call",
			transformName,
			transformType
		});
	}
	toObject() {
		return getFunctionParams(_classPrivateFieldGet2(_params, this), { type: "object" });
	}
	toObjectValue() {
		return getFunctionParams(_classPrivateFieldGet2(_params, this), { type: "objectValue" });
	}
	toConstructor() {
		return getFunctionParams(_classPrivateFieldGet2(_params, this), { type: "constructor" });
	}
};

//#endregion
//#region src/index.ts
const useState = import_react.useState;
const useEffect = import_react.useEffect;
const useReducer = import_react.useReducer;
const useRef = import_react.useRef;

//#endregion
export { App, Const, File, FileManager, FileProcessor, Function, FunctionParams, Root, Runtime, TreeNode, Type, createContext, createFabric, createFile, createFunctionParams, createReactFabric, openDevtools, useApp, useContext, useEffect, useFile, useLifecycle, useReducer, useRef, useState };