import { C as parse, T as $ZodError, _ as string, a as snakeCase, b as url, h as object, n as constantCase, p as literal, r as pascalCase, v as union, w as parseAsync } from "./dist-fA4EItr0.mjs";
import { D as deleteOperationError, E as deleteOperation, F as setModelDescription, G as setStateSchema, H as setOperationErrorName, I as setModelExtension, L as setModelId, M as setAuthorName, N as setAuthorWebsite, P as setInitialState, R as setModelName, T as deleteModule, U as setOperationName, V as setOperationDescription, W as setOperationSchema, X as generateId, f as addModule, m as addOperationError, p as addOperation, z as setModuleName } from "./document-drive-DjL9iikf.mjs";
import { c as FormProvider, d as set, f as useForm, l as appendErrors, p as useFormContext, r as DocumentToolbar, s as Controller, u as get } from "./connect-C8Ur6M5x.mjs";
import { C as twMerge, y as composeRefs } from "./dist-BeZaEP6S.mjs";
import { E as useSetPHDocumentEditorConfig, b as useSelectedDocumentOfType, y as usePHToast } from "./dist-D3qXr1ES.mjs";
import { a as handleModelNameChange, c as makeEmptyOperationSchema, d as makeOperationInitialDoc, i as compareStringsWithoutWhitespace, l as makeInitialSchemaDoc, o as initializeModelSchema, p as renameSchemaType, s as isEmptyOperationSchema, t as ensureValidOperationSchemaInputName } from "./linting-Dx50GuLN.mjs";
import { t as SchemaContextProvider } from "./schema-context-CX5ml_9t.mjs";
import * as React$1 from "react";
import React, { Suspense, forwardRef, lazy, useCallback, useEffect, useId, useImperativeHandle, useRef, useState } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import "react-dom";
//#region ../../node_modules/.pnpm/@radix-ui+react-slot@1.2.4_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-slot/dist/index.mjs
var REACT_LAZY_TYPE = Symbol.for("react.lazy");
var use$1 = React$1[" use ".trim().toString()];
function isPromiseLike(value) {
	return typeof value === "object" && value !== null && "then" in value;
}
function isLazyComponent(element) {
	return element != null && typeof element === "object" && "$$typeof" in element && element.$$typeof === REACT_LAZY_TYPE && "_payload" in element && isPromiseLike(element._payload);
}
/* @__NO_SIDE_EFFECTS__ */
function createSlot(ownerName) {
	const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);
	const Slot2 = React$1.forwardRef((props, forwardedRef) => {
		let { children, ...slotProps } = props;
		if (isLazyComponent(children) && typeof use$1 === "function") children = use$1(children._payload);
		const childrenArray = React$1.Children.toArray(children);
		const slottable = childrenArray.find(isSlottable);
		if (slottable) {
			const newElement = slottable.props.children;
			const newChildren = childrenArray.map((child) => {
				if (child === slottable) {
					if (React$1.Children.count(newElement) > 1) return React$1.Children.only(null);
					return React$1.isValidElement(newElement) ? newElement.props.children : null;
				} else return child;
			});
			return /* @__PURE__ */ jsx(SlotClone, {
				...slotProps,
				ref: forwardedRef,
				children: React$1.isValidElement(newElement) ? React$1.cloneElement(newElement, void 0, newChildren) : null
			});
		}
		return /* @__PURE__ */ jsx(SlotClone, {
			...slotProps,
			ref: forwardedRef,
			children
		});
	});
	Slot2.displayName = `${ownerName}.Slot`;
	return Slot2;
}
var Slot = /* @__PURE__ */ createSlot("Slot");
/* @__NO_SIDE_EFFECTS__ */
function createSlotClone(ownerName) {
	const SlotClone = React$1.forwardRef((props, forwardedRef) => {
		let { children, ...slotProps } = props;
		if (isLazyComponent(children) && typeof use$1 === "function") children = use$1(children._payload);
		if (React$1.isValidElement(children)) {
			const childrenRef = getElementRef(children);
			const props2 = mergeProps(slotProps, children.props);
			if (children.type !== React$1.Fragment) props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
			return React$1.cloneElement(children, props2);
		}
		return React$1.Children.count(children) > 1 ? React$1.Children.only(null) : null;
	});
	SlotClone.displayName = `${ownerName}.SlotClone`;
	return SlotClone;
}
var SLOTTABLE_IDENTIFIER = Symbol("radix.slottable");
function isSlottable(child) {
	return React$1.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;
}
function mergeProps(slotProps, childProps) {
	const overrideProps = { ...childProps };
	for (const propName in childProps) {
		const slotPropValue = slotProps[propName];
		const childPropValue = childProps[propName];
		if (/^on[A-Z]/.test(propName)) {
			if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => {
				const result = childPropValue(...args);
				slotPropValue(...args);
				return result;
			};
			else if (slotPropValue) overrideProps[propName] = slotPropValue;
		} else if (propName === "style") overrideProps[propName] = {
			...slotPropValue,
			...childPropValue
		};
		else if (propName === "className") overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
	}
	return {
		...slotProps,
		...overrideProps
	};
}
function getElementRef(element) {
	let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
	let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
	if (mayWarn) return element.ref;
	getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
	mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
	if (mayWarn) return element.props.ref;
	return element.props.ref || element.ref;
}
//#endregion
//#region ../../node_modules/.pnpm/@radix-ui+react-primitive@2.1.4_@types+react-dom@19.2.3_@types+react@19.2.14__@types+re_c8c8fd2647f03197dbf56370d7498033/node_modules/@radix-ui/react-primitive/dist/index.mjs
var Primitive = [
	"a",
	"button",
	"div",
	"form",
	"h2",
	"h3",
	"img",
	"input",
	"label",
	"li",
	"nav",
	"ol",
	"p",
	"select",
	"span",
	"svg",
	"ul"
].reduce((primitive, node) => {
	const Slot = /* @__PURE__ */ createSlot(`Primitive.${node}`);
	const Node = React$1.forwardRef((props, forwardedRef) => {
		const { asChild, ...primitiveProps } = props;
		const Comp = asChild ? Slot : node;
		if (typeof window !== "undefined") window[Symbol.for("radix-ui")] = true;
		return /* @__PURE__ */ jsx(Comp, {
			...primitiveProps,
			ref: forwardedRef
		});
	});
	Node.displayName = `Primitive.${node}`;
	return {
		...primitive,
		[node]: Node
	};
}, {});
//#endregion
//#region ../../node_modules/.pnpm/clsx@2.0.0/node_modules/clsx/dist/clsx.mjs
function r$1(e) {
	var t, f, n = "";
	if ("string" == typeof e || "number" == typeof e) n += e;
	else if ("object" == typeof e) if (Array.isArray(e)) for (t = 0; t < e.length; t++) e[t] && (f = r$1(e[t])) && (n && (n += " "), n += f);
	else for (t in e) e[t] && (n && (n += " "), n += t);
	return n;
}
function clsx() {
	for (var e, t, f = 0, n = ""; f < arguments.length;) (e = arguments[f++]) && (t = r$1(e)) && (n && (n += " "), n += t);
	return n;
}
//#endregion
//#region ../../node_modules/.pnpm/class-variance-authority@0.7.0/node_modules/class-variance-authority/dist/index.mjs
const falsyToString = (value) => typeof value === "boolean" ? "".concat(value) : value === 0 ? "0" : value;
const cx = clsx;
const cva = (base, config) => {
	return (props) => {
		var ref;
		if ((config === null || config === void 0 ? void 0 : config.variants) == null) return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
		const { variants, defaultVariants } = config;
		const getVariantClassNames = Object.keys(variants).map((variant) => {
			const variantProp = props === null || props === void 0 ? void 0 : props[variant];
			const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];
			if (variantProp === null) return null;
			const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);
			return variants[variant][variantKey];
		});
		const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param) => {
			let [key, value] = param;
			if (value === void 0) return acc;
			acc[key] = value;
			return acc;
		}, {});
		return cx(base, getVariantClassNames, config === null || config === void 0 ? void 0 : (ref = config.compoundVariants) === null || ref === void 0 ? void 0 : ref.reduce((acc, param1) => {
			let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param1;
			return Object.entries(compoundVariantOptions).every((param) => {
				let [key, value] = param;
				return Array.isArray(value) ? value.includes({
					...defaultVariants,
					...propsWithoutUndefined
				}[key]) : {
					...defaultVariants,
					...propsWithoutUndefined
				}[key] === value;
			}) ? [
				...acc,
				cvClass,
				cvClassName
			] : acc;
		}, []), props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
	};
};
//#endregion
//#region editors/document-model-editor/components/divider.tsx
function Divider({ className, size = "sm", margin = "md" }) {
	function getSize() {
		if (size === "sm") return "h-px";
		if (size === "md") return "h-1";
		return "h-1.5";
	}
	function getMargin() {
		if (margin === "sm") return "my-4";
		if (margin === "md") return "my-6";
		return "my-8";
	}
	return /* @__PURE__ */ jsx("div", { className: twMerge("bg-gray-200 dark:bg-slate-600 dark:text-slate-100", getSize(), getMargin(), className) });
}
//#endregion
//#region ../../node_modules/.pnpm/@hookform+resolvers@5.2.2_react-hook-form@7.71.2_react@19.2.6_/node_modules/@hookform/resolvers/dist/resolvers.mjs
const r = (t, r, o) => {
	if (t && "reportValidity" in t) {
		const s = get(o, r);
		t.setCustomValidity(s && s.message || ""), t.reportValidity();
	}
}, o = (e, t) => {
	for (const o in t.fields) {
		const s = t.fields[o];
		s && s.ref && "reportValidity" in s.ref ? r(s.ref, o, e) : s && s.refs && s.refs.forEach((t) => r(t, o, e));
	}
}, s$1 = (r, s) => {
	s.shouldUseNativeValidation && o(r, s);
	const n = {};
	for (const o in r) {
		const f = get(s.fields, o), c = Object.assign(r[o] || {}, { ref: f && f.ref });
		if (i$1(s.names || Object.keys(r), o)) {
			const r = Object.assign({}, get(n, o));
			set(r, "root", c), set(n, o, r);
		} else set(n, o, c);
	}
	return n;
}, i$1 = (e, t) => {
	const r = n(t);
	return e.some((e) => n(e).match(`^${r}\\.\\d+`));
};
function n(e) {
	return e.replace(/\]|\[/g, "");
}
//#endregion
//#region ../../node_modules/.pnpm/@hookform+resolvers@5.2.2_react-hook-form@7.71.2_react@19.2.6_/node_modules/@hookform/resolvers/zod/dist/zod.mjs
function t(r, e) {
	try {
		var o = r();
	} catch (r) {
		return e(r);
	}
	return o && o.then ? o.then(void 0, e) : o;
}
function s(r, e) {
	for (var n = {}; r.length;) {
		var t = r[0], s = t.code, i = t.message, a = t.path.join(".");
		if (!n[a]) if ("unionErrors" in t) {
			var u = t.unionErrors[0].errors[0];
			n[a] = {
				message: u.message,
				type: u.code
			};
		} else n[a] = {
			message: i,
			type: s
		};
		if ("unionErrors" in t && t.unionErrors.forEach(function(e) {
			return e.errors.forEach(function(e) {
				return r.push(e);
			});
		}), e) {
			var c = n[a].types, f = c && c[t.code];
			n[a] = appendErrors(a, e, n, s, f ? [].concat(f, t.message) : t.message);
		}
		r.shift();
	}
	return n;
}
function i(r, e) {
	for (var n = {}; r.length;) {
		var t = r[0], s = t.code, i = t.message, a = t.path.join(".");
		if (!n[a]) if ("invalid_union" === t.code && t.errors.length > 0) {
			var u = t.errors[0][0];
			n[a] = {
				message: u.message,
				type: u.code
			};
		} else n[a] = {
			message: i,
			type: s
		};
		if ("invalid_union" === t.code && t.errors.forEach(function(e) {
			return e.forEach(function(e) {
				return r.push(e);
			});
		}), e) {
			var c = n[a].types, f = c && c[t.code];
			n[a] = appendErrors(a, e, n, s, f ? [].concat(f, t.message) : t.message);
		}
		r.shift();
	}
	return n;
}
function a(o$1, a, u) {
	if (void 0 === u && (u = {}), function(r) {
		return "_def" in r && "object" == typeof r._def && "typeName" in r._def;
	}(o$1)) return function(n, i, c) {
		try {
			return Promise.resolve(t(function() {
				return Promise.resolve(o$1["sync" === u.mode ? "parse" : "parseAsync"](n, a)).then(function(e) {
					return c.shouldUseNativeValidation && o({}, c), {
						errors: {},
						values: u.raw ? Object.assign({}, n) : e
					};
				});
			}, function(r) {
				if (function(r) {
					return Array.isArray(null == r ? void 0 : r.issues);
				}(r)) return {
					values: {},
					errors: s$1(s(r.errors, !c.shouldUseNativeValidation && "all" === c.criteriaMode), c)
				};
				throw r;
			}));
		} catch (r) {
			return Promise.reject(r);
		}
	};
	if (function(r) {
		return "_zod" in r && "object" == typeof r._zod;
	}(o$1)) return function(s, c, f) {
		try {
			return Promise.resolve(t(function() {
				return Promise.resolve(("sync" === u.mode ? parse : parseAsync)(o$1, s, a)).then(function(e) {
					return f.shouldUseNativeValidation && o({}, f), {
						errors: {},
						values: u.raw ? Object.assign({}, s) : e
					};
				});
			}, function(r) {
				if (function(r) {
					return r instanceof $ZodError;
				}(r)) return {
					values: {},
					errors: s$1(i(r.issues, !f.shouldUseNativeValidation && "all" === f.criteriaMode), f)
				};
				throw r;
			}));
		} catch (r) {
			return Promise.reject(r);
		}
	};
	throw new Error("Invalid input: not a Zod schema");
}
//#endregion
//#region editors/document-model-editor/schemas/inputs.ts
const isUppercase = (value) => !/\p{Ll}/u.test(value);
const isLowercase = (value) => !/\p{Lu}/u.test(value);
function createNameSchema(options = {}) {
	const { required = false, allowEmpty = false, unique = [] } = options;
	const baseSchema = allowEmpty ? string() : string().min(1);
	const uniqueRefinement = baseSchema.refine((value) => {
		if (!value && allowEmpty) return true;
		return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
	}, { message: "Item with this name already exists" });
	if (!required) return unique.length > 0 ? string().optional().refine((value) => {
		if (value === void 0) return true;
		if (!value && allowEmpty) return true;
		return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
	}, { message: "Item with this name already exists" }) : string().optional();
	return unique.length > 0 ? uniqueRefinement : baseSchema;
}
function createConstantCaseSchema(options = {}) {
	return createNameSchema(options).transform((value) => value ? value.toUpperCase() : value).refine((value) => !value || isUppercase(value), { message: "Must be uppercase" });
}
function createLowercaseSnakeCaseSchema(options = {}) {
	return createNameSchema(options).transform((value) => value ? value.toLowerCase() : value).refine((value) => !value || isLowercase(value), { message: "Must be lowercase" });
}
function toLowercaseSnakeCase(value, options = {}) {
	return createLowercaseSnakeCaseSchema(options).parse(snakeCase(value));
}
function toConstantCase(value, options = {}) {
	return createConstantCaseSchema(options).parse(constantCase(value));
}
object({
	name: createNameSchema({ allowEmpty: true }),
	website: union([url(), literal("")]).optional().default("")
}).default({
	name: "",
	website: ""
});
//#endregion
//#region editors/document-model-editor/context/form-context.ts
const FormFieldContext = React.createContext({});
const FormItemContext = React.createContext({});
//#endregion
//#region editors/document-model-editor/hooks/useFormField.ts
const useFormField = () => {
	const fieldContext = React.useContext(FormFieldContext);
	const itemContext = React.useContext(FormItemContext);
	const { getFieldState, formState } = useFormContext();
	const fieldState = getFieldState(fieldContext.name, formState);
	if (!fieldContext) throw new Error("useFormField should be used within <FormField>");
	const { id } = itemContext;
	return {
		id,
		name: fieldContext.name,
		formItemId: `${id}-form-item`,
		formDescriptionId: `${id}-form-item-description`,
		formMessageId: `${id}-form-item-message`,
		...fieldState
	};
};
//#endregion
//#region ../../node_modules/.pnpm/@radix-ui+react-label@2.1.8_@types+react-dom@19.2.3_@types+react@19.2.14__@types+react@_8d35ec453e0b59eefe06771bb1432577/node_modules/@radix-ui/react-label/dist/index.mjs
var NAME = "Label";
var Label$1 = React$1.forwardRef((props, forwardedRef) => {
	return /* @__PURE__ */ jsx(Primitive.label, {
		...props,
		ref: forwardedRef,
		onMouseDown: (event) => {
			if (event.target.closest("button, input, select, textarea")) return;
			props.onMouseDown?.(event);
			if (!event.defaultPrevented && event.detail > 1) event.preventDefault();
		}
	});
});
Label$1.displayName = NAME;
var Root = Label$1;
//#endregion
//#region editors/document-model-editor/components/label.tsx
const labelVariants = cva("text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70");
const Label = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Root, {
	ref,
	className: twMerge(labelVariants(), className),
	...props
}));
Label.displayName = Root.displayName;
//#endregion
//#region editors/document-model-editor/components/form.tsx
const Form = FormProvider;
const FormField = ({ ...props }) => {
	return /* @__PURE__ */ jsx(FormFieldContext.Provider, {
		value: { name: props.name },
		children: /* @__PURE__ */ jsx(Controller, { ...props })
	});
};
const FormItem = React$1.forwardRef(({ className, ...props }, ref) => {
	const id = React$1.useId();
	return /* @__PURE__ */ jsx(FormItemContext.Provider, {
		value: { id },
		children: /* @__PURE__ */ jsx("div", {
			ref,
			className,
			...props
		})
	});
});
FormItem.displayName = "FormItem";
const FormLabel = React$1.forwardRef(({ className, ...props }, ref) => {
	const { error, formItemId } = useFormField();
	return /* @__PURE__ */ jsx(Label, {
		ref,
		className: twMerge(error && "text-red-900 dark:text-red-400", className),
		htmlFor: formItemId,
		...props
	});
});
FormLabel.displayName = "FormLabel";
const FormControl = React$1.forwardRef(({ ...props }, ref) => {
	const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
	return /* @__PURE__ */ jsx(Slot, {
		ref,
		id: formItemId,
		"aria-describedby": !error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`,
		"aria-invalid": !!error,
		...props
	});
});
FormControl.displayName = "FormControl";
const FormDescription = React$1.forwardRef(({ className, ...props }, ref) => {
	const { formDescriptionId } = useFormField();
	return /* @__PURE__ */ jsx("p", {
		ref,
		id: formDescriptionId,
		className: twMerge("text-sm text-gray-700 dark:text-slate-200", className),
		...props
	});
});
FormDescription.displayName = "FormDescription";
const FormMessage = React$1.forwardRef(({ className, children, ...props }, ref) => {
	const { error, formMessageId } = useFormField();
	const body = error ? String(error.message) : children;
	if (!body) return null;
	return /* @__PURE__ */ jsx("p", {
		ref,
		id: formMessageId,
		className: twMerge("text-sm font-medium text-red-800 dark:text-red-100", className),
		...props,
		children: body
	});
});
FormMessage.displayName = "FormMessage";
//#endregion
//#region editors/document-model-editor/components/text-area.tsx
const Textarea = forwardRef(({ className, ...props }, ref) => {
	const textareaRef = useRef(null);
	const adjustHeight = useCallback((textarea) => {
		textarea.style.height = "auto";
		const newHeight = Math.max(textarea.scrollHeight, textarea.offsetHeight);
		textarea.style.height = `${newHeight}px`;
	}, []);
	const handleInput = useCallback((e) => {
		adjustHeight(e.currentTarget);
	}, [adjustHeight]);
	React$1.useEffect(() => {
		if (textareaRef.current) adjustHeight(textareaRef.current);
	}, [adjustHeight]);
	useImperativeHandle(ref, () => ({
		focus: () => textareaRef.current?.focus(),
		element: textareaRef.current
	}));
	return /* @__PURE__ */ jsx("textarea", {
		...props,
		className: twMerge("min-h-10 w-full resize-none rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-600 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-500 dark:bg-slate-600 dark:text-slate-100 dark:placeholder:text-slate-300", className),
		ref: textareaRef,
		onInput: handleInput
	});
});
Textarea.displayName = "Textarea";
//#endregion
//#region editors/document-model-editor/components/text-field.tsx
const TextField = forwardRef(({ name, value, onSubmit, label, placeholder, unique, className = "", rows = 1, focusOnMount = false, required = false, allowEmpty = false, shouldReset = false, onChange }, ref) => {
	const textareaRef = useRef(null);
	const id = useId();
	useEffect(() => {
		if (focusOnMount && textareaRef.current) textareaRef.current.focus();
	}, [focusOnMount]);
	const form = useForm({
		resolver: a(object({ [name]: createNameSchema({
			required,
			allowEmpty,
			unique
		}) })),
		defaultValues: { [name]: value ?? "" }
	});
	const handleSubmit = useCallback((values) => {
		const newValue = values[name];
		if (newValue === void 0 || value === newValue) return;
		onSubmit(newValue);
		if (shouldReset) form.reset({ [name]: "" });
	}, [
		name,
		value,
		onSubmit,
		form,
		shouldReset
	]);
	const handleBlur = useCallback(async () => {
		const currentValue = form.getValues()[name] ?? "";
		if (value === null || value === void 0) {
			if (!currentValue || currentValue.trim() === "") return;
		}
		if (compareStringsWithoutWhitespace(currentValue, value ?? "")) return;
		try {
			await form.trigger();
			if (form.formState.isValid) await form.handleSubmit(handleSubmit)();
		} catch (_e) {}
	}, [
		form,
		handleSubmit,
		name,
		value
	]);
	const onEnterKeyDown = useCallback((e) => {
		if (e.key === "Enter") {
			e.preventDefault();
			e.target.blur();
		}
	}, []);
	const handleChange = useCallback((e) => {
		const newValue = e.target.value;
		onChange?.(newValue);
	}, [onChange]);
	useImperativeHandle(ref, () => ({ focus: () => textareaRef.current?.focus() }));
	useEffect(() => {
		form.reset({ [name]: value ?? "" });
	}, [
		form,
		name,
		value
	]);
	return /* @__PURE__ */ jsx(Form, {
		...form,
		children: /* @__PURE__ */ jsx(FormField, {
			control: form.control,
			name,
			render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, {
				className: "grid h-full grid-rows-[auto,1fr] gap-2 overflow-visible",
				children: [
					!!label && /* @__PURE__ */ jsx(FormLabel, {
						htmlFor: name,
						className: "text-sm font-medium text-gray-700 dark:text-slate-200",
						children: label
					}),
					/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Textarea, {
						...field,
						id,
						name,
						ref: (node) => {
							if (node) {
								field.ref(node.element);
								textareaRef.current = node;
							}
						},
						placeholder,
						onBlur: () => void handleBlur(),
						onChange: (e) => {
							field.onChange(e);
							handleChange(e);
						},
						onKeyDown: onEnterKeyDown,
						rows,
						className
					}) }),
					/* @__PURE__ */ jsx(FormMessage, {})
				]
			})
		})
	});
});
TextField.displayName = "TextField";
object({
	name: string(),
	documentType: string(),
	extension: string().optional().default(""),
	description: string(),
	authorName: string(),
	authorWebsite: string()
});
function ModelMetadata(props) {
	return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(ModelNameForm, { ...props }), /* @__PURE__ */ jsx("div", {
		className: "flex h-full flex-col gap-4",
		children: /* @__PURE__ */ jsxs("div", {
			className: "grid flex-1 grid-cols-3 items-start gap-4",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "col-span-2 flex h-full flex-col gap-4",
				children: [/* @__PURE__ */ jsx("div", {
					className: "shrink-0",
					children: /* @__PURE__ */ jsx(DocumentTypeForm, { ...props })
				}), /* @__PURE__ */ jsx("div", {
					className: "min-h-0 flex-1",
					children: /* @__PURE__ */ jsx(DescriptionForm, { ...props })
				})]
			}), /* @__PURE__ */ jsxs("div", {
				className: "col-span-1 flex flex-col gap-4",
				children: [
					/* @__PURE__ */ jsx(AuthorNameForm, { ...props }),
					/* @__PURE__ */ jsx(AuthorWebsiteForm, { ...props }),
					/* @__PURE__ */ jsx(ModelExtensionForm, { ...props })
				]
			})]
		})
	})] });
}
function ModelNameForm(props) {
	const { name, globalStateSchema, localStateSchema, setModelName, setStateSchema } = props;
	return /* @__PURE__ */ jsx(TextField, {
		name: "name",
		value: name,
		onSubmit: useCallback((newName) => {
			if (name === newName) return;
			setModelName(newName);
			if (!!!globalStateSchema) {
				setStateSchema(makeInitialSchemaDoc(newName, "global"), "global");
				return;
			}
			setStateSchema(renameSchemaType(globalStateSchema, name, newName, "global"), "global");
			if (localStateSchema) setStateSchema(renameSchemaType(localStateSchema, name, newName, "local"), "local");
			handleModelNameChange({
				oldName: name,
				newName,
				globalStateSchema,
				localStateSchema,
				setStateSchema
			});
		}, [
			name,
			globalStateSchema,
			localStateSchema,
			setStateSchema,
			setModelName
		]),
		placeholder: "Model name",
		className: "border-none pl-0 text-xl font-bold text-gray-900 dark:text-slate-50",
		required: true,
		focusOnMount: true
	});
}
function DocumentTypeForm(props) {
	const { documentType, setModelId } = props;
	return /* @__PURE__ */ jsx(TextField, {
		label: "Document Type *",
		name: "powerhouse/document-model",
		value: documentType,
		onSubmit: setModelId,
		placeholder: "Document Type",
		required: true
	});
}
function ModelExtensionForm(props) {
	const { extension, setModelExtension } = props;
	return /* @__PURE__ */ jsx(TextField, {
		name: "extension",
		value: extension,
		onSubmit: setModelExtension,
		label: "Model Extension",
		placeholder: "Example .phdm",
		allowEmpty: true
	});
}
function DescriptionForm(props) {
	const { description, setModelDescription } = props;
	return /* @__PURE__ */ jsx(TextField, {
		name: "description",
		label: "Model Description",
		value: description,
		onSubmit: setModelDescription,
		placeholder: "Describe your document to others",
		allowEmpty: true,
		className: "h-full"
	});
}
function AuthorNameForm(props) {
	const { authorName, setAuthorName } = props;
	return /* @__PURE__ */ jsx(TextField, {
		name: "authorName",
		value: authorName,
		onSubmit: setAuthorName,
		label: "Author Name",
		placeholder: "Username or organisation",
		allowEmpty: true
	});
}
function AuthorWebsiteForm(props) {
	const { authorWebsite, setAuthorWebsite } = props;
	return /* @__PURE__ */ jsx(TextField, {
		name: "authorWebsite",
		value: authorWebsite,
		label: "Website URL",
		onSubmit: (newAuthorWebsite) => {
			if (!!authorWebsite && !newAuthorWebsite) return;
			setAuthorWebsite(newAuthorWebsite);
		},
		placeholder: "https://www.powerhouse.inc/",
		allowEmpty: true
	});
}
//#endregion
//#region editors/document-model-editor/components/module-form.tsx
function ModuleForm({ module, onAddModule, updateModuleName, modules = [] }) {
	const isEdit = !!module;
	const moduleNames = modules.map((m) => m.name);
	const handleSubmit = async (name) => {
		const formattedName = toLowercaseSnakeCase(name);
		if (!formattedName.length) return;
		if (isEdit) {
			if (formattedName !== module.name) updateModuleName(module.id, formattedName);
		} else await onAddModule(formattedName);
	};
	return /* @__PURE__ */ jsx(TextField, {
		name: "name",
		label: isEdit ? "Module name *" : "Add module *",
		value: module?.name,
		onSubmit: (name) => void handleSubmit(name),
		placeholder: "Add module",
		unique: moduleNames,
		shouldReset: !isEdit,
		required: true
	}, module?.id ?? "new");
}
//#endregion
//#region editors/document-model-editor/components/operation-form.tsx
function OperationForm({ operation, module, focusOnMount, allOperationNames, onAddOperationAndInitialSchema, updateOperationName, deleteOperation }) {
	const isEdit = !!operation;
	const handleSubmit = async (name) => {
		if (isEdit && name === "") {
			deleteOperation(operation.id);
			return;
		}
		const formattedName = toConstantCase(name);
		if (isEdit) {
			if (formattedName !== operation.name) updateOperationName(operation.id, formattedName);
		} else await onAddOperationAndInitialSchema(module.id, formattedName);
	};
	const handleChange = (value) => {
		if (isEdit && value === "") deleteOperation(operation.id);
	};
	return /* @__PURE__ */ jsx(TextField, {
		name: "name",
		value: operation?.name,
		label: isEdit ? "Operation name *" : "Add operation *",
		onSubmit: (name) => void handleSubmit(name),
		onChange: handleChange,
		placeholder: "Add operation",
		required: !isEdit,
		allowEmpty: !isEdit,
		shouldReset: !isEdit,
		focusOnMount,
		unique: allOperationNames
	});
}
//#endregion
//#region editors/document-model-editor/components/operation-description-form.tsx
function OperationDescriptionForm({ operation, focusOnMount, setOperationDescription }) {
	const textFieldRef = useRef(null);
	useEffect(() => {
		if (focusOnMount && textFieldRef.current) textFieldRef.current.focus();
	}, [focusOnMount]);
	return /* @__PURE__ */ jsx(TextField, {
		ref: textFieldRef,
		name: "description",
		value: operation.description,
		onSubmit: (newDescription) => setOperationDescription(operation.id, newDescription),
		label: "Operation description",
		allowEmpty: true,
		placeholder: "Operation Description"
	});
}
//#endregion
//#region editors/document-model-editor/components/operation-error-form.tsx
function OperationErrorForm({ operation, error, focusOnMount, onSubmit, onAddOperationError, deleteOperationError, setOperationErrorName }) {
	const textFieldRef = useRef(null);
	const isEdit = !!error;
	const allOperationErrorNames = operation.errors.map((o) => o.name).filter((n) => n !== null);
	const handleSubmit = (name) => {
		if (isEdit && name === "") {
			deleteOperationError(error.id);
			return;
		}
		const formattedName = pascalCase(name);
		if (isEdit) setOperationErrorName(operation.id, error.id, formattedName);
		else onAddOperationError(operation.id, formattedName);
		onSubmit?.();
	};
	const handleChange = (value) => {
		if (isEdit && value === "") deleteOperationError(error.id);
	};
	return /* @__PURE__ */ jsx(TextField, {
		ref: textFieldRef,
		name: "name",
		value: error?.name,
		onSubmit: handleSubmit,
		onChange: handleChange,
		placeholder: "Add exception",
		required: !isEdit,
		allowEmpty: !isEdit,
		shouldReset: !isEdit,
		unique: allOperationErrorNames,
		focusOnMount
	});
}
//#endregion
//#region editors/document-model-editor/components/operation-errors.tsx
function OperationErrors({ operation, addOperationError, deleteOperationError, setOperationErrorName }) {
	const addErrorFormId = useId();
	const [shouldFocusAddForm, setShouldFocusAddForm] = useState(false);
	const onAddOperationError = useCallback(async (operationId, error) => {
		const errorId = await addOperationError(operationId, error);
		if (errorId) setShouldFocusAddForm(true);
		return errorId;
	}, [addOperationError, setShouldFocusAddForm]);
	const onAddOperationErrorSubmit = useCallback(() => setShouldFocusAddForm(false), [setShouldFocusAddForm]);
	return /* @__PURE__ */ jsxs("ul", {
		className: "ml-4 list-disc",
		children: [operation.errors.map((error) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
			error,
			operation,
			onAddOperationError,
			deleteOperationError,
			setOperationErrorName
		}) }, error.id)), /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
			operation,
			onAddOperationError,
			deleteOperationError,
			setOperationErrorName,
			focusOnMount: shouldFocusAddForm,
			onSubmit: onAddOperationErrorSubmit
		}, `${addErrorFormId}-${shouldFocusAddForm}`) })]
	});
}
//#endregion
//#region editors/document-model-editor/components/operation.tsx
const GraphqlEditor = lazy(() => import("./graphql-editor-BiK6s8_B.mjs"));
function Operation(props) {
	const { operation, module, allOperationNames, lastCreatedOperationId, onAddOperationAndInitialSchema, updateOperationName, deleteOperation, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
	const noInputRequired = isEmptyOperationSchema(operation.schema);
	const handleToggleNoInput = useCallback((checked) => toggleNoInputRequired(operation.id, checked), [operation.id, toggleNoInputRequired]);
	const handleUpdateDocument = useCallback((newDoc) => updateOperationSchema(operation.id, newDoc), [operation.id, updateOperationSchema]);
	const customLinter = useCallback((doc) => operation.name ? ensureValidOperationSchemaInputName(doc, operation.name) : [], [operation.name]);
	return /* @__PURE__ */ jsxs("div", {
		className: "mt-4 grid grid-cols-2 gap-x-12",
		style: {
			gridTemplateAreas: `
        "left editor"
        "errors editor"
      `,
			gridTemplateRows: "auto 1fr"
		},
		children: [
			/* @__PURE__ */ jsxs("div", {
				className: "flex flex-col gap-2",
				style: { gridArea: "left" },
				children: [/* @__PURE__ */ jsx(OperationForm, {
					operation,
					onAddOperationAndInitialSchema,
					updateOperationName,
					deleteOperation,
					module,
					allOperationNames
				}), /* @__PURE__ */ jsx(OperationDescriptionForm, {
					operation,
					focusOnMount: operation.id === lastCreatedOperationId,
					setOperationDescription
				})]
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "relative top-8",
				style: { gridArea: "editor" },
				children: [/* @__PURE__ */ jsxs("label", {
					className: "mb-2 flex cursor-pointer items-center gap-2",
					children: [/* @__PURE__ */ jsx("input", {
						type: "checkbox",
						checked: noInputRequired,
						onChange: (e) => handleToggleNoInput(e.target.checked),
						className: "size-4 rounded-sm border-gray-300 dark:border-slate-500 dark:bg-slate-600 dark:text-slate-100"
					}), /* @__PURE__ */ jsx("span", {
						className: "text-sm text-gray-700 dark:text-slate-200",
						children: "Operation with no inputs"
					})]
				}), !noInputRequired && /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(GraphqlEditor, {
					doc: operation.schema ?? "",
					updateDocumentInModel: handleUpdateDocument,
					customLinter
				}) })]
			}),
			/* @__PURE__ */ jsxs("div", {
				style: { gridArea: "errors" },
				children: [/* @__PURE__ */ jsx("h3", {
					className: "my-2 text-sm font-medium text-gray-700 dark:text-slate-200",
					children: "Reducer Exceptions"
				}), /* @__PURE__ */ jsx(OperationErrors, {
					operation,
					addOperationError,
					deleteOperationError,
					setOperationErrorName
				})]
			})
		]
	});
}
//#endregion
//#region editors/document-model-editor/components/operations.tsx
function Operations({ module, allOperations, shouldFocusNewOperation, updateOperationName, deleteOperation, addOperationAndInitialSchema, addOperationError, deleteOperationError, setOperationErrorName, updateOperationSchema, setOperationDescription, toggleNoInputRequired }) {
	const [lastCreatedOperationId, setLastCreatedOperationId] = useState(null);
	const addOperationFormId = useId();
	const allOperationNames = allOperations.map((o) => o.name).filter((n) => n !== null);
	const onAddOperationAndInitialSchema = useCallback(async (moduleId, name) => {
		const operationId = await addOperationAndInitialSchema(moduleId, name);
		if (operationId) setLastCreatedOperationId(operationId);
		return operationId;
	}, [addOperationAndInitialSchema, setLastCreatedOperationId]);
	return /* @__PURE__ */ jsxs("div", { children: [module.operations.map((operation) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Operation, {
		operation,
		module,
		lastCreatedOperationId,
		allOperationNames,
		addOperationError,
		deleteOperationError,
		setOperationErrorName,
		onAddOperationAndInitialSchema,
		updateOperationName,
		deleteOperation,
		updateOperationSchema,
		setOperationDescription,
		toggleNoInputRequired
	}) }, operation.id)), /* @__PURE__ */ jsx("div", {
		className: "mt-6 w-1/2 pr-6",
		children: /* @__PURE__ */ jsx(OperationForm, {
			onAddOperationAndInitialSchema,
			updateOperationName,
			deleteOperation,
			module,
			allOperationNames,
			focusOnMount: shouldFocusNewOperation
		}, addOperationFormId)
	})] });
}
//#endregion
//#region editors/document-model-editor/components/module.tsx
function Module(props) {
	const { module, modules, allOperations, lastCreatedModuleId, onAddModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
	return /* @__PURE__ */ jsxs("div", {
		className: "relative rounded-3xl bg-gray-100 p-6 dark:bg-slate-700",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "mb-2 w-1/2 pr-6",
			children: [/* @__PURE__ */ jsx(ModuleForm, {
				modules,
				module,
				onAddModule,
				updateModuleName
			}), !!module && /* @__PURE__ */ jsx("button", {
				"aria-label": "Delete module",
				tabIndex: -1,
				className: "absolute top-1 right-1 p-2 text-gray-900 transition-colors hover:text-gray-500 dark:text-slate-100 dark:hover:text-slate-400",
				onClick: () => {
					deleteModule(module.id);
				},
				children: /* @__PURE__ */ jsx("svg", {
					className: "size-6",
					viewBox: "0 0 24 24",
					fill: "currentcolor",
					children: /* @__PURE__ */ jsx("path", {
						fillRule: "evenodd",
						clipRule: "evenodd",
						d: "M16.9993 8.51506L15.4844 7L11.9994 10.4852L8.51497 7.00057L7 8.51562L10.4844 12.0003L7.00056 15.4843L8.51552 16.9994L11.9994 13.5153L15.4838 17L16.9988 15.4849L13.5144 12.0003L16.9993 8.51506Z"
					})
				})
			})]
		}), !!module && /* @__PURE__ */ jsx(Operations, {
			module,
			allOperations,
			shouldFocusNewOperation: module.id === lastCreatedModuleId,
			updateOperationName,
			deleteOperation,
			addOperationAndInitialSchema,
			updateOperationSchema,
			setOperationDescription,
			addOperationError,
			deleteOperationError,
			setOperationErrorName,
			toggleNoInputRequired
		})]
	});
}
//#endregion
//#region editors/document-model-editor/components/modules.tsx
function Modules({ modules, allOperations, addModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired }) {
	const [lastCreatedModuleId, setLastCreatedModuleId] = useState(null);
	const focusTrapRef = useRef(null);
	const onAddModule = useCallback(async (name) => {
		const moduleId = await addModule(name);
		if (moduleId) {
			setLastCreatedModuleId(moduleId);
			focusTrapRef.current?.focus();
		}
		return moduleId;
	}, [addModule, setLastCreatedModuleId]);
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col gap-2",
		children: [
			modules.map((module) => /* @__PURE__ */ jsx(Module, {
				module,
				modules,
				allOperations,
				lastCreatedModuleId,
				onAddModule,
				updateModuleName,
				deleteModule,
				updateOperationName,
				deleteOperation,
				addOperationAndInitialSchema,
				updateOperationSchema,
				setOperationDescription,
				addOperationError,
				deleteOperationError,
				setOperationErrorName,
				toggleNoInputRequired
			}, module.id)),
			/* @__PURE__ */ jsx(Module, {
				modules,
				allOperations,
				lastCreatedModuleId,
				onAddModule,
				updateModuleName,
				deleteModule,
				updateOperationName,
				deleteOperation,
				addOperationAndInitialSchema,
				updateOperationSchema,
				setOperationDescription,
				addOperationError,
				deleteOperationError,
				setOperationErrorName,
				toggleNoInputRequired
			}, "add-module"),
			/* @__PURE__ */ jsx("div", {
				ref: focusTrapRef,
				tabIndex: 0,
				className: "size-0 overflow-hidden",
				"aria-hidden": "true"
			})
		]
	});
}
//#endregion
//#region editors/document-model-editor/config.ts
const editorConfig = { isExternalControlsEnabled: false };
//#endregion
//#region editors/document-model-editor/hooks/useDocumentModelDocument.ts
function useSelectedDocumentModelDocument() {
	return useSelectedDocumentOfType("powerhouse/document-model");
}
//#endregion
//#region editors/document-model-editor/editor.tsx
const StateSchemas = lazy(() => import("./state-schemas-Dt2-S4R8.mjs"));
function Editor() {
	useSetPHDocumentEditorConfig(editorConfig);
	const toast = usePHToast();
	const [document, dispatch] = useSelectedDocumentModelDocument();
	const [scope, setScope] = useState("global");
	const documentNodeName = document.header.name;
	const { name: modelName, id: documentType, extension, description, author: { name: authorName, website: authorWebsite } } = document.state.global;
	const { state: { global: { schema: globalStateSchema, initialValue: globalStateInitialValue }, local: { schema: localStateSchema, initialValue: localStateInitialValue } }, modules } = document.state.global.specifications[0];
	const operations = modules.flatMap((module) => module.operations);
	const shouldSetInitialName = useRef(!modelName && !!documentNodeName && operations.length === 0);
	useEffect(() => {
		if (!shouldSetInitialName.current || !documentNodeName) return;
		const initialSchemaDoc = initializeModelSchema(documentNodeName);
		dispatch([setModelName({ name: documentNodeName }), setStateSchema({
			schema: initialSchemaDoc,
			scope: "global"
		})]);
		shouldSetInitialName.current = false;
	}, [documentNodeName, dispatch]);
	const operationSchemasSdl = operations.flatMap((operation) => operation.schema ?? []).join("\n");
	const handleSetModelId = (id) => {
		if (compareStringsWithoutWhitespace(id, documentType)) return;
		dispatch([setModelId({ id })]);
	};
	const handleSetModelDescription = (newDescription) => {
		if (compareStringsWithoutWhitespace(newDescription, description)) return;
		dispatch(setModelDescription({ description: newDescription }));
	};
	const handleSetModelExtension = (newExtension) => {
		if (compareStringsWithoutWhitespace(newExtension, extension)) return;
		dispatch(setModelExtension({ extension: newExtension }));
	};
	const handleSetModelName = (newName) => {
		if (compareStringsWithoutWhitespace(newName, modelName)) return;
		dispatch(setModelName({ name: newName }));
	};
	const handleSetAuthorName = (newAuthorName) => {
		if (compareStringsWithoutWhitespace(newAuthorName, authorName)) return;
		dispatch(setAuthorName({ authorName: newAuthorName }));
	};
	const handleSetAuthorWebsite = (newAuthorWebsite) => {
		if (compareStringsWithoutWhitespace(newAuthorWebsite, authorWebsite ?? "")) return;
		dispatch(setAuthorWebsite({ authorWebsite: newAuthorWebsite }));
	};
	const handleSetStateSchema = (newSchema, scope) => {
		if (compareStringsWithoutWhitespace(newSchema, scope === "global" ? globalStateSchema : localStateSchema)) return;
		dispatch(setStateSchema({
			schema: newSchema,
			scope
		}));
	};
	const handleSetInitialState = (newInitialValue, scope) => {
		if (compareStringsWithoutWhitespace(newInitialValue, scope === "global" ? globalStateInitialValue : localStateInitialValue)) return;
		dispatch(setInitialState({
			initialValue: newInitialValue,
			scope
		}));
	};
	const handleAddModule = (name) => {
		return new Promise((resolve) => {
			try {
				if (modules.some((module) => compareStringsWithoutWhitespace(module.name, name))) {
					resolve(void 0);
					return;
				}
				const id = generateId();
				dispatch(addModule({
					id,
					name
				}));
				resolve(id);
			} catch (error) {
				console.error("Failed to add module:", error);
				resolve(void 0);
			}
		});
	};
	const handleSetModuleName = (id, name) => {
		if (modules.some((module) => compareStringsWithoutWhitespace(module.name, name))) return;
		dispatch(setModuleName({
			id,
			name
		}));
	};
	const handleDeleteModule = (id) => {
		dispatch(deleteModule({ id }));
	};
	const handleAddOperation = (moduleId, name) => {
		return new Promise((resolve) => {
			const id = generateId();
			dispatch(addOperation({
				id,
				moduleId,
				name,
				scope
			}), (errors) => {
				if (errors.length > 0) {
					if (toast) toast(errors[0].message, { type: "connect-warning" });
					resolve(void 0);
				} else resolve(id);
			}, () => resolve(id));
		});
	};
	const handleSetOperationName = (id, name) => {
		dispatch(setOperationName({
			id,
			name
		}), (errors) => {
			if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
		});
	};
	const handleSetOperationSchema = (id, newSchema) => {
		const operation = operations.find((operation) => operation.id === id);
		if (operation?.schema && compareStringsWithoutWhitespace(newSchema, operation.schema)) return;
		dispatch(setOperationSchema({
			id,
			schema: newSchema
		}));
	};
	const handleToggleNoInputRequired = (id, noInputRequired) => {
		const operation = operations.find((op) => op.id === id);
		if (!operation?.name) return;
		if (noInputRequired) dispatch(setOperationSchema({
			id,
			schema: makeEmptyOperationSchema(operation.name)
		}));
		else dispatch(setOperationSchema({
			id,
			schema: makeOperationInitialDoc(operation.name)
		}));
	};
	const handleSetOperationDescription = (id, newDescription) => {
		if (compareStringsWithoutWhitespace(operations.find((operation) => operation.id === id)?.description ?? "", newDescription)) return;
		dispatch(setOperationDescription({
			id,
			description: newDescription
		}));
	};
	const handleDeleteOperation = (id) => {
		dispatch(deleteOperation({ id }));
	};
	const handleAddOperationError = (operationId, errorName) => {
		return new Promise((resolve) => {
			try {
				if ((operations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) {
					resolve(void 0);
					return;
				}
				const id = generateId();
				dispatch(addOperationError({
					id,
					operationId,
					errorName,
					errorCode: pascalCase(errorName)
				}));
				resolve(id);
			} catch (error) {
				console.error("Failed to add operation error:", error);
				resolve(void 0);
			}
		});
	};
	const handleDeleteOperationError = (id) => {
		dispatch(deleteOperationError({ id }));
	};
	const handleSetOperationErrorName = (operationId, errorId, errorName) => {
		if ((operations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) return;
		dispatch(setOperationErrorName({
			id: errorId,
			errorName
		}));
	};
	const addOperationAndInitialSchema = async (moduleId, name) => {
		try {
			const id = await handleAddOperation(moduleId, name);
			if (!id) return void 0;
			try {
				handleSetOperationSchema(id, makeOperationInitialDoc(name));
				return id;
			} catch (error) {
				console.error("Failed to update operation schema:", error);
				return;
			}
		} catch (error) {
			console.error("Failed to add operation and schema:", error);
			return;
		}
	};
	return /* @__PURE__ */ jsxs("main", {
		className: "min-h-dvh bg-gray-50 p-6 dark:bg-slate-800",
		children: [/* @__PURE__ */ jsx(DocumentToolbar, {}), /* @__PURE__ */ jsx(SchemaContextProvider, {
			globalStateSchemaSdl: globalStateSchema,
			localStateSchemaSdl: localStateSchema,
			operationSchemasSdl,
			children: /* @__PURE__ */ jsxs("div", {
				className: "mx-auto max-w-6xl px-4 pt-8",
				children: [
					/* @__PURE__ */ jsx(ModelMetadata, {
						name: modelName,
						documentType,
						extension,
						description,
						authorName,
						authorWebsite: authorWebsite ?? "",
						globalStateSchema,
						localStateSchema,
						setModelId: handleSetModelId,
						setModelDescription: handleSetModelDescription,
						setModelExtension: handleSetModelExtension,
						setModelName: handleSetModelName,
						setAuthorName: handleSetAuthorName,
						setAuthorWebsite: handleSetAuthorWebsite,
						setStateSchema: handleSetStateSchema
					}),
					/* @__PURE__ */ jsx(Divider, {}),
					/* @__PURE__ */ jsxs("div", { children: [
						/* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(StateSchemas, {
							modelName,
							globalStateSchema,
							globalStateInitialValue,
							localStateSchema,
							localStateInitialValue,
							setStateSchema: handleSetStateSchema,
							setInitialState: handleSetInitialState,
							currentScope: scope,
							onScopeChange: setScope
						}) }),
						/* @__PURE__ */ jsx(Divider, {}),
						/* @__PURE__ */ jsxs("h3", {
							className: "mb-6 text-lg text-gray-900 capitalize dark:text-slate-100",
							children: [scope, " Operations"]
						}),
						/* @__PURE__ */ jsx(Modules, {
							modules: modules.map((module) => ({
								...module,
								operations: module.operations.filter((op) => op.scope === scope)
							})),
							allOperations: operations,
							addModule: handleAddModule,
							updateModuleName: handleSetModuleName,
							deleteModule: handleDeleteModule,
							updateOperationName: handleSetOperationName,
							updateOperationSchema: handleSetOperationSchema,
							setOperationDescription: handleSetOperationDescription,
							deleteOperation: handleDeleteOperation,
							addOperationError: handleAddOperationError,
							deleteOperationError: handleDeleteOperationError,
							setOperationErrorName: handleSetOperationErrorName,
							addOperationAndInitialSchema,
							toggleNoInputRequired: handleToggleNoInputRequired
						})
					] })
				]
			})
		})]
	});
}
//#endregion
export { Editor as default };

//# sourceMappingURL=editor-kdobbTut.mjs.map