globalThis.process ??= {};
globalThis.process.env ??= {};
import { r as __exportAll } from "./rolldown-runtime_-UtK6b3T.mjs";
import { c as isEntityId, l as jsonError, u as jsonOk } from "./crypto_CY2zBtG3.mjs";
import { c as assertCsrf, i as requireAdmin } from "./auth_B0DWM0G6.mjs";
import { a as saveContentModelEditor, i as restoreContentModelEditor, o as transitionContentModelEditor, r as loadContentModelEditorSnapshot, t as ContentModelEditorError } from "./content-model-editor_A7KaA6-n.mjs";
import { env } from "cloudflare:workers";
//#region src/pages/api/admin/content-model/editor.ts
var editor_exports = /* @__PURE__ */ __exportAll({
	GET: () => GET,
	POST: () => POST,
	prerender: () => false
});
function objectBody(value) {
	if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ContentModelEditorError("validation", "request body must be an object");
	return value;
}
function bounded(value, field, max = 4096) {
	if (typeof value !== "string" || value.length < 1 || value.length > max) throw new ContentModelEditorError("validation", `${field} must be a bounded string`);
	return value;
}
function id(value) {
	if (!isEntityId(value)) throw new ContentModelEditorError("validation", "id must be a valid UUID");
	return value;
}
function adminPrincipal(actorId, sessionId) {
	return Object.freeze({
		userId: actorId,
		sessionId,
		roles: ["admin"]
	});
}
function optionalDate(value, field) {
	if (value === void 0) return void 0;
	return bounded(value, field, 128);
}
function patch(value) {
	if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ContentModelEditorError("validation", "patch must be an object");
	return value;
}
function mapEditorError(error) {
	const name = error.name, code = error.code;
	if (name === "CsrfError" || name === "RoleDeniedError") return jsonError(403, "forbidden", "editor operation unavailable");
	if (name === "InvalidSessionError") return jsonError(401, "unauthorized", "editor operation unavailable");
	if (name === "RateLimitedError") return jsonError(429, "rate_limited", "editor operation unavailable");
	if (error instanceof ContentModelEditorError) {
		if (error.code === "access-denied") return jsonError(404, "editor_unavailable", "editor operation unavailable");
		if (error.code === "stale-version") return jsonError(409, "stale_version", "content changed since the editor snapshot");
		if (error.code === "unsupported-capability") return jsonError(409, "unsupported_capability", error.message);
		if (error.code === "integrity") return jsonError(409, "integrity_conflict", "editor operation conflicted");
		return jsonError(400, "validation_error", error.message);
	}
	if (name === "ContentLifecycleError") {
		if (code === "access-denied" || code === "not-found") return jsonError(404, "editor_unavailable", "editor operation unavailable");
		if (code === "stale-version" || code === "operation-conflict") return jsonError(409, "conflict", "editor operation conflicted");
		if (code === "capability-unavailable") return jsonError(409, "unsupported_capability", "editor operation unavailable");
		return jsonError(400, "validation_error", error instanceof Error ? error.message : "invalid editor operation");
	}
	if (name === "FieldsLifecycleError") {
		if (code === "not-found" || code === "access-denied") return jsonError(404, "editor_unavailable", "editor operation unavailable");
		if (code === "stale-version" || code === "operation-conflict" || code === "corpus-drift") return jsonError(409, "conflict", "editor operation conflicted");
		if (code === "capability-unavailable") return jsonError(409, "unsupported_capability", "editor operation unavailable");
		return jsonError(400, "validation_error", error instanceof Error ? error.message : "invalid editor operation");
	}
	console.error("content model editor route failed", error);
	return jsonError(500, "internal_error", "internal error");
}
var GET = async ({ request, url, cookies }) => {
	try {
		const auth = await requireAdmin(request, env, cookies), entryId = id(url.searchParams.get("id")), principal = adminPrincipal(auth.actor.id, auth.sessionId);
		return jsonOk(await loadContentModelEditorSnapshot(env, principal, entryId));
	} catch (error) {
		return mapEditorError(error);
	}
};
var POST = async ({ request, cookies }) => {
	try {
		const auth = await requireAdmin(request, env, cookies);
		assertCsrf(request, {
			authMode: auth.authMode,
			siteOrigin: env.SITE_ORIGIN
		});
		const body = objectBody(await request.json()), action = bounded(body.action, "action", 64), entryId = id(body.id), principal = adminPrincipal(auth.actor.id, auth.sessionId), operationId = bounded(body.operationId, "operationId", 180), expectedUpdatedAt = bounded(body.expectedUpdatedAt, "expectedUpdatedAt", 128);
		if (action === "save") return jsonOk(await saveContentModelEditor(env, principal, entryId, {
			expectedUpdatedAt,
			operationId,
			patch: patch(body.patch),
			...body.fieldValues === void 0 ? {} : { fieldValues: objectBody(body.fieldValues) },
			...body.blockDocument === void 0 ? {} : { blockDocument: body.blockDocument },
			...body.expectedBlockVersion === void 0 ? {} : { expectedBlockVersion: bounded(body.expectedBlockVersion, "expectedBlockVersion", 256) },
			...body.expectedFieldsVersion === void 0 ? {} : { expectedFieldsVersion: bounded(body.expectedFieldsVersion, "expectedFieldsVersion", 128) }
		}));
		if (action === "restore") return jsonOk(await restoreContentModelEditor(env, principal, entryId, {
			expectedUpdatedAt,
			expectedFieldsVersion: bounded(body.expectedFieldsVersion, "expectedFieldsVersion", 128),
			operationId,
			contentRevisionId: id(body.contentRevisionId),
			fieldsRevisionId: id(body.fieldsRevisionId)
		}));
		if (action === "transition") return jsonOk(await transitionContentModelEditor(env, principal, entryId, {
			expectedUpdatedAt,
			expectedFieldsVersion: bounded(body.expectedFieldsVersion, "expectedFieldsVersion", 128),
			operationId,
			to: bounded(body.to, "to", 128),
			...optionalDate(body.scheduleAt, "scheduleAt") ? { scheduleAt: optionalDate(body.scheduleAt, "scheduleAt") } : {},
			...optionalDate(body.publishedAt, "publishedAt") ? { publishedAt: optionalDate(body.publishedAt, "publishedAt") } : {}
		}));
		throw new ContentModelEditorError("validation", `unsupported action ${action}`);
	} catch (error) {
		return mapEditorError(error);
	}
};
//#endregion
//#region \0virtual:astro:page:src/pages/api/admin/content-model/editor@_@ts
var page = () => editor_exports;
//#endregion
export { page };
