import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
import { n as cachedQuery, t as CacheNamespace } from "./object-cache-Bok5j2ae.mjs";
import { t as CommentRepository } from "./comment-CzeatwBV.mjs";
import { t as OptionsRepository } from "./options-DTTML-Tx.mjs";
import { t as PluginContextFactory } from "./context-CUsR9dXL.mjs";
import { r as requestCached } from "./request-cache-KCNHp_RJ.mjs";
import { a as getDb } from "./loader-CB6YHeul.mjs";
import { i as resolveLocaleChain, r as resolveLocale } from "./resolve-DR3wqMTy.mjs";
import { a as normalizeCapabilities } from "./types-DROWRxYV.mjs";
import { dt as sanitizeHref } from "./redirects-DXEXBAII.mjs";
import { t as extractRequestMeta } from "./request-meta-DbvXaAvU.mjs";
import { r as setCronTasksEnabled } from "./cron-v4FTEFR_.mjs";
import { t as CommentReactionRepository } from "./comment-reaction-Cj9QJY7I.mjs";
import { sql } from "kysely";
import { ulid } from "ulidx";
import { AsyncLocalStorage } from "node:async_hooks";
import { z } from "astro/zod";

//#region src/fields/image.ts
const imageSchema = z.object({
	id: z.string(),
	src: z.string(),
	alt: z.string().optional(),
	width: z.number().optional(),
	height: z.number().optional()
});
function image(options = {}) {
	const validation = options.allowedTypes && options.allowedTypes.length > 0 ? { allowedMimeTypes: [...options.allowedTypes] } : void 0;
	return {
		type: "image",
		columnType: "TEXT",
		schema: options.required === false ? imageSchema.optional() : imageSchema,
		options,
		ui: { widget: "image" },
		validation
	};
}

//#endregion
//#region src/fields/file.ts
function file(options = {}) {
	const fileObjSchema = z.object({
		id: z.string(),
		url: z.string(),
		filename: z.string(),
		mimeType: z.string(),
		size: z.number()
	});
	return {
		type: "file",
		columnType: "TEXT",
		schema: options.required ? fileObjSchema : fileObjSchema.optional(),
		options,
		ui: {
			widget: "file",
			helpText: options.helpText,
			maxSize: options.maxSize
		},
		validation: options.allowedTypes && options.allowedTypes.length > 0 ? { allowedMimeTypes: [...options.allowedTypes] } : void 0
	};
}

//#endregion
//#region src/fields/reference.ts
/**
* Reference field
* References another content item by ID
*/
function reference(collection, options) {
	const schema = z.string();
	return {
		type: "reference",
		columnType: "TEXT",
		schema: options?.required === false ? schema.optional() : schema,
		options: {
			...options,
			collection
		},
		ui: { widget: "reference" }
	};
}

//#endregion
//#region src/fields/portable-text.ts
/**
* Portable Text block schema
*/
const portableTextBlockSchema = z.object({
	_type: z.string(),
	_key: z.string()
}).passthrough();
/**
* Portable Text field
* Stores structured content in Portable Text format
*/
function portableText(options) {
	const schema = z.array(portableTextBlockSchema);
	return {
		type: "portableText",
		columnType: "JSON",
		schema: options?.required === false ? schema.optional() : schema,
		options,
		ui: { widget: "portableText" }
	};
}

//#endregion
//#region src/content/converters/prosemirror-to-portable-text.ts
/**
* Generate a unique key for Portable Text blocks
*/
function generateKey() {
	return Math.random().toString(36).substring(2, 11);
}
/**
* Convert ProseMirror document to Portable Text
*/
function prosemirrorToPortableText(doc) {
	if (!doc || doc.type !== "doc" || !doc.content) return [];
	const blocks = [];
	for (const node of doc.content) {
		const converted = convertNode(node);
		if (converted) if (Array.isArray(converted)) blocks.push(...converted);
		else blocks.push(converted);
	}
	return blocks;
}
/**
* Convert a single ProseMirror node to Portable Text block(s)
*/
function convertNode(node) {
	switch (node.type) {
		case "paragraph": return convertParagraph(node);
		case "heading": return convertHeading(node);
		case "bulletList": return convertList$1(node, "bullet");
		case "orderedList": return convertList$1(node, "number");
		case "blockquote": return convertBlockquote(node);
		case "codeBlock": return convertCodeBlock$1(node);
		case "htmlBlock": return convertHtmlBlock(node);
		case "image": return convertImage$1(node);
		case "horizontalRule": return {
			_type: "break",
			_key: generateKey(),
			style: "lineBreak"
		};
		default: return {
			_type: node.type,
			_key: generateKey(),
			...node.attrs,
			_pmContent: node.content
		};
	}
}
/**
* Convert paragraph to Portable Text block
*/
function convertParagraph(node) {
	const { children, markDefs } = convertInlineContent(node.content || []);
	if (children.length === 0) return null;
	const ta = node.attrs?.textAlign;
	const textAlign = ta === "center" || ta === "right" || ta === "justify" ? ta : void 0;
	return {
		_type: "block",
		_key: generateKey(),
		style: "normal",
		children,
		markDefs: markDefs.length > 0 ? markDefs : void 0,
		...textAlign ? { textAlign } : {}
	};
}
/** Map heading level number to Portable Text style */
function headingLevelToStyle(level) {
	switch (level) {
		case 1: return "h1";
		case 2: return "h2";
		case 3: return "h3";
		case 4: return "h4";
		case 5: return "h5";
		case 6: return "h6";
		default: return "h1";
	}
}
/**
* Convert heading to Portable Text block
*/
function convertHeading(node) {
	const { children, markDefs } = convertInlineContent(node.content || []);
	const style = headingLevelToStyle(typeof node.attrs?.level === "number" ? node.attrs.level : 1);
	if (children.length === 0) return null;
	const ta = node.attrs?.textAlign;
	const textAlign = ta === "center" || ta === "right" || ta === "justify" ? ta : void 0;
	return {
		_type: "block",
		_key: generateKey(),
		style,
		children,
		markDefs: markDefs.length > 0 ? markDefs : void 0,
		...textAlign ? { textAlign } : {}
	};
}
/**
* Convert list to Portable Text blocks
*/
function convertList$1(node, listItem) {
	const blocks = [];
	for (const item of node.content || []) if (item.type === "listItem") {
		const itemBlocks = convertListItem$1(item, listItem, 1);
		blocks.push(...itemBlocks);
	}
	return blocks;
}
/**
* Convert list item to Portable Text blocks
*/
function convertListItem$1(item, listItem, level) {
	const blocks = [];
	for (const child of item.content || []) if (child.type === "paragraph") {
		const { children, markDefs } = convertInlineContent(child.content || []);
		if (children.length > 0) blocks.push({
			_type: "block",
			_key: generateKey(),
			style: "normal",
			listItem,
			level,
			children,
			markDefs: markDefs.length > 0 ? markDefs : void 0
		});
	} else if (child.type === "bulletList") blocks.push(...convertListItemNested(child, "bullet", level + 1));
	else if (child.type === "orderedList") blocks.push(...convertListItemNested(child, "number", level + 1));
	return blocks;
}
/**
* Convert nested list
*/
function convertListItemNested(node, listItem, level) {
	const blocks = [];
	for (const item of node.content || []) if (item.type === "listItem") blocks.push(...convertListItem$1(item, listItem, level));
	return blocks;
}
/**
* Convert blockquote to Portable Text blocks
*/
function convertBlockquote(node) {
	const blocks = [];
	for (const child of node.content || []) if (child.type === "paragraph") {
		const { children, markDefs } = convertInlineContent(child.content || []);
		if (children.length > 0) blocks.push({
			_type: "block",
			_key: generateKey(),
			style: "blockquote",
			children,
			markDefs: markDefs.length > 0 ? markDefs : void 0
		});
	}
	return blocks.length === 1 ? blocks[0] : blocks.length > 0 ? blocks : null;
}
/**
* Convert code block to Portable Text
*/
function convertCodeBlock$1(node) {
	const code = node.content?.map((n) => n.text || "").join("") || "";
	const language = typeof node.attrs?.language === "string" ? node.attrs.language : void 0;
	return {
		_type: "code",
		_key: generateKey(),
		code,
		language: language || void 0
	};
}
/**
* Convert HTML block to Portable Text
*/
function convertHtmlBlock(node) {
	const rawHtml = node.attrs?.html;
	return {
		_type: "htmlBlock",
		_key: generateKey(),
		html: typeof rawHtml === "string" ? rawHtml : ""
	};
}
/**
* Convert image to Portable Text
*/
function convertImage$1(node) {
	const attrs = node.attrs;
	const provider = typeof attrs?.provider === "string" ? attrs.provider : void 0;
	const mediaId = typeof attrs?.mediaId === "string" ? attrs.mediaId : void 0;
	const src = typeof attrs?.src === "string" ? attrs.src : "";
	const alt = typeof attrs?.alt === "string" ? attrs.alt : void 0;
	const title = typeof attrs?.title === "string" ? attrs.title : void 0;
	const width = typeof attrs?.width === "number" ? attrs.width : void 0;
	const height = typeof attrs?.height === "number" ? attrs.height : void 0;
	const displayWidth = typeof attrs?.displayWidth === "number" ? attrs.displayWidth : void 0;
	const displayHeight = typeof attrs?.displayHeight === "number" ? attrs.displayHeight : void 0;
	return {
		_type: "image",
		_key: generateKey(),
		asset: {
			_ref: mediaId || src || "",
			url: src || "",
			provider: provider && provider !== "local" ? provider : void 0
		},
		alt: alt || void 0,
		caption: title || void 0,
		width: width || void 0,
		height: height || void 0,
		displayWidth: displayWidth || void 0,
		displayHeight: displayHeight || void 0
	};
}
/**
* Convert inline content (text nodes with marks) to Portable Text spans
*/
function convertInlineContent(nodes) {
	const children = [];
	const markDefs = [];
	const markDefMap = /* @__PURE__ */ new Map();
	for (const node of nodes) if (node.type === "text" && node.text) {
		const marks = [];
		for (const mark of node.marks || []) {
			const markType = convertMark(mark, markDefs, markDefMap);
			if (markType) marks.push(markType);
		}
		children.push({
			_type: "span",
			_key: generateKey(),
			text: node.text,
			marks: marks.length > 0 ? marks : void 0
		});
	} else if (node.type === "hardBreak") if (children.length > 0) {
		const lastChild = children.at(-1);
		lastChild.text += "\n";
	} else children.push({
		_type: "span",
		_key: generateKey(),
		text: "\n"
	});
	if (children.length === 0) children.push({
		_type: "span",
		_key: generateKey(),
		text: ""
	});
	return {
		children,
		markDefs
	};
}
/**
* Convert a ProseMirror mark to Portable Text mark
*/
function convertMark(mark, markDefs, markDefMap) {
	switch (mark.type) {
		case "bold":
		case "strong": return "strong";
		case "italic":
		case "em": return "em";
		case "underline": return "underline";
		case "strike":
		case "strikethrough": return "strike-through";
		case "code": return "code";
		case "link": {
			const href = (typeof mark.attrs?.href === "string" ? mark.attrs.href : "") || "";
			if (markDefMap.has(href)) return markDefMap.get(href);
			const key = generateKey();
			markDefs.push({
				_type: "link",
				_key: key,
				href,
				blank: mark.attrs?.target === "_blank"
			});
			markDefMap.set(href, key);
			return key;
		}
		default: return mark.type;
	}
}

//#endregion
//#region src/content/converters/portable-text-to-prosemirror.ts
/**
* Convert Portable Text to ProseMirror document
*/
function portableTextToProsemirror(blocks) {
	if (!blocks || blocks.length === 0) return {
		type: "doc",
		content: [{ type: "paragraph" }]
	};
	const content = [];
	let i = 0;
	while (i < blocks.length) {
		const block = blocks[i];
		if (isTextBlock(block) && block.listItem) {
			const listBlocks = [];
			const listType = block.listItem;
			while (i < blocks.length) {
				const current = blocks[i];
				if (!isTextBlock(current) || !current.listItem) break;
				if ((current.level || 1) > 1 || current.listItem === listType) {
					listBlocks.push(current);
					i++;
				} else break;
			}
			content.push(convertList(listBlocks, listType));
		} else {
			const converted = convertBlock(block);
			if (converted) content.push(converted);
			i++;
		}
	}
	return {
		type: "doc",
		content: content.length > 0 ? content : [{ type: "paragraph" }]
	};
}
/**
* Type guard for text blocks
*/
function isTextBlock(block) {
	return block._type === "block";
}
/**
* Type guard for image blocks.
* Checks both `_type` and that `asset` is a valid object — image blocks
* without an `asset` wrapper (e.g. `{ _type: "image", url: "..." }`) are
* malformed and should not be cast to `PortableTextImageBlock`.
*/
function isImageBlock(block) {
	return block._type === "image" && "asset" in block && typeof block.asset === "object" && block.asset !== null;
}
/**
* Type guard for code blocks
*/
function isCodeBlock(block) {
	return block._type === "code";
}
/**
* Convert a single Portable Text block to ProseMirror node
*/
function convertBlock(block) {
	if (isTextBlock(block)) return convertTextBlock(block);
	if (isImageBlock(block)) return convertImage(block);
	if (block._type === "image") return convertMalformedImage(block);
	if (isCodeBlock(block)) return convertCodeBlock(block);
	if (block._type === "htmlBlock") return {
		type: "htmlBlock",
		attrs: { html: block.html || "" }
	};
	if (block._type === "break") return { type: "horizontalRule" };
	return {
		type: "paragraph",
		content: [{
			type: "text",
			text: `[Unknown block type: ${block._type}]`,
			marks: [{ type: "code" }]
		}]
	};
}
/**
* Convert text block to ProseMirror paragraph or heading
*/
function convertTextBlock(block) {
	const { style = "normal", children, markDefs = [] } = block;
	const content = convertSpans(children, markDefs);
	switch (style) {
		case "h1":
		case "h2":
		case "h3":
		case "h4":
		case "h5":
		case "h6": return {
			type: "heading",
			attrs: {
				level: parseInt(style.substring(1), 10),
				...block.textAlign ? { textAlign: block.textAlign } : {}
			},
			content: content.length > 0 ? content : void 0
		};
		case "blockquote": return {
			type: "blockquote",
			content: [{
				type: "paragraph",
				content: content.length > 0 ? content : void 0
			}]
		};
		default: return {
			type: "paragraph",
			attrs: block.textAlign ? { textAlign: block.textAlign } : void 0,
			content: content.length > 0 ? content : void 0
		};
	}
}
/**
* Convert list items to ProseMirror list
*/
function convertList(items, listType) {
	const rootItems = [];
	let i = 0;
	while (i < items.length) {
		const item = items[i];
		if ((item.level || 1) === 1) {
			const nestedItems = [];
			i++;
			while (i < items.length && (items[i].level || 1) > 1) {
				nestedItems.push(items[i]);
				i++;
			}
			rootItems.push(convertListItem(item, nestedItems, listType));
		} else {
			rootItems.push(convertListItem(item, [], listType));
			i++;
		}
	}
	return {
		type: listType === "bullet" ? "bulletList" : "orderedList",
		content: rootItems
	};
}
/**
* Convert a single list item to ProseMirror
*/
function convertListItem(item, nestedItems, parentListType) {
	const content = [];
	const spans = convertSpans(item.children, item.markDefs || []);
	content.push({
		type: "paragraph",
		content: spans.length > 0 ? spans : void 0
	});
	if (nestedItems.length > 0) {
		let minLevel = Infinity;
		for (const ni of nestedItems) {
			const level = ni.level || 2;
			if (level < minLevel) minLevel = level;
		}
		let j = 0;
		while (j < nestedItems.length) {
			const anchorType = nestedItems[j].listItem || parentListType;
			const nestedGroup = [];
			do {
				nestedGroup.push(nestedItems[j]);
				j++;
			} while (j < nestedItems.length && ((nestedItems[j].level || 2) > minLevel || (nestedItems[j].listItem || parentListType) === anchorType));
			if (nestedGroup.length > 0) {
				const adjustedGroup = nestedGroup.map((ni) => ({
					...ni,
					level: (ni.level || 2) - 1
				}));
				content.push(convertList(adjustedGroup, anchorType));
			}
		}
	}
	return {
		type: "listItem",
		content
	};
}
/**
* Convert Portable Text spans to ProseMirror text nodes
*/
function convertSpans(spans, markDefs) {
	const nodes = [];
	const markDefsMap = new Map(markDefs.map((md) => [md._key, md]));
	for (const span of spans) {
		if (span._type !== "span") continue;
		const parts = span.text.split("\n");
		for (let i = 0; i < parts.length; i++) {
			const text = parts[i];
			if (text.length > 0) {
				const marks = convertMarks(span.marks || [], markDefsMap);
				const node = {
					type: "text",
					text
				};
				if (marks.length > 0) node.marks = marks;
				nodes.push(node);
			}
			if (i < parts.length - 1) nodes.push({ type: "hardBreak" });
		}
	}
	return nodes;
}
/**
* Convert Portable Text marks to ProseMirror marks
*/
function convertMarks(marks, markDefs) {
	const pmMarks = [];
	for (const mark of marks) switch (mark) {
		case "strong":
			pmMarks.push({ type: "bold" });
			break;
		case "em":
			pmMarks.push({ type: "italic" });
			break;
		case "underline":
			pmMarks.push({ type: "underline" });
			break;
		case "strike-through":
			pmMarks.push({ type: "strike" });
			break;
		case "code":
			pmMarks.push({ type: "code" });
			break;
		default: {
			const markDef = markDefs.get(mark);
			if (markDef) if (markDef._type === "link") pmMarks.push({
				type: "link",
				attrs: {
					href: markDef.href,
					target: markDef.blank ? "_blank" : null
				}
			});
			else pmMarks.push({
				type: markDef._type,
				attrs: markDef
			});
			break;
		}
	}
	return pmMarks;
}
/**
* Convert image block to ProseMirror
*/
function convertImage(block) {
	return {
		type: "image",
		attrs: {
			src: block.asset.url || block.asset._ref,
			alt: block.alt || "",
			title: block.caption || "",
			mediaId: block.asset._ref,
			provider: block.asset.provider,
			width: block.width,
			height: block.height,
			displayWidth: block.displayWidth,
			displayHeight: block.displayHeight
		}
	};
}
/**
* Convert a malformed image block (missing `asset` wrapper) to ProseMirror.
* Handles blocks like `{ _type: "image", url: "...", alt: "..." }` that may
* originate from migrations or third-party imports.
*/
function convertMalformedImage(block) {
	return {
		type: "image",
		attrs: {
			src: "url" in block && typeof block.url === "string" ? block.url : "",
			alt: "alt" in block && typeof block.alt === "string" ? block.alt : "",
			title: "caption" in block && typeof block.caption === "string" ? block.caption : "",
			mediaId: void 0,
			provider: void 0,
			width: "width" in block && typeof block.width === "number" ? block.width : void 0,
			height: "height" in block && typeof block.height === "number" ? block.height : void 0,
			displayWidth: "displayWidth" in block && typeof block.displayWidth === "number" ? block.displayWidth : void 0,
			displayHeight: "displayHeight" in block && typeof block.displayHeight === "number" ? block.displayHeight : void 0
		}
	};
}
/**
* Convert code block to ProseMirror
*/
function convertCodeBlock(block) {
	return {
		type: "codeBlock",
		attrs: { language: block.language || null },
		content: block.code ? [{
			type: "text",
			text: block.code
		}] : void 0
	};
}

//#endregion
//#region src/plugins/define-plugin.ts
/**
* definePlugin() Helper
*
* Native plugin authoring entry. Returns a fully-resolved
* `ResolvedPlugin` ready for the host integration to mount.
*
* Sandboxed plugins do NOT use this function. They default-export
* a bare `{ hooks?, routes? }` object with a `satisfies SandboxedPlugin`
* annotation from `emdash/plugin`. See the `emdash` changeset for the
* authoring shape.
*/
/**
* Define a native EmDash plugin.
*
* Native plugins ship as regular npm modules, get installed via
* `pnpm add` + an `astro.config.mjs` edit, and run in the host
* process. They have full access to the runtime — capabilities are
* still enforced by `PluginContextFactory`, but there is no isolation
* boundary.
*
* @example
* ```typescript
* import { definePlugin } from "emdash";
*
* export default definePlugin({
*   id: "my-plugin",
*   version: "1.0.0",
*   capabilities: ["content:read"],
*   hooks: {
*     "content:beforeSave": async (event, ctx) => {
*       ctx.log.info("Saving content", { collection: event.collection });
*       return event.content;
*     }
*   },
*   routes: {
*     "sync": {
*       handler: async (ctx) => {
*         return { status: "ok" };
*       }
*     }
*   }
* });
* ```
*
* Sandboxed-format plugins do not use `definePlugin`. They
* default-export a bare `{ hooks?, routes? }` object with a
* `satisfies SandboxedPlugin` annotation from `emdash/plugin`. Calling
* `definePlugin` with an object that has no `id` throws at runtime
* (the type system already rejects it at compile time — this check is
* for callers that bypass typechecking).
*/
function definePlugin(definition) {
	if (typeof definition.id !== "string" || definition.id.length === 0) throw new Error(`definePlugin() requires \`id\` (got ${typeof definition.id}). For native plugins, make sure your definition has both \`id\` and \`version\`. For sandboxed plugins, drop \`definePlugin()\` entirely and \`export default { hooks, routes } satisfies SandboxedPlugin\` from "emdash/plugin" — identity comes from \`emdash-plugin.jsonc\`.`);
	return defineNativePlugin(definition);
}
/**
* Internal: define a native-format plugin with full validation and normalization.
*/
function defineNativePlugin(definition) {
	const SIMPLE_ID = /^[a-z0-9-]+$/;
	const SCOPED_ID = /^@[a-z0-9-]+\/[a-z0-9-]+$/;
	const SEMVER_PATTERN = /^\d+\.\d+\.\d+/;
	const { id, version, capabilities = [], allowedHosts = [], hooks = {}, routes = {}, admin = {} } = definition;
	const storage = definition.storage ?? {};
	if (!SIMPLE_ID.test(id) && !SCOPED_ID.test(id)) throw new Error(`Invalid plugin id "${id}". Must be lowercase alphanumeric with dashes (e.g., "my-plugin" or "@scope/my-plugin").`);
	if (!SEMVER_PATTERN.test(version)) throw new Error(`Invalid plugin version "${version}". Must be semver format (e.g., "1.0.0").`);
	const validCapabilities = new Set([
		"network:request",
		"network:request:unrestricted",
		"content:read",
		"content:write",
		"media:read",
		"media:write",
		"users:read",
		"email:send",
		"hooks.email-transport:register",
		"hooks.email-events:register",
		"hooks.page-fragments:register",
		"network:fetch",
		"network:fetch:any",
		"read:content",
		"write:content",
		"read:media",
		"write:media",
		"read:users",
		"email:provide",
		"email:intercept",
		"page:inject"
	]);
	for (const cap of capabilities) if (!validCapabilities.has(cap)) throw new Error(`Invalid capability "${cap}" in plugin "${id}".`);
	const canonical = normalizeCapabilities(capabilities);
	const normalizedCapabilities = [...canonical];
	if (canonical.includes("content:write") && !canonical.includes("content:read")) normalizedCapabilities.push("content:read");
	if (canonical.includes("media:write") && !canonical.includes("media:read")) normalizedCapabilities.push("media:read");
	if (canonical.includes("network:request:unrestricted") && !canonical.includes("network:request")) normalizedCapabilities.push("network:request");
	return {
		id,
		version,
		capabilities: normalizedCapabilities,
		allowedHosts,
		storage,
		hooks: resolveHooks(hooks, id),
		routes,
		admin
	};
}
/**
* Resolve hooks to normalized format with defaults.
*
* PluginHooks and ResolvedPluginHooks share the same keys — each input value is
* `HookConfig<H> | H` and the output is `ResolvedHook<H>`.  TS can't narrow
* the handler type through a dynamic key, so we assert at the loop boundary.
*/
function resolveHooks(hooks, pluginId) {
	const resolved = {};
	for (const key of Object.keys(hooks)) {
		const hook = hooks[key];
		if (hook) resolved[key] = resolveHook(hook, pluginId);
	}
	return resolved;
}
/**
* Check if a hook value is a config object (has a `handler` property)
*/
function isHookConfig(hook) {
	return typeof hook === "object" && hook !== null && "handler" in hook;
}
/**
* Resolve a single hook to normalized format
*/
function resolveHook(hook, pluginId) {
	if (isHookConfig(hook)) {
		if (hook.exclusive !== void 0 && typeof hook.exclusive !== "boolean") throw new Error(`Invalid "exclusive" value in hook config for plugin "${pluginId}". Must be boolean.`);
		return {
			priority: hook.priority ?? 100,
			timeout: hook.timeout ?? 5e3,
			dependencies: hook.dependencies ?? [],
			errorPolicy: hook.errorPolicy ?? "abort",
			exclusive: hook.exclusive ?? false,
			handler: hook.handler,
			pluginId
		};
	}
	return {
		priority: 100,
		timeout: 5e3,
		dependencies: [],
		errorPolicy: "abort",
		exclusive: false,
		handler: hook,
		pluginId
	};
}

//#endregion
//#region src/plugins/hooks.ts
/**
* Plugin Hooks System v2
*
* Uses the unified PluginContext for all hooks.
* Manages lifecycle hooks with:
* - Deterministic ordering via priority + dependencies
* - Timeout enforcement
* - Error isolation
* - Observability
*
*/
/**
* Hook pipeline for executing hooks in order
*/
var HookPipeline = class HookPipeline {
	hooks = /* @__PURE__ */ new Map();
	pluginMap = /* @__PURE__ */ new Map();
	contextFactory = null;
	/** Stored so setContextFactory can merge incrementally. */
	contextFactoryOptions = {};
	/** Hook names where at least one handler declared exclusive: true */
	exclusiveHookNames = /* @__PURE__ */ new Set();
	/**
	* Selected provider plugin ID for each exclusive hook.
	* Set by the PluginManager after resolution.
	*/
	exclusiveSelections = /* @__PURE__ */ new Map();
	constructor(plugins, factoryOptions) {
		if (factoryOptions) {
			this.contextFactory = new PluginContextFactory(factoryOptions);
			this.contextFactoryOptions = { ...factoryOptions };
		}
		for (const plugin of plugins) this.pluginMap.set(plugin.id, plugin);
		this.registerPlugins(plugins);
	}
	/**
	* Set or update the context factory options.
	*
	* When called on a pipeline that already has a factory, the new options
	* are merged on top of the existing ones so that callers don't need to
	* repeat every field (e.g. adding `cronReschedule` without losing
	* `storage` / `getUploadUrl`).
	*/
	setContextFactory(options) {
		const merged = {
			...this.contextFactoryOptions,
			...options
		};
		this.contextFactory = new PluginContextFactory(merged);
		this.contextFactoryOptions = merged;
	}
	/**
	* Get context for a plugin
	*/
	getContext(pluginId) {
		const plugin = this.pluginMap.get(pluginId);
		if (!plugin) throw new Error(`Plugin "${pluginId}" not found`);
		if (!this.contextFactory) throw new Error("Context factory not initialized - call setContextFactory first");
		return this.contextFactory.createContext(plugin);
	}
	/**
	* Get typed hooks for a specific hook name.
	* The internal map stores ResolvedHook<unknown>, but we know each name
	* maps to a specific handler type via HookHandlerMap.
	*
	* Exclusive hooks that have a selected provider are filtered out — they
	* should only run via invokeExclusiveHook(), not in the regular pipeline.
	*/
	getTypedHooks(name) {
		const all = this.hooks.get(name) ?? [];
		if (this.exclusiveSelections.has(name)) return all.filter((h) => !h.exclusive);
		return all;
	}
	/**
	* Register all hooks from plugins.
	*
	* Registers each hook name individually to preserve type safety. The
	* internal map stores ResolvedHook<unknown> since it's keyed by string,
	* but getTypedHooks() restores the correct handler type on retrieval.
	*/
	registerPlugins(plugins) {
		for (const plugin of plugins) {
			this.registerPluginHook(plugin, "plugin:install");
			this.registerPluginHook(plugin, "plugin:activate");
			this.registerPluginHook(plugin, "plugin:deactivate");
			this.registerPluginHook(plugin, "plugin:uninstall");
			this.registerPluginHook(plugin, "content:beforeSave");
			this.registerPluginHook(plugin, "content:afterSave");
			this.registerPluginHook(plugin, "content:beforeDelete");
			this.registerPluginHook(plugin, "content:afterDelete");
			this.registerPluginHook(plugin, "content:afterPublish");
			this.registerPluginHook(plugin, "content:afterUnpublish");
			this.registerPluginHook(plugin, "content:afterRestore");
			this.registerPluginHook(plugin, "content:afterSchedule");
			this.registerPluginHook(plugin, "content:afterUnschedule");
			this.registerPluginHook(plugin, "media:beforeUpload");
			this.registerPluginHook(plugin, "media:afterUpload");
			this.registerPluginHook(plugin, "cron");
			this.registerPluginHook(plugin, "email:beforeSend");
			this.registerPluginHook(plugin, "email:deliver");
			this.registerPluginHook(plugin, "email:afterSend");
			this.registerPluginHook(plugin, "comment:beforeCreate");
			this.registerPluginHook(plugin, "comment:moderate");
			this.registerPluginHook(plugin, "comment:afterCreate");
			this.registerPluginHook(plugin, "comment:afterModerate");
			this.registerPluginHook(plugin, "page:metadata");
			this.registerPluginHook(plugin, "page:fragments");
		}
		for (const [hookName, hooks] of this.hooks) this.hooks.set(hookName, this.sortHooks(hooks));
	}
	/**
	* Maps hook names to the capability required to register them.
	*
	* Hooks not listed here have no capability requirement (e.g. lifecycle
	* hooks, cron). Any plugin declaring a listed hook without the required
	* capability will have that hook silently skipped at registration time.
	*/
	static HOOK_REQUIRED_CAPABILITY = new Map([
		["email:beforeSend", "hooks.email-events:register"],
		["email:afterSend", "hooks.email-events:register"],
		["email:deliver", "hooks.email-transport:register"],
		["content:beforeSave", "content:write"],
		["content:afterSave", "content:read"],
		["content:beforeDelete", "content:read"],
		["content:afterDelete", "content:read"],
		["content:afterPublish", "content:read"],
		["content:afterUnpublish", "content:read"],
		["content:afterRestore", "content:read"],
		["content:afterSchedule", "content:read"],
		["content:afterUnschedule", "content:read"],
		["media:beforeUpload", "media:write"],
		["media:afterUpload", "media:read"],
		["comment:beforeCreate", "users:read"],
		["comment:moderate", "users:read"],
		["comment:afterCreate", "users:read"],
		["comment:afterModerate", "users:read"],
		["page:fragments", "hooks.page-fragments:register"]
	]);
	/**
	* Register a single plugin's hook by name
	*/
	registerPluginHook(plugin, name) {
		const hook = plugin.hooks[name];
		if (!hook) return;
		const requiredCapability = HookPipeline.HOOK_REQUIRED_CAPABILITY.get(name);
		if (requiredCapability && !plugin.capabilities.includes(requiredCapability)) {
			console.warn(`[hooks] Plugin "${plugin.id}" declares ${name} hook without ${requiredCapability} capability — skipping`);
			return;
		}
		if (hook.exclusive) this.exclusiveHookNames.add(name);
		this.registerHook(name, hook);
	}
	/**
	* Register a single hook
	*/
	registerHook(name, hook) {
		const existing = this.hooks.get(name) || [];
		existing.push(hook);
		this.hooks.set(name, existing);
	}
	/**
	* Sort hooks by priority and dependencies
	*/
	sortHooks(hooks) {
		const sorted = [];
		const remaining = [...hooks];
		while (remaining.length > 0) {
			const ready = remaining.filter((hook) => hook.dependencies.every((dep) => sorted.some((s) => s.pluginId === dep)));
			if (ready.length === 0) {
				const pluginIds = remaining.map((h) => h.pluginId).join(", ");
				console.warn(`[hooks] Hook dependency cycle or missing dependency detected among plugins: ${pluginIds}. Falling back to priority order.`);
				remaining.sort((a, b) => a.priority - b.priority);
				sorted.push(...remaining);
				break;
			}
			ready.sort((a, b) => a.priority - b.priority);
			const next = ready[0];
			sorted.push(next);
			remaining.splice(remaining.indexOf(next), 1);
		}
		return sorted;
	}
	/**
	* Execute a hook with timeout
	*/
	async executeWithTimeout(fn, timeout) {
		let timer;
		const timeoutPromise = new Promise((_, reject) => timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Hook timeout after ${timeout}ms`)), timeout));
		try {
			return await Promise.race([fn(), timeoutPromise]);
		} finally {
			clearTimeout(timer);
		}
	}
	/**
	* Run plugin:install hooks
	*/
	async runPluginInstall(pluginId) {
		return this.runLifecycleHook("plugin:install", pluginId);
	}
	/**
	* Run plugin:activate hooks
	*/
	async runPluginActivate(pluginId) {
		return this.runLifecycleHook("plugin:activate", pluginId);
	}
	/**
	* Run plugin:deactivate hooks
	*/
	async runPluginDeactivate(pluginId) {
		return this.runLifecycleHook("plugin:deactivate", pluginId);
	}
	/**
	* Run plugin:uninstall hooks
	*/
	async runPluginUninstall(pluginId, deleteData) {
		const hooks = this.getTypedHooks("plugin:uninstall");
		const results = [];
		const hook = hooks.find((h) => h.pluginId === pluginId);
		if (!hook) return results;
		const { handler } = hook;
		const event = { deleteData };
		const ctx = this.getContext(pluginId);
		const start = Date.now();
		try {
			await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
			results.push({
				success: true,
				pluginId: hook.pluginId,
				duration: Date.now() - start
			});
		} catch (error) {
			results.push({
				success: false,
				error: error instanceof Error ? error : new Error(String(error)),
				pluginId: hook.pluginId,
				duration: Date.now() - start
			});
		}
		return results;
	}
	async runLifecycleHook(hookName, pluginId) {
		const hooks = this.getTypedHooks(hookName);
		const results = [];
		const hook = hooks.find((h) => h.pluginId === pluginId);
		if (!hook) return results;
		const { handler } = hook;
		const event = {};
		const ctx = this.getContext(pluginId);
		const start = Date.now();
		try {
			await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
			results.push({
				success: true,
				pluginId: hook.pluginId,
				duration: Date.now() - start
			});
		} catch (error) {
			results.push({
				success: false,
				error: error instanceof Error ? error : new Error(String(error)),
				pluginId: hook.pluginId,
				duration: Date.now() - start
			});
		}
		return results;
	}
	/**
	* Run content:beforeSave hooks
	* Returns modified content from the pipeline
	*/
	async runContentBeforeSave(content, collection, isNew) {
		const hooks = this.getTypedHooks("content:beforeSave");
		const results = [];
		let currentContent = content;
		for (const hook of hooks) {
			const { handler } = hook;
			const event = {
				content: currentContent,
				collection,
				isNew
			};
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				const result = await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				if (result !== void 0) currentContent = result;
				results.push({
					success: true,
					value: currentContent,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return {
			content: currentContent,
			results
		};
	}
	/**
	* Run content:afterSave hooks
	*/
	async runContentAfterSave(content, collection, isNew) {
		const hooks = this.getTypedHooks("content:afterSave");
		const results = [];
		for (const hook of hooks) {
			const { handler } = hook;
			const event = {
				content,
				collection,
				isNew
			};
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				results.push({
					success: true,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return results;
	}
	/**
	* Run content:beforeDelete hooks
	* Returns whether deletion is allowed
	*/
	async runContentBeforeDelete(id, collection) {
		const hooks = this.getTypedHooks("content:beforeDelete");
		const results = [];
		let allowed = true;
		for (const hook of hooks) {
			const { handler } = hook;
			const event = {
				id,
				collection,
				permanent: false
			};
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				const result = await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				if (result === false) allowed = false;
				results.push({
					success: true,
					value: result !== false,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return {
			allowed,
			results
		};
	}
	/**
	* Run content:afterDelete hooks
	*/
	async runContentAfterDelete(id, collection, permanent) {
		const hooks = this.getTypedHooks("content:afterDelete");
		const results = [];
		for (const hook of hooks) {
			const { handler } = hook;
			const event = {
				id,
				collection,
				permanent
			};
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				results.push({
					success: true,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return results;
	}
	/**
	* Run content state-change hooks that all share the same event shape.
	*/
	async runContentStateChangeHook(name, content, collection) {
		const hooks = this.getTypedHooks(name);
		const results = [];
		for (const hook of hooks) {
			const { handler } = hook;
			const event = {
				content,
				collection
			};
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				results.push({
					success: true,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return results;
	}
	/**
	* Run content:afterPublish hooks (fire-and-forget).
	*/
	async runContentAfterPublish(content, collection) {
		return this.runContentStateChangeHook("content:afterPublish", content, collection);
	}
	/**
	* Run content:afterUnpublish hooks (fire-and-forget).
	*/
	async runContentAfterUnpublish(content, collection) {
		return this.runContentStateChangeHook("content:afterUnpublish", content, collection);
	}
	/**
	* Run content:afterRestore hooks (fire-and-forget).
	*/
	async runContentAfterRestore(content, collection) {
		return this.runContentStateChangeHook("content:afterRestore", content, collection);
	}
	/**
	* Run content:afterSchedule hooks (fire-and-forget).
	*/
	async runContentAfterSchedule(content, collection) {
		return this.runContentStateChangeHook("content:afterSchedule", content, collection);
	}
	/**
	* Run content:afterUnschedule hooks (fire-and-forget).
	*/
	async runContentAfterUnschedule(content, collection) {
		return this.runContentStateChangeHook("content:afterUnschedule", content, collection);
	}
	/**
	* Run media:beforeUpload hooks
	*/
	async runMediaBeforeUpload(file) {
		const hooks = this.getTypedHooks("media:beforeUpload");
		const results = [];
		let currentFile = file;
		for (const hook of hooks) {
			const { handler } = hook;
			const event = { file: currentFile };
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				const result = await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				if (result !== void 0) currentFile = result;
				results.push({
					success: true,
					value: currentFile,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return {
			file: currentFile,
			results
		};
	}
	/**
	* Run media:afterUpload hooks
	*/
	async runMediaAfterUpload(media) {
		const hooks = this.getTypedHooks("media:afterUpload");
		const results = [];
		for (const hook of hooks) {
			const { handler } = hook;
			const event = { media };
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				results.push({
					success: true,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return results;
	}
	/**
	* Invoke the cron hook for a specific plugin.
	*
	* Unlike other hooks which broadcast to all plugins, the cron hook is
	* dispatched only to the target plugin — the one that owns the task.
	*/
	async invokeCronHook(pluginId, event) {
		const hook = this.getTypedHooks("cron").find((h) => h.pluginId === pluginId);
		if (!hook) return {
			success: false,
			error: /* @__PURE__ */ new Error(`Plugin "${pluginId}" has no cron hook registered`),
			pluginId,
			duration: 0
		};
		const { handler } = hook;
		const ctx = this.getContext(pluginId);
		const start = Date.now();
		try {
			await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
			return {
				success: true,
				pluginId,
				duration: Date.now() - start
			};
		} catch (error) {
			return {
				success: false,
				error: error instanceof Error ? error : new Error(String(error)),
				pluginId,
				duration: Date.now() - start
			};
		}
	}
	/**
	* Run email:beforeSend hooks (middleware pipeline).
	*
	* Each handler receives the message and returns a modified message or
	* `false` to cancel delivery. The pipeline chains message transformations —
	* each handler receives the output of the previous one.
	*/
	async runEmailBeforeSend(message, source) {
		const hooks = this.getTypedHooks("email:beforeSend");
		const results = [];
		let currentMessage = message;
		for (const hook of hooks) {
			const { handler } = hook;
			const event = {
				message: { ...currentMessage },
				source
			};
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				const result = await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				if (result === false) {
					results.push({
						success: true,
						value: false,
						pluginId: hook.pluginId,
						duration: Date.now() - start
					});
					return {
						message: false,
						results
					};
				}
				if (result && typeof result === "object") currentMessage = result;
				results.push({
					success: true,
					value: currentMessage,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return {
			message: currentMessage,
			results
		};
	}
	/**
	* Run email:afterSend hooks (fire-and-forget).
	*
	* Errors are logged but don't propagate — they don't affect the caller.
	*/
	async runEmailAfterSend(message, source) {
		const hooks = this.getTypedHooks("email:afterSend");
		const results = [];
		for (const hook of hooks) {
			const { handler } = hook;
			const event = {
				message,
				source
			};
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
				results.push({
					success: true,
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			} catch (error) {
				console.error(`[email:afterSend] Plugin "${hook.pluginId}" error:`, error instanceof Error ? error.message : error);
				results.push({
					success: false,
					error: error instanceof Error ? error : new Error(String(error)),
					pluginId: hook.pluginId,
					duration: Date.now() - start
				});
			}
		}
		return results;
	}
	/**
	* Run comment:beforeCreate hooks (middleware pipeline).
	*
	* Each handler receives the event and returns a modified event or
	* `false` to reject the comment. The pipeline chains transformations —
	* each handler receives the output of the previous one.
	*/
	async runCommentBeforeCreate(event) {
		const hooks = this.getTypedHooks("comment:beforeCreate");
		let currentEvent = event;
		for (const hook of hooks) {
			const { handler } = hook;
			const ctx = this.getContext(hook.pluginId);
			const start = Date.now();
			try {
				const result = await this.executeWithTimeout(() => handler({ ...currentEvent }, ctx), hook.timeout);
				if (result === false) return false;
				if (result && typeof result === "object") currentEvent = result;
			} catch (error) {
				console.error(`[comment:beforeCreate] Plugin "${hook.pluginId}" error (${Date.now() - start}ms):`, error instanceof Error ? error.message : error);
				if (hook.errorPolicy === "abort") throw error;
			}
		}
		return currentEvent;
	}
	/**
	* Run comment:afterCreate hooks (fire-and-forget).
	*
	* Errors are logged but don't propagate — they don't affect the caller.
	*/
	async runCommentAfterCreate(event) {
		const hooks = this.getTypedHooks("comment:afterCreate");
		for (const hook of hooks) {
			const { handler } = hook;
			const ctx = this.getContext(hook.pluginId);
			try {
				await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
			} catch (error) {
				console.error(`[comment:afterCreate] Plugin "${hook.pluginId}" error:`, error instanceof Error ? error.message : error);
			}
		}
	}
	/**
	* Run comment:afterModerate hooks (fire-and-forget).
	*
	* Errors are logged but don't propagate — they don't affect the caller.
	*/
	async runCommentAfterModerate(event) {
		const hooks = this.getTypedHooks("comment:afterModerate");
		for (const hook of hooks) {
			const { handler } = hook;
			const ctx = this.getContext(hook.pluginId);
			try {
				await this.executeWithTimeout(() => handler(event, ctx), hook.timeout);
			} catch (error) {
				console.error(`[comment:afterModerate] Plugin "${hook.pluginId}" error:`, error instanceof Error ? error.message : error);
			}
		}
	}
	/**
	* Run page:metadata hooks. Each handler returns contributions that are
	* merged by the metadata collector. Errors are logged but don't propagate.
	*/
	async runPageMetadata(event) {
		const hooks = this.getTypedHooks("page:metadata");
		const results = [];
		for (const hook of hooks) {
			const { handler } = hook;
			const ctx = this.getContext(hook.pluginId);
			try {
				const result = await this.executeWithTimeout(() => Promise.resolve(handler(event, ctx)), hook.timeout);
				if (result != null) {
					const contributions = Array.isArray(result) ? result : [result];
					results.push({
						pluginId: hook.pluginId,
						contributions
					});
				}
			} catch (error) {
				console.error(`[page:metadata] Plugin "${hook.pluginId}" error:`, error instanceof Error ? error.message : error);
			}
		}
		return results;
	}
	/**
	* Run page:fragments hooks. Only trusted plugins should be registered
	* for this hook. Errors are logged but don't propagate.
	*/
	async runPageFragments(event) {
		const hooks = this.getTypedHooks("page:fragments");
		const results = [];
		for (const hook of hooks) {
			const { handler } = hook;
			const ctx = this.getContext(hook.pluginId);
			try {
				const result = await this.executeWithTimeout(() => Promise.resolve(handler(event, ctx)), hook.timeout);
				if (result != null) {
					const contributions = Array.isArray(result) ? result : [result];
					results.push({
						pluginId: hook.pluginId,
						contributions
					});
				}
			} catch (error) {
				console.error(`[page:fragments] Plugin "${hook.pluginId}" error:`, error instanceof Error ? error.message : error);
			}
		}
		return results;
	}
	/**
	* Check if any hooks are registered for a given name
	*/
	hasHooks(name) {
		const hooks = this.hooks.get(name);
		return hooks !== void 0 && hooks.length > 0;
	}
	/**
	* Get hook count for debugging
	*/
	getHookCount(name) {
		return this.hooks.get(name)?.length || 0;
	}
	/**
	* Get all registered hook names
	*/
	getRegisteredHooks() {
		return [...this.hooks.keys()];
	}
	/**
	* Returns hook names where at least one handler declared exclusive: true
	*/
	getRegisteredExclusiveHooks() {
		return [...this.exclusiveHookNames];
	}
	/**
	* Check if a hook is exclusive
	*/
	isExclusiveHook(name) {
		return this.exclusiveHookNames.has(name);
	}
	/**
	* Set the selected provider for an exclusive hook.
	* Called by PluginManager after resolution.
	*/
	setExclusiveSelection(hookName, pluginId) {
		this.exclusiveSelections.set(hookName, pluginId);
	}
	/**
	* Clear the selected provider for an exclusive hook.
	*/
	clearExclusiveSelection(hookName) {
		this.exclusiveSelections.delete(hookName);
	}
	/**
	* Get the selected provider for an exclusive hook (if any).
	*/
	getExclusiveSelection(hookName) {
		return this.exclusiveSelections.get(hookName);
	}
	/**
	* Get all plugins that registered a handler for a given exclusive hook.
	*/
	getExclusiveHookProviders(hookName) {
		return (this.hooks.get(hookName) ?? []).filter((h) => h.exclusive).map((h) => ({ pluginId: h.pluginId }));
	}
	/**
	* Get all plugins that registered a non-exclusive handler for a given
	* hook (e.g. `email:beforeSend`, `email:afterSend`), preserving priority
	* order. Partitions with `getExclusiveHookProviders()`, which returns
	* plugins whose registration is marked `exclusive: true`.
	*/
	getHookProviders(hookName) {
		return (this.hooks.get(hookName) ?? []).filter((h) => !h.exclusive).map((h) => ({ pluginId: h.pluginId }));
	}
	/**
	* Invoke an exclusive hook — dispatch only to the selected provider.
	* Returns null if no provider is selected or if the selected hook
	* is not found in the pipeline.
	*
	* This is a generic dispatch used by the email pipeline and other
	* exclusive hook consumers. The handler type is unknown — callers
	* must know the expected signature.
	*
	* Errors are isolated: a failing handler returns an error result
	* instead of propagating the exception to the caller.
	*/
	async invokeExclusiveHook(hookName, event) {
		const selectedPluginId = this.exclusiveSelections.get(hookName);
		if (!selectedPluginId) return null;
		const hook = (this.hooks.get(hookName) ?? []).find((h) => h.pluginId === selectedPluginId && h.exclusive);
		if (!hook) return null;
		const start = Date.now();
		try {
			const ctx = this.getContext(selectedPluginId);
			const handler = hook.handler;
			return {
				result: await this.executeWithTimeout(() => handler(event, ctx), hook.timeout),
				pluginId: selectedPluginId,
				duration: Date.now() - start
			};
		} catch (error) {
			return {
				result: void 0,
				pluginId: selectedPluginId,
				error: error instanceof Error ? error : new Error(String(error)),
				duration: Date.now() - start
			};
		}
	}
};
/**
* Create a hook pipeline from plugins
*/
function createHookPipeline(plugins, factoryOptions) {
	return new HookPipeline(plugins, factoryOptions);
}
/** Options table key prefix for exclusive hook selections */
const EXCLUSIVE_HOOK_KEY_PREFIX$1 = "emdash:exclusive_hook:";
/**
* Resolve exclusive hook selections.
*
* Shared algorithm used by both PluginManager and EmDashRuntime:
* 1. If a DB selection exists and that plugin is active → keep it.
* 2. If DB selection is stale (plugin inactive/gone) → clear it.
* 3. If no selection and only one active provider → auto-select it.
* 4. If preferred hints match an active provider → first match wins.
* 5. If multiple providers and no hint → leave unselected (admin must choose).
*/
async function resolveExclusiveHooks(opts) {
	const { pipeline, isActive, getOption, getOptions, setOption, deleteOption, preferredHints } = opts;
	const exclusiveHookNames = pipeline.getRegisteredExclusiveHooks();
	if (exclusiveHookNames.length === 0) return;
	let batchedSelections;
	if (getOptions) try {
		batchedSelections = await getOptions(exclusiveHookNames.map((hookName) => `${EXCLUSIVE_HOOK_KEY_PREFIX$1}${hookName}`));
	} catch {
		return;
	}
	for (const hookName of exclusiveHookNames) {
		const providers = pipeline.getExclusiveHookProviders(hookName);
		const activeProviderIds = new Set(providers.map((p) => p.pluginId).filter((id) => isActive(id)));
		const key = `${EXCLUSIVE_HOOK_KEY_PREFIX$1}${hookName}`;
		let currentSelection = null;
		if (batchedSelections) currentSelection = batchedSelections.get(key) ?? null;
		else try {
			currentSelection = await getOption(key);
		} catch {
			continue;
		}
		if (currentSelection && activeProviderIds.has(currentSelection)) {
			pipeline.setExclusiveSelection(hookName, currentSelection);
			continue;
		}
		if (currentSelection) try {
			await deleteOption(key);
		} catch {}
		if (activeProviderIds.size === 1) {
			const [onlyProvider] = activeProviderIds;
			try {
				await setOption(key, onlyProvider);
			} catch {}
			pipeline.setExclusiveSelection(hookName, onlyProvider);
			continue;
		}
		if (preferredHints) {
			let found = false;
			for (const [pluginId, hooks] of preferredHints) if (hooks.includes(hookName) && activeProviderIds.has(pluginId)) {
				try {
					await setOption(key, pluginId);
				} catch {}
				pipeline.setExclusiveSelection(hookName, pluginId);
				found = true;
				break;
			}
			if (found) continue;
		}
		pipeline.clearExclusiveSelection(hookName);
	}
}

//#endregion
//#region src/plugins/email.ts
/**
* Email Pipeline
*
* Orchestrates the three-stage email pipeline:
* 1. email:beforeSend hooks (middleware — transform, validate, cancel)
* 2. email:deliver hook (exclusive — exactly one provider delivers)
* 3. email:afterSend hooks (logging, analytics, fire-and-forget)
*
* Security features:
* - Recursion guard prevents re-entrant sends (e.g. plugin calling ctx.email.send from a hook)
* - System emails (source="system") bypass email:beforeSend and email:afterSend hooks entirely
*   to protect auth tokens from exfiltration by plugin hooks
*
*/
/** Hook name for the exclusive email delivery hook */
const EMAIL_DELIVER_HOOK = "email:deliver";
/** Source value used for auth emails (magic links, invites, password resets) */
const SYSTEM_SOURCE = "system";
/**
* Error thrown when ctx.email.send() is called but no provider is configured.
*/
var EmailNotConfiguredError = class extends Error {
	constructor() {
		super("No email provider is configured. Install and activate an email provider plugin, then select it in Settings > Email.");
		this.name = "EmailNotConfiguredError";
	}
};
/**
* Error thrown when a recursive email send is detected.
*/
var EmailRecursionError = class extends Error {
	constructor() {
		super("Recursive email send detected. A plugin hook attempted to send an email from within the email pipeline, which would cause infinite recursion.");
		this.name = "EmailRecursionError";
	}
};
/**
* Recursion guard using AsyncLocalStorage.
*
* EmailPipeline is a singleton (worker-lifetime cached via EmDashRuntime).
* Instance state like `sendDepth` would false-positive under concurrent
* requests because two unrelated sends would increment the same counter.
* ALS scopes the guard to the current async execution context, so concurrent
* requests each get their own independent recursion tracking.
*/
const emailSendALS = new AsyncLocalStorage();
/**
* EmailPipeline orchestrates email delivery through the plugin hook system.
*
* The pipeline runs in three stages:
* 1. email:beforeSend — middleware hooks that can transform or cancel messages
* 2. email:deliver — exclusive hook dispatching to the selected provider
* 3. email:afterSend — fire-and-forget hooks for logging/analytics
*/
var EmailPipeline = class {
	pipeline;
	constructor(pipeline) {
		this.pipeline = pipeline;
	}
	/**
	* Replace the underlying hook pipeline.
	*
	* Called by the runtime when rebuilding the hook pipeline after a
	* plugin is enabled or disabled, so the email pipeline dispatches
	* to the current set of active hooks.
	*/
	setPipeline(pipeline) {
		this.pipeline = pipeline;
	}
	/**
	* Send an email through the full pipeline.
	*
	* @param message - The email to send
	* @param source - Where the email originated ("system" for auth, plugin ID for plugins)
	* @throws EmailNotConfiguredError if no provider is selected
	* @throws EmailRecursionError if called re-entrantly from within a hook
	* @throws Error if the provider handler throws
	*/
	async send(message, source) {
		const store = emailSendALS.getStore();
		if (store && store.depth > 0) throw new EmailRecursionError();
		const run = () => this.sendInner(message, source);
		if (store) {
			store.depth++;
			try {
				await run();
			} finally {
				store.depth--;
			}
		} else await emailSendALS.run({ depth: 1 }, run);
	}
	/**
	* Inner send implementation, separated from the recursion guard.
	*/
	async sendInner(message, source) {
		if (!message || typeof message !== "object") throw new Error("Invalid email message: message must be an object");
		if (!message.to || typeof message.to !== "string") throw new Error("Invalid email message: 'to' is required and must be a string");
		if (!message.subject || typeof message.subject !== "string") throw new Error("Invalid email message: 'subject' is required and must be a string");
		if (!message.text || typeof message.text !== "string") throw new Error("Invalid email message: 'text' is required and must be a string");
		const isSystemEmail = source === SYSTEM_SOURCE;
		let finalMessage;
		if (isSystemEmail) finalMessage = message;
		else {
			const beforeResult = await this.pipeline.runEmailBeforeSend(message, source);
			if (beforeResult.message === false) {
				const cancelledBy = beforeResult.results.find((r) => r.value === false)?.pluginId ?? "unknown";
				console.info(`[email] Email to "${message.to}" cancelled by plugin "${cancelledBy}"`);
				return;
			}
			finalMessage = beforeResult.message;
		}
		const deliverEvent = {
			message: finalMessage,
			source
		};
		const deliverResult = await this.pipeline.invokeExclusiveHook(EMAIL_DELIVER_HOOK, deliverEvent);
		if (!deliverResult) throw new EmailNotConfiguredError();
		if (deliverResult.error) throw deliverResult.error;
		if (!isSystemEmail) this.pipeline.runEmailAfterSend(finalMessage, source).catch((err) => console.error("[email] afterSend pipeline error:", err instanceof Error ? err.message : err));
	}
	/**
	* Check if an email provider is configured and available.
	*
	* Returns true if an email:deliver provider is selected in the exclusive
	* hook system. Plugins and auth code use this to decide whether to show
	* "send invite" vs "copy invite link" UI.
	*/
	isAvailable() {
		return this.pipeline.getExclusiveSelection(EMAIL_DELIVER_HOOK) !== void 0;
	}
};

//#endregion
//#region src/plugins/routes.ts
/**
* Plugin Routes v2
*
* Handles plugin API route invocation with:
* - Input validation via Zod schemas
* - Route context creation
* - Error handling
*
*/
/**
* Body-reading methods on `Request`. EmDash parses the request body once before
* the handler runs and exposes the result as `ctx.input`, leaving the underlying
* stream consumed. Calling any of these on `ctx.request` would re-read a spent
* stream and throw an opaque platform error ("Body is unusable: Body has already
* been read") with no hint about `ctx.input` — so the guard replaces them with an
* actionable message instead (#1293).
*/
const CONSUMED_BODY_METHODS = new Set([
	"json",
	"text",
	"arrayBuffer",
	"blob",
	"formData",
	"bytes"
]);
/**
* Wrap the request handed to a plugin route handler so an accidental
* `ctx.request.json()` (or `.text()`, `.formData()`, …) fails with a message
* pointing at `ctx.input` rather than the runtime's cryptic "body already read"
* error. Every non-body member passes through unchanged; function members are
* bound to the underlying request so methods like `clone()` don't throw an
* "Illegal invocation" when called on the proxy.
*/
function guardConsumedRequestBody(request) {
	return new Proxy(request, { get(target, prop) {
		if (typeof prop === "string" && CONSUMED_BODY_METHODS.has(prop)) return () => {
			throw new Error(`[emdash] ctx.request.${prop}() is not available inside a plugin route handler: EmDash has already parsed the request body and exposes it as ctx.input. Read ctx.input instead of ctx.request.${prop}().`);
		};
		const value = Reflect.get(target, prop, target);
		return typeof value === "function" ? value.bind(target) : value;
	} });
}
/**
* Route handler for a plugin
*/
var PluginRouteHandler = class {
	contextFactory;
	plugin;
	trustedProxyHeaders;
	constructor(plugin, factoryOptions) {
		this.plugin = plugin;
		this.contextFactory = new PluginContextFactory(factoryOptions);
		this.trustedProxyHeaders = factoryOptions.trustedProxyHeaders ?? [];
	}
	/**
	* Invoke a route by name
	*/
	async invoke(routeName, options) {
		const route = this.plugin.routes[routeName];
		if (!route) return {
			success: false,
			error: {
				code: "ROUTE_NOT_FOUND",
				message: `Route "${routeName}" not found in plugin "${this.plugin.id}"`
			},
			status: 404
		};
		let validatedInput;
		if (route.input) {
			const parseResult = route.input.safeParse(options.body);
			if (!parseResult.success) return {
				success: false,
				error: {
					code: "VALIDATION_ERROR",
					message: "Invalid request body",
					details: parseResult.error.format()
				},
				status: 400
			};
			validatedInput = parseResult.data;
		} else validatedInput = options.body;
		const routeContext = {
			...this.contextFactory.createContext(this.plugin),
			input: validatedInput,
			request: guardConsumedRequestBody(options.request),
			requestMeta: extractRequestMeta(options.request, this.trustedProxyHeaders)
		};
		try {
			return {
				success: true,
				data: await route.handler(routeContext),
				status: 200
			};
		} catch (error) {
			if (error instanceof PluginRouteError) return {
				success: false,
				error: {
					code: error.code,
					message: error.message,
					details: error.details
				},
				status: error.status
			};
			console.error(`[plugin:${this.plugin.id}] Route handler failed:`, error);
			return {
				success: false,
				error: {
					code: "INTERNAL_ERROR",
					message: "An internal error occurred"
				},
				status: 500
			};
		}
	}
	/**
	* Get all route names
	*/
	getRouteNames() {
		return Object.keys(this.plugin.routes);
	}
	/**
	* Check if a route exists
	*/
	hasRoute(name) {
		return name in this.plugin.routes;
	}
	/**
	* Get route metadata without invoking the handler.
	* Returns null if the route doesn't exist.
	*/
	getRouteMeta(name) {
		const route = this.plugin.routes[name];
		if (!route) return null;
		return { public: route.public === true };
	}
};
/**
* Error class for plugin routes
* Allows plugins to return structured errors with specific HTTP status codes
*/
var PluginRouteError = class PluginRouteError extends Error {
	constructor(code, message, status = 400, details) {
		super(message);
		this.code = code;
		this.status = status;
		this.details = details;
		this.name = "PluginRouteError";
	}
	/**
	* Create a bad request error (400)
	*/
	static badRequest(message, details) {
		return new PluginRouteError("BAD_REQUEST", message, 400, details);
	}
	/**
	* Create an unauthorized error (401)
	*/
	static unauthorized(message = "Unauthorized") {
		return new PluginRouteError("UNAUTHORIZED", message, 401);
	}
	/**
	* Create a forbidden error (403)
	*/
	static forbidden(message = "Forbidden") {
		return new PluginRouteError("FORBIDDEN", message, 403);
	}
	/**
	* Create a not found error (404)
	*/
	static notFound(message = "Not found") {
		return new PluginRouteError("NOT_FOUND", message, 404);
	}
	/**
	* Create a conflict error (409)
	*/
	static conflict(message, details) {
		return new PluginRouteError("CONFLICT", message, 409, details);
	}
	/**
	* Create an internal error (500)
	*/
	static internal(message = "Internal error") {
		return new PluginRouteError("INTERNAL_ERROR", message, 500);
	}
};
/**
* Registry for all plugin route handlers
*/
var PluginRouteRegistry = class {
	handlers = /* @__PURE__ */ new Map();
	constructor(factoryOptions) {
		this.factoryOptions = factoryOptions;
	}
	/**
	* Register a plugin's routes
	*/
	register(plugin) {
		const handler = new PluginRouteHandler(plugin, this.factoryOptions);
		this.handlers.set(plugin.id, handler);
	}
	/**
	* Unregister a plugin's routes
	*/
	unregister(pluginId) {
		this.handlers.delete(pluginId);
	}
	/**
	* Invoke a plugin route
	*/
	async invoke(pluginId, routeName, options) {
		const handler = this.handlers.get(pluginId);
		if (!handler) return {
			success: false,
			error: {
				code: "PLUGIN_NOT_FOUND",
				message: `Plugin "${pluginId}" not found`
			},
			status: 404
		};
		return handler.invoke(routeName, options);
	}
	/**
	* Get all registered plugin IDs
	*/
	getPluginIds() {
		return [...this.handlers.keys()];
	}
	/**
	* Get routes for a plugin
	*/
	getRoutes(pluginId) {
		return this.handlers.get(pluginId)?.getRouteNames() ?? [];
	}
	/**
	* Get route metadata for a specific plugin route.
	* Returns null if the plugin or route doesn't exist.
	*/
	getRouteMeta(pluginId, routeName) {
		const handler = this.handlers.get(pluginId);
		if (!handler) return null;
		return handler.getRouteMeta(routeName);
	}
};

//#endregion
//#region src/plugins/manager.ts
/** Options table key prefix for exclusive hook DB reads via PluginManager */
const EXCLUSIVE_HOOK_KEY_PREFIX = "emdash:exclusive_hook:";
/**
* Plugin Manager v2
*
* Manages the full lifecycle of plugins and coordinates hooks/routes.
*/
var PluginManager = class {
	plugins = /* @__PURE__ */ new Map();
	hookPipeline = null;
	routeRegistry = null;
	factoryOptions;
	initialized = false;
	constructor(options) {
		this.options = options;
		this.factoryOptions = {
			db: options.db,
			storage: options.storage,
			getUploadUrl: options.getUploadUrl,
			trustedProxyHeaders: options.trustedProxyHeaders
		};
	}
	/**
	* Set the email pipeline used when creating plugin contexts.
	* Reinitializes routes/hooks if already initialized so ctx.email is available immediately.
	*/
	setEmailPipeline(pipeline) {
		this.factoryOptions.emailPipeline = pipeline;
		if (this.initialized) this.reinitialize();
	}
	/**
	* Register a plugin definition
	* This resolves the definition and adds it to the manager, but doesn't install it
	*/
	register(definition) {
		const resolved = definePlugin(definition);
		if (this.plugins.has(resolved.id)) throw new Error(`Plugin "${resolved.id}" is already registered`);
		this.plugins.set(resolved.id, {
			plugin: resolved,
			state: "registered"
		});
		this.initialized = false;
		return resolved;
	}
	/**
	* Register multiple plugins
	*/
	registerAll(definitions) {
		for (const def of definitions) this.register(def);
	}
	/**
	* Unregister a plugin
	* Plugin must be inactive or just registered
	*/
	unregister(pluginId) {
		const entry = this.plugins.get(pluginId);
		if (!entry) return false;
		if (entry.state === "active") throw new Error(`Cannot unregister active plugin "${pluginId}". Deactivate it first.`);
		this.plugins.delete(pluginId);
		this.initialized = false;
		return true;
	}
	/**
	* Install a plugin (run install hooks, set up storage)
	*/
	async install(pluginId) {
		const entry = this.plugins.get(pluginId);
		if (!entry) throw new Error(`Plugin "${pluginId}" not found`);
		if (entry.state !== "registered") throw new Error(`Plugin "${pluginId}" is already installed (state: ${entry.state})`);
		this.ensureInitialized();
		const results = await this.hookPipeline.runPluginInstall(pluginId);
		const failed = results.find((r) => !r.success);
		if (failed) throw new Error(`Plugin install failed: ${failed.error?.message ?? "Unknown error"}`);
		entry.state = "installed";
		return results;
	}
	/**
	* Activate a plugin (run activate hooks, enable hooks/routes)
	*/
	async activate(pluginId) {
		const entry = this.plugins.get(pluginId);
		if (!entry) throw new Error(`Plugin "${pluginId}" not found`);
		if (entry.state === "active") return [];
		if (entry.state === "registered") await this.install(pluginId);
		this.ensureInitialized();
		const results = await this.hookPipeline.runPluginActivate(pluginId);
		const failed = results.find((r) => !r.success);
		if (failed) throw new Error(`Plugin activation failed: ${failed.error?.message ?? "Unknown error"}`);
		entry.state = "active";
		await setCronTasksEnabled(this.options.db, pluginId, true);
		this.reinitialize();
		await this.resolveExclusiveHooks();
		return results;
	}
	/**
	* Deactivate a plugin (run deactivate hooks, disable hooks/routes)
	*/
	async deactivate(pluginId) {
		const entry = this.plugins.get(pluginId);
		if (!entry) throw new Error(`Plugin "${pluginId}" not found`);
		if (entry.state !== "active") return [];
		this.ensureInitialized();
		const results = await this.hookPipeline.runPluginDeactivate(pluginId);
		await setCronTasksEnabled(this.options.db, pluginId, false);
		entry.state = "inactive";
		this.reinitialize();
		await this.resolveExclusiveHooks();
		return results;
	}
	/**
	* Uninstall a plugin (run uninstall hooks, optionally delete data)
	*/
	async uninstall(pluginId, deleteData = false) {
		const entry = this.plugins.get(pluginId);
		if (!entry) throw new Error(`Plugin "${pluginId}" not found`);
		if (entry.state === "active") await this.deactivate(pluginId);
		this.ensureInitialized();
		const results = await this.hookPipeline.runPluginUninstall(pluginId, deleteData);
		await this.deleteCronTasks(pluginId);
		this.plugins.delete(pluginId);
		this.initialized = false;
		await this.resolveExclusiveHooks();
		return results;
	}
	/**
	* Run content:beforeSave hooks across all active plugins
	*/
	async runContentBeforeSave(content, collection, isNew) {
		this.ensureInitialized();
		return this.hookPipeline.runContentBeforeSave(content, collection, isNew);
	}
	/**
	* Run content:afterSave hooks across all active plugins
	*/
	async runContentAfterSave(content, collection, isNew) {
		this.ensureInitialized();
		return this.hookPipeline.runContentAfterSave(content, collection, isNew);
	}
	/**
	* Run content:beforeDelete hooks across all active plugins
	*/
	async runContentBeforeDelete(id, collection) {
		this.ensureInitialized();
		return this.hookPipeline.runContentBeforeDelete(id, collection);
	}
	/**
	* Run content:afterDelete hooks across all active plugins
	*/
	async runContentAfterDelete(id, collection, permanent) {
		this.ensureInitialized();
		return this.hookPipeline.runContentAfterDelete(id, collection, permanent);
	}
	/**
	* Run content:afterPublish hooks across all active plugins
	*/
	async runContentAfterPublish(content, collection) {
		this.ensureInitialized();
		return this.hookPipeline.runContentAfterPublish(content, collection);
	}
	/**
	* Run content:afterUnpublish hooks across all active plugins
	*/
	async runContentAfterUnpublish(content, collection) {
		this.ensureInitialized();
		return this.hookPipeline.runContentAfterUnpublish(content, collection);
	}
	/**
	* Run content:afterRestore hooks across all active plugins
	*/
	async runContentAfterRestore(content, collection) {
		this.ensureInitialized();
		return this.hookPipeline.runContentAfterRestore(content, collection);
	}
	/**
	* Run content:afterSchedule hooks across all active plugins
	*/
	async runContentAfterSchedule(content, collection) {
		this.ensureInitialized();
		return this.hookPipeline.runContentAfterSchedule(content, collection);
	}
	/**
	* Run content:afterUnschedule hooks across all active plugins
	*/
	async runContentAfterUnschedule(content, collection) {
		this.ensureInitialized();
		return this.hookPipeline.runContentAfterUnschedule(content, collection);
	}
	/**
	* Run media:beforeUpload hooks across all active plugins
	*/
	async runMediaBeforeUpload(file) {
		this.ensureInitialized();
		return this.hookPipeline.runMediaBeforeUpload(file);
	}
	/**
	* Run media:afterUpload hooks across all active plugins
	*/
	async runMediaAfterUpload(media) {
		this.ensureInitialized();
		return this.hookPipeline.runMediaAfterUpload(media);
	}
	/**
	* Invoke the cron hook for a specific plugin (per-plugin dispatch).
	* Used as the InvokeCronHookFn callback for CronExecutor.
	*/
	async invokeCronHook(pluginId, event) {
		this.ensureInitialized();
		const result = await this.hookPipeline.invokeCronHook(pluginId, event);
		if (!result.success && result.error) throw result.error;
	}
	/**
	* Invoke a plugin route
	*/
	async invokeRoute(pluginId, routeName, options) {
		this.ensureInitialized();
		return this.routeRegistry.invoke(pluginId, routeName, options);
	}
	/**
	* Get all routes for a plugin
	*/
	getPluginRoutes(pluginId) {
		this.ensureInitialized();
		return this.routeRegistry.getRoutes(pluginId);
	}
	/**
	* Get a plugin by ID
	*/
	getPlugin(pluginId) {
		return this.plugins.get(pluginId)?.plugin;
	}
	/**
	* Get plugin state
	*/
	getPluginState(pluginId) {
		return this.plugins.get(pluginId)?.state;
	}
	/**
	* Get all registered plugins
	*/
	getAllPlugins() {
		return Array.from(this.plugins.values(), (entry) => ({
			plugin: entry.plugin,
			state: entry.state
		}));
	}
	/**
	* Get all active plugins
	*/
	getActivePlugins() {
		return [...this.plugins.values()].filter((entry) => entry.state === "active").map((entry) => entry.plugin);
	}
	/**
	* Check if a plugin exists
	*/
	hasPlugin(pluginId) {
		return this.plugins.has(pluginId);
	}
	/**
	* Check if a plugin is active
	*/
	isActive(pluginId) {
		return this.plugins.get(pluginId)?.state === "active";
	}
	/**
	* Get all plugins that registered a handler for an exclusive hook.
	*/
	getExclusiveHookProviders(hookName) {
		this.ensureInitialized();
		return this.hookPipeline.getExclusiveHookProviders(hookName).map((p) => {
			const plugin = this.plugins.get(p.pluginId);
			return {
				pluginId: p.pluginId,
				pluginName: plugin?.plugin.id ?? p.pluginId
			};
		});
	}
	/**
	* Read the selected provider for an exclusive hook from the options table.
	*/
	async getExclusiveHookSelection(hookName) {
		return new OptionsRepository(this.options.db).get(`${EXCLUSIVE_HOOK_KEY_PREFIX}${hookName}`);
	}
	/**
	* Set the selected provider for an exclusive hook in the options table.
	* Pass null to clear the selection.
	*/
	async setExclusiveHookSelection(hookName, pluginId) {
		const optionsRepo = new OptionsRepository(this.options.db);
		const key = `${EXCLUSIVE_HOOK_KEY_PREFIX}${hookName}`;
		if (pluginId === null) {
			await optionsRepo.delete(key);
			this.hookPipeline?.clearExclusiveSelection(hookName);
			return;
		}
		const entry = this.plugins.get(pluginId);
		if (!entry) throw new Error(`Plugin "${pluginId}" not found`);
		if (entry.state !== "active") throw new Error(`Plugin "${pluginId}" is not active`);
		await optionsRepo.set(key, pluginId);
		this.hookPipeline?.setExclusiveSelection(hookName, pluginId);
	}
	/**
	* Resolution algorithm for exclusive hooks.
	*
	* Delegates to the shared resolveExclusiveHooks() function.
	* See hooks.ts for the full algorithm description.
	*/
	async resolveExclusiveHooks(preferredHints) {
		this.ensureInitialized();
		const optionsRepo = new OptionsRepository(this.options.db);
		await resolveExclusiveHooks({
			pipeline: this.hookPipeline,
			isActive: (pluginId) => this.isActive(pluginId),
			getOption: (key) => optionsRepo.get(key),
			getOptions: (keys) => optionsRepo.getMany(keys),
			setOption: (key, value) => optionsRepo.set(key, value),
			deleteOption: async (key) => {
				await optionsRepo.delete(key);
			},
			preferredHints
		});
	}
	/**
	* Get all exclusive hooks with their providers and current selections.
	* Used by the admin API.
	*/
	async getExclusiveHooksInfo() {
		this.ensureInitialized();
		const exclusiveHookNames = this.hookPipeline.getRegisteredExclusiveHooks();
		const result = [];
		for (const hookName of exclusiveHookNames) {
			const providers = this.hookPipeline.getExclusiveHookProviders(hookName);
			const selection = await this.getExclusiveHookSelection(hookName);
			result.push({
				hookName,
				providers,
				selectedPluginId: selection
			});
		}
		return result;
	}
	/**
	* Initialize or reinitialize the hook pipeline and route registry
	*/
	ensureInitialized() {
		if (this.initialized) return;
		const activePlugins = this.getActivePlugins();
		this.hookPipeline = new HookPipeline(activePlugins, this.factoryOptions);
		this.routeRegistry = new PluginRouteRegistry(this.factoryOptions);
		for (const plugin of activePlugins) this.routeRegistry.register(plugin);
		this.initialized = true;
	}
	/**
	* Force reinitialization (useful after plugin state changes)
	*/
	reinitialize() {
		this.initialized = false;
		this.ensureInitialized();
	}
	/**
	* Delete all cron tasks for a plugin.
	* Used during uninstall.
	*/
	async deleteCronTasks(pluginId) {
		try {
			await sql`
				DELETE FROM _emdash_cron_tasks
				WHERE plugin_id = ${pluginId}
			`.execute(this.options.db);
		} catch {}
	}
};
/**
* Create a plugin manager
*/
function createPluginManager(options) {
	return new PluginManager(options);
}

//#endregion
//#region src/plugins/scheduler/node.ts
/** Minimum polling interval (ms) — prevents tight loops if next_run_at is in the past */
const MIN_INTERVAL_MS = 1e3;
/**
* Maximum polling interval (ms). Each wake runs the maintenance pass — stale
* lock recovery *and* the scheduled-publishing sweep + system cleanup. The cap
* is the worst-case latency for scheduled content when no plugin cron task is
* due sooner (`getNextDueTime()` only knows about cron tasks, not content
* `scheduled_at`). Held at 60s so Node publish latency matches the Cloudflare
* Cron Trigger cadence (`* * * * *`) rather than lagging up to five minutes.
*/
const MAX_INTERVAL_MS = 60 * 1e3;
var NodeCronScheduler = class {
	timer = null;
	running = false;
	systemCleanup = null;
	constructor(executor) {
		this.executor = executor;
	}
	setSystemCleanup(fn) {
		this.systemCleanup = fn;
	}
	start() {
		this.running = true;
		this.arm();
	}
	stop() {
		this.running = false;
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
	}
	reschedule() {
		if (!this.running) return;
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
		this.arm();
	}
	arm() {
		if (!this.running) return;
		this.executor.getNextDueTime().then((nextDue) => {
			if (!this.running) return void 0;
			let delayMs;
			if (nextDue) {
				const dueAt = new Date(nextDue).getTime();
				delayMs = Math.max(dueAt - Date.now(), MIN_INTERVAL_MS);
				delayMs = Math.min(delayMs, MAX_INTERVAL_MS);
			} else delayMs = MAX_INTERVAL_MS;
			this.timer = setTimeout(() => {
				if (!this.running) return;
				this.executeTick();
			}, delayMs);
			if (this.timer && typeof this.timer === "object" && "unref" in this.timer) this.timer.unref();
		}).catch((error) => {
			console.error("[cron:node] Failed to get next due time:", error);
			if (this.running) {
				this.timer = setTimeout(() => this.arm(), MAX_INTERVAL_MS);
				if (this.timer && typeof this.timer === "object" && "unref" in this.timer) this.timer.unref();
			}
		});
	}
	executeTick() {
		if (!this.running) return;
		const tasks = [this.executor.tick(), this.executor.recoverStaleLocks()];
		if (this.systemCleanup) tasks.push(this.systemCleanup());
		Promise.allSettled(tasks).then((results) => {
			for (const r of results) if (r.status === "rejected") console.error("[cron:node] Tick task failed:", r.reason);
		}).finally(() => {
			if (this.running) this.arm();
		});
	}
};

//#endregion
//#region src/plugins/sandbox/noop.ts
/**
* Error thrown when attempting to use sandboxing on an unsupported platform.
*/
var SandboxNotAvailableError = class extends Error {
	constructor() {
		super("Plugin sandboxing is not available. Configure a sandbox runner: use @emdash-cms/cloudflare/sandbox on Cloudflare, or @emdash-cms/sandbox-workerd/sandbox on Node.js (requires workerd). Without sandboxing, use trusted plugins (from config) instead.");
		this.name = "SandboxNotAvailableError";
	}
};
/**
* No-op sandbox runner for platforms without isolation support.
*
* - `isAvailable()` returns false
* - `load()` throws SandboxNotAvailableError
* - `terminateAll()` is a no-op
*
* This is the default runner when no platform adapter is configured.
*/
var NoopSandboxRunner = class {
	/**
	* Always returns false - sandboxing is not available.
	*/
	isAvailable() {
		return false;
	}
	/**
	* Always returns false - no sandbox runtime to be healthy.
	*/
	isHealthy() {
		return false;
	}
	/**
	* Always throws - can't load sandboxed plugins without isolation.
	*/
	async load(_manifest, _code) {
		throw new SandboxNotAvailableError();
	}
	/**
	* No-op - sandboxing not available, email callback is irrelevant.
	*/
	setEmailSend() {}
	/**
	* No-op - nothing to terminate.
	*/
	async terminateAll() {}
};
/**
* Create a no-op sandbox runner.
* This is used as the default when no platform adapter is configured.
*/
function createNoopSandboxRunner(_options) {
	return new NoopSandboxRunner();
}

//#endregion
//#region src/plugins/sandbox/types.ts
/**
* Error thrown when the sandbox runtime is unavailable.
* This happens when the sidecar process has crashed or hasn't started.
*/
var SandboxUnavailableError = class extends Error {
	constructor(pluginId, reason) {
		super(`Plugin sandbox unavailable for ${pluginId}: ${reason}`);
		this.name = "SandboxUnavailableError";
	}
};

//#endregion
//#region src/comments/ranking.ts
/**
* Comment ranking utilities (Tier 1 of the best-in-class comments RFC).
*
* Wilson score lower-bound (95% confidence) — the same primitive Reddit uses
* for its "Best" comment sort. Ranks by the statistical lower bound of the
* positive-reaction proportion rather than the raw count, so a comment with a
* couple of reactions can't outrank a heavily-reacted one until it earns
* confidence, and a late-but-popular comment still rises (submission time is
* irrelevant).
*
* Positive-only reactions (the recommended default) degrade gracefully: with
* `down = 0` the score still increases monotonically with `up` while penalising
* low-sample comments — wilson(1,0) ≈ 0.21, wilson(10,0) ≈ 0.73,
* wilson(200,0) ≈ 0.98.
*/
/** z for a 95% two-sided confidence interval. */
const DEFAULT_Z = 1.96;
/** Reactions that count against a comment when both signals are in use. */
const NEGATIVE_REACTIONS = new Set(["dislike", "down"]);
/**
* Wilson score lower bound of the positive proportion.
*
* @param up   count of positive reactions
* @param down count of negative reactions
* @returns a score in [0, 1]; 0 when there are no reactions
*/
function wilsonLowerBound(up, down, z = DEFAULT_Z) {
	const n = up + down;
	if (n <= 0) return 0;
	const phat = up / n;
	const z2 = z * z;
	const denom = 1 + z2 / n;
	return (phat + z2 / (2 * n) - z * Math.sqrt((phat * (1 - phat) + z2 / (4 * n)) / n)) / denom;
}
/**
* Reduce a per-reaction count map to a single rank score via the Wilson
* lower bound. Any reaction not in {@link NEGATIVE_REACTIONS} is treated as
* positive, so the positive-only default (just `like`) works without special
* casing.
*/
function reactionScore(counts) {
	let up = 0;
	let down = 0;
	for (const [reaction, count] of Object.entries(counts)) if (NEGATIVE_REACTIONS.has(reaction)) down += count;
	else up += count;
	return wilsonLowerBound(up, down);
}

//#endregion
//#region src/comments/query.ts
/**
* Get approved comments for a content item.
*
* @example
* ```ts
* import { getComments } from "emdash";
*
* const { items, total } = await getComments({
*   collection: "posts",
*   contentId: post.id,
*   threaded: true,
* });
* ```
*/
async function getComments(options) {
	const sort = options.sort ?? "oldest";
	const withReactions = options.reactions || sort === "best";
	const threaded = options.threaded ? "t" : "f";
	return cachedQuery({
		namespace: CacheNamespace.COMMENTS,
		key: `comments:${options.collection}:${options.contentId}:${threaded}:${withReactions ? "r" : "n"}:${sort}`,
		load: async () => {
			return getCommentsWithDb(await getDb(), options);
		}
	});
}
/**
* Get approved comments with an explicit db handle.
*
* @internal Use `getComments()` in templates. This variant is for routes
* that already have a database handle.
*/
async function getCommentsWithDb(db, options) {
	const repo = new CommentRepository(db);
	const total = await repo.countByContent(options.collection, options.contentId, "approved");
	const result = await repo.findByContent(options.collection, options.contentId, {
		status: "approved",
		limit: 500
	});
	const items = options.threaded ? CommentRepository.assembleThreads(result.items).map((c) => CommentRepository.toPublicComment(c)) : result.items.map((c) => CommentRepository.toPublicComment(c));
	if (options.reactions || options.sort === "best") {
		await attachReactions(db, items);
		if (options.sort === "best") sortByBest(items);
	}
	return {
		items,
		total
	};
}
/**
* Attach aggregate reaction counts to a list of public comments (and their
* replies), in a single batched query.
*/
async function attachReactions(db, items) {
	const ids = [];
	for (const comment of items) {
		ids.push(comment.id);
		if (comment.replies) for (const reply of comment.replies) ids.push(reply.id);
	}
	if (ids.length === 0) return;
	const counts = await new CommentReactionRepository(db).countsForComments(ids);
	const assign = (comment) => {
		const reactions = counts.get(comment.id);
		if (reactions) comment.reactions = reactions;
	};
	for (const comment of items) {
		assign(comment);
		comment.replies?.forEach(assign);
	}
}
/**
* Sort top-level comments by Wilson-scored reactions (descending), tie-broken
* by oldest-first to keep ordering stable.
*/
function sortByBest(items) {
	items.sort((a, b) => {
		const scoreDelta = reactionScore(b.reactions ?? {}) - reactionScore(a.reactions ?? {});
		if (scoreDelta !== 0) return scoreDelta;
		if (a.createdAt < b.createdAt) return -1;
		if (a.createdAt > b.createdAt) return 1;
		return 0;
	});
}
/**
* Get the count of approved comments for a content item.
*
* @example
* ```ts
* import { getCommentCount } from "emdash";
*
* const count = await getCommentCount("posts", post.id);
* ```
*/
async function getCommentCount(collection, contentId) {
	return getCommentCountWithDb(await getDb(), collection, contentId);
}
/**
* Get comment count with an explicit db handle.
*
* @internal Use `getCommentCount()` in templates.
*/
async function getCommentCountWithDb(db, collection, contentId) {
	return new CommentRepository(db).countByContent(collection, contentId, "approved");
}

//#endregion
//#region src/menus/index.ts
/**
* Get a menu by name with resolved URLs.
*
* @example
* ```ts
* const menu = await getMenu("primary");
* const menuEs = await getMenu("primary", { locale: "es" });
* ```
*/
function getMenu(name, options = {}) {
	const locale = resolveLocale(options.locale);
	return requestCached(`menu:${name}:${locale ?? "*"}`, () => cachedQuery({
		namespace: CacheNamespace.MENUS,
		key: `${name}:${locale ?? "*"}`,
		load: async () => {
			return getMenuWithDb(name, await getDb(), { locale });
		}
	}));
}
/**
* Get menu by name with resolved URLs (with explicit db). Internal helper for
* admin routes that already have a database handle.
*/
async function getMenuWithDb(name, db, options = {}) {
	const chain = resolveLocaleChain(options.locale);
	const selectMenu = () => db.selectFrom("_emdash_menus").selectAll().where("name", "=", name);
	let menuRow;
	if (chain.length === 0) menuRow = await selectMenu().orderBy("locale", "asc").executeTakeFirst();
	else {
		menuRow = void 0;
		for (const locale of chain) {
			menuRow = await selectMenu().where("locale", "=", locale).executeTakeFirst();
			if (menuRow) break;
		}
	}
	if (!menuRow) return null;
	const items = await buildMenuTree(await db.selectFrom("_emdash_menu_items").selectAll().$castTo().where("menu_id", "=", menuRow.id).orderBy("sort_order", "asc").execute(), db, menuRow.locale);
	return {
		id: menuRow.id,
		name: menuRow.name,
		label: menuRow.label,
		items,
		locale: menuRow.locale,
		translationGroup: menuRow.translation_group
	};
}
/**
* Get all menus (without items, locale-filtered — for admin list / site nav
* summaries). When no locale is configured, returns menus across all locales.
*/
async function getMenus(options = {}) {
	return getMenusWithDb(await getDb(), options);
}
/**
* Get all menus (with explicit db)
*
* @internal Use `getMenus()` in templates. This variant is for admin routes
* that already have a database handle.
*/
async function getMenusWithDb(db, options = {}) {
	const locale = resolveLocale(options.locale);
	let query = db.selectFrom("_emdash_menus").select([
		"id",
		"name",
		"label",
		"locale"
	]).orderBy("name", "asc");
	if (locale !== void 0) query = query.where("locale", "=", locale);
	return query.execute();
}
/**
* Build a hierarchical menu tree from a flat list of items. Items are
* resolved against the given `locale` so references land on the right
* per-locale content rows.
*/
async function buildMenuTree(items, db, locale) {
	const collectionSlugs = /* @__PURE__ */ new Set();
	for (const item of items) {
		if (item.reference_collection) collectionSlugs.add(item.reference_collection);
		if (item.type === "page" || item.type === "post") collectionSlugs.add(item.reference_collection || `${item.type}s`);
	}
	const urlPatterns = collectionSlugs.size > 0 ? await getCollectionUrlPatterns(db, collectionSlugs) : /* @__PURE__ */ new Map();
	const validItems = (await Promise.all(items.map((item) => resolveMenuItem(item, db, urlPatterns, locale)))).filter((item) => item !== null);
	const itemMap = /* @__PURE__ */ new Map();
	const rootItems = [];
	for (const item of validItems) itemMap.set(item.id, {
		...item,
		children: []
	});
	for (const item of items) {
		const menuItem = itemMap.get(item.id);
		if (!menuItem) continue;
		if (item.parent_id) {
			const parent = itemMap.get(item.parent_id);
			if (parent) parent.children.push(menuItem);
			else rootItems.push(menuItem);
		} else rootItems.push(menuItem);
	}
	return rootItems;
}
/**
* Look up the `url_pattern` for a set of collection slugs, request-cached so
* a page rendering several menus (header, footer, ...) only pays for the
* lookup once per distinct slug set. Callers must treat the returned map as
* read-only — it is shared across cache hits within the request.
*/
function getCollectionUrlPatterns(db, collectionSlugs) {
	return requestCached(`menu-collection-patterns:${[...collectionSlugs].toSorted().join(",")}`, async () => {
		const rows = await db.selectFrom("_emdash_collections").select(["slug", "url_pattern"]).where("slug", "in", [...collectionSlugs]).execute();
		const urlPatterns = /* @__PURE__ */ new Map();
		for (const row of rows) urlPatterns.set(row.slug, row.url_pattern);
		return urlPatterns;
	});
}
/**
* Resolve a single menu item's URL. `reference_id` is a translation_group
* (migration 036 remapped all existing references); we join it against
* the per-locale ec_* row or per-locale taxonomy row.
*/
async function resolveMenuItem(item, db, urlPatterns, locale) {
	let url;
	try {
		switch (item.type) {
			case "custom":
				url = item.custom_url || "#";
				break;
			case "page":
			case "post":
				url = await resolveContentUrl(item.reference_collection || `${item.type}s`, item.reference_id, db, urlPatterns, locale);
				if (url === null) return null;
				break;
			case "taxonomy":
				url = await resolveTaxonomyUrl(item.reference_id, db, locale);
				if (url === null) return null;
				break;
			case "collection":
				if (!item.reference_collection) return null;
				if (item.reference_id) {
					url = await resolveContentUrl(item.reference_collection, item.reference_id, db, urlPatterns, locale);
					if (url === null) return null;
				} else url = `/${item.reference_collection}/`;
				break;
			default: if (item.reference_collection && item.reference_id) {
				url = await resolveContentUrl(item.reference_collection, item.reference_id, db, urlPatterns, locale);
				if (url === null) return null;
			} else url = "#";
		}
	} catch (error) {
		console.error(`Failed to resolve menu item ${item.id}:`, error);
		return null;
	}
	return {
		id: item.id,
		label: item.label,
		url: sanitizeHref(url),
		target: item.target || void 0,
		titleAttr: item.title_attr || void 0,
		cssClasses: item.css_classes || void 0,
		children: []
	};
}
const SLUG_PLACEHOLDER = /\{slug\}/g;
const ID_PLACEHOLDER = /\{id\}/g;
/**
* Interpolate a URL pattern with entry data
*
* Replaces `{slug}` and `{id}` placeholders.
*/
function interpolateUrlPattern(pattern, slug, id) {
	return pattern.replace(SLUG_PLACEHOLDER, slug).replace(ID_PLACEHOLDER, id);
}
/**
* Resolve the URL for a content reference. `referenceGroup` is the content
* row's translation_group; we look up the row in the requested locale
* (falling back to the source if no translation exists so the menu link is
* still clickable).
*/
async function resolveContentUrl(collection, referenceGroup, db, urlPatterns, locale) {
	if (!referenceGroup) return null;
	try {
		validateIdentifier(collection, "menu item collection");
		let result = await sql`
			SELECT id, slug FROM ${sql.ref(`ec_${collection}`)}
			WHERE translation_group = ${referenceGroup} AND locale = ${locale}
			LIMIT 1
		`.execute(db);
		let row = result.rows[0];
		if (!row) {
			result = await sql`
				SELECT id, slug FROM ${sql.ref(`ec_${collection}`)}
				WHERE translation_group = ${referenceGroup}
				ORDER BY locale ASC LIMIT 1
			`.execute(db);
			row = result.rows[0];
		}
		if (!row) row = (await sql`
				SELECT id, slug FROM ${sql.ref(`ec_${collection}`)}
				WHERE id = ${referenceGroup} LIMIT 1
			`.execute(db)).rows[0];
		if (!row) return null;
		const pattern = urlPatterns.get(collection);
		if (pattern) return interpolateUrlPattern(pattern, row.slug, row.id);
		return `/${collection}/${row.slug}`;
	} catch (error) {
		console.error(`Failed to resolve content URL for ${collection}/${referenceGroup}:`, error);
		return null;
	}
}
/**
* Resolve URL for a taxonomy term reference. `referenceGroup` is the term's
* translation_group; we pick the row in the active locale (or fall back).
*/
async function resolveTaxonomyUrl(referenceGroup, db, locale) {
	if (!referenceGroup) return null;
	let taxonomy = await db.selectFrom("taxonomies").select(["name", "slug"]).where("translation_group", "=", referenceGroup).where("locale", "=", locale).executeTakeFirst();
	if (!taxonomy) taxonomy = await db.selectFrom("taxonomies").select(["name", "slug"]).where("translation_group", "=", referenceGroup).orderBy("locale", "asc").executeTakeFirst();
	if (!taxonomy) taxonomy = await db.selectFrom("taxonomies").select(["name", "slug"]).where("id", "=", referenceGroup).executeTakeFirst();
	if (!taxonomy) return null;
	return `/${taxonomy.name}/${taxonomy.slug}`;
}

//#endregion
export { file as C, reference as S, resolveExclusiveHooks as _, SandboxUnavailableError as a, prosemirrorToPortableText as b, createNoopSandboxRunner as c, createPluginManager as d, PluginRouteError as f, createHookPipeline as g, HookPipeline as h, getComments as i, NodeCronScheduler as l, EmailPipeline as m, getMenus as n, NoopSandboxRunner as o, PluginRouteRegistry as p, getCommentCount as r, SandboxNotAvailableError as s, getMenu as t, PluginManager as u, definePlugin as v, image as w, portableText as x, portableTextToProsemirror as y };
//# sourceMappingURL=menus-CsZ2ZEK2.mjs.map