globalThis.process ??= {};
globalThis.process.env ??= {};
import { r as __exportAll } from "./rolldown-runtime_-UtK6b3T.mjs";
import { l as jsonError, u as jsonOk } from "./crypto_CY2zBtG3.mjs";
import { T as previewContentTypeChange, c as createContentStatus, j as restoreContentBackup, l as createContentType, n as applyContentTypeChange, t as applyContentStatusChange, w as previewContentStatusChange } from "./dist_TEPdmzZw.mjs";
import { M as previewFieldBlockChange, N as previewOptionsPageDeactivation, Y as applyFieldGroupChange, Z as createFieldGroup, a as applyOptionsPageDeactivation, i as applyFieldBlockChange, ot as previewFieldGroupChange, p as createOptionsPage, q as updateOptionsPage, u as createFieldBlock, ut as restoreFieldsBackup } from "./dist_C9SfSFSK.mjs";
import { c as assertCsrf, i as requireAdmin } from "./auth_B0DWM0G6.mjs";
import { a as contentModelAdminFieldsDestructiveEffects, c as contentModelContentBackupStore, d as createFieldsDefinitionBackup, f as listContentModelAdminDefinitions, i as contentModelAdminFieldsContext, l as contentModelFieldsBackupStore, m as runContentModelAdminMutation, n as contentModelAdminAuthorization, o as contentModelAdminOptionsFieldsContext, p as previewContentModelDefinitionBackupRestore, r as contentModelAdminContentEffects, s as contentModelAdminPrincipal, t as ContentModelAdminError, u as createContentTypeDefinitionBackup } from "./content-model-admin_B6uak5yI.mjs";
import { env } from "cloudflare:workers";
//#region src/pages/api/admin/content-model/definitions.ts
var definitions_exports = /* @__PURE__ */ __exportAll({
	GET: () => GET,
	POST: () => POST,
	prerender: () => false
});
function objectBody(value) {
	if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ContentModelAdminError("validation", "request body must be an object");
	return value;
}
function string(value, field, max = 4096) {
	if (typeof value !== "string" || value.length < 1 || value.length > max) throw new ContentModelAdminError("validation", `${field} must be a bounded string`);
	return value;
}
function integer(value, field) {
	if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new ContentModelAdminError("validation", `${field} must be a positive integer`);
	return value;
}
function operationId(body) {
	return string(body.operationId, "operationId", 256);
}
function proposedOptionsManageCapability(definition) {
	if (typeof definition !== "object" || definition === null || Array.isArray(definition)) return [];
	const capability = definition.manageCapability;
	return typeof capability === "string" && capability.length > 0 && capability.length <= 256 ? [capability] : [];
}
function mapDefinitionAdminError(error) {
	const name = error.name;
	const code = error.code;
	if (name === "CsrfError" || name === "RoleDeniedError") return jsonError(403, "forbidden", "definition operation unavailable");
	if (name === "InvalidSessionError") return jsonError(401, "unauthorized", "definition operation unavailable");
	if (error instanceof ContentModelAdminError) {
		if (error.code === "unsupported-capability") return jsonError(409, "unsupported_capability", error.message);
		if (error.code === "backup-invalid") return jsonError(409, "backup_invalid", "definition operation unavailable");
		return jsonError(400, "validation_error", error.message);
	}
	if (name === "ContentDefinitionError") {
		if (code === "definition-not-found" || code === "code-definition-owned") return jsonError(404, "definition_unavailable", "definition operation unavailable");
		if (code === "definition-conflict" || code === "stale-definition" || code === "stale-impact" || code === "authorization-drift" || code === "strategy-conflict" || code === "operation-conflict") return jsonError(409, "conflict", "definition operation conflicted");
		return jsonError(400, "validation_error", error instanceof Error ? error.message : "invalid definition operation");
	}
	if (name === "FieldsLifecycleError") {
		const detail = error.detail;
		const codeOwned = code === "validation" && typeof detail === "string" && (detail.includes("code-owned") || detail.includes("owned by code") || detail.includes("registry reconciliation"));
		if (code === "not-found" || code === "access-denied" || codeOwned) return jsonError(404, "definition_unavailable", "definition operation unavailable");
		if (code === "stale-version" || code === "corpus-drift" || code === "operation-conflict" || code === "backup-invalid") return jsonError(409, "conflict", error instanceof Error ? error.message : "definition operation conflicted");
		return jsonError(400, "validation_error", error instanceof Error ? error.message : "invalid definition operation");
	}
	console.error("content model definition admin failed", error);
	return jsonError(500, "internal_error", "internal error");
}
var GET = async ({ request, cookies }) => {
	try {
		await requireAdmin(request, env, cookies);
		return jsonOk(await listContentModelAdminDefinitions(env));
	} catch (error) {
		return mapDefinitionAdminError(error);
	}
};
var POST = async ({ request, cookies }) => {
	try {
		const { actor, authMode } = await requireAdmin(request, env, cookies);
		assertCsrf(request, {
			authMode,
			siteOrigin: env.SITE_ORIGIN
		});
		const body = objectBody(await request.json());
		const action = string(body.action, "action", 128);
		const principal = contentModelAdminPrincipal(actor.id);
		const fieldsContext = contentModelAdminFieldsContext(actor.id);
		const result = await runContentModelAdminMutation(env, async (tx) => {
			switch (action) {
				case "createContentType": return createContentType(tx, principal, {
					definition: body.definition,
					operationId: operationId(body)
				}, contentModelAdminAuthorization, contentModelAdminContentEffects);
				case "createContentStatus": return createContentStatus(tx, principal, {
					definition: body.definition,
					operationId: operationId(body)
				}, contentModelAdminAuthorization, contentModelAdminContentEffects);
				case "previewContentType": {
					const strategies = (body.strategies ?? []).map((strategy) => strategy.kind === "purgeFeatureData" && !strategy.backupId ? Object.freeze({
						...strategy,
						backupId: crypto.randomUUID()
					}) : strategy);
					const impact = await previewContentTypeChange(tx, principal, {
						key: string(body.key, "key", 128),
						expectedVersion: integer(body.expectedVersion, "expectedVersion"),
						patch: body.patch,
						deactivate: body.deactivate === true,
						delete: body.delete === true,
						strategies
					}, contentModelAdminAuthorization);
					const backups = [];
					for (const strategy of strategies) if (strategy.kind === "purgeFeatureData") backups.push(await createContentTypeDefinitionBackup(tx, impact, strategy));
					return Object.freeze({
						impact,
						strategies: Object.freeze(strategies),
						backups: Object.freeze(backups)
					});
				}
				case "applyContentType": return applyContentTypeChange(tx, principal, {
					impactToken: string(body.impactToken, "impactToken", 64e3),
					operationId: operationId(body),
					strategies: body.strategies ?? []
				}, contentModelAdminAuthorization, contentModelAdminContentEffects, { destructive: { backups: contentModelContentBackupStore } });
				case "previewContentStatus": return previewContentStatusChange(tx, principal, {
					key: string(body.key, "key", 128),
					expectedVersion: integer(body.expectedVersion, "expectedVersion"),
					patch: body.patch,
					deactivate: body.deactivate === true,
					delete: body.delete === true,
					strategy: body.strategy
				}, contentModelAdminAuthorization);
				case "applyContentStatus": return applyContentStatusChange(tx, principal, {
					impactToken: string(body.impactToken, "impactToken", 64e3),
					operationId: operationId(body),
					strategy: body.strategy
				}, contentModelAdminAuthorization, contentModelAdminContentEffects);
				case "createFieldGroup": return createFieldGroup(tx, body.definition, fieldsContext, { operationId: operationId(body) });
				case "previewFieldGroup": {
					const raw = body.strategy;
					const strategy = raw?.kind === "purgeValues" && !raw.backupId ? Object.freeze({
						...raw,
						backupId: crypto.randomUUID()
					}) : raw;
					const impact = await previewFieldGroupChange(tx, string(body.key, "key", 128), integer(body.expectedVersion, "expectedVersion"), body.patch ?? {}, strategy, fieldsContext);
					const backup = strategy?.kind === "purgeValues" ? await createFieldsDefinitionBackup(tx, fieldsContext, {
						kind: "group",
						impact,
						strategy
					}) : null;
					return Object.freeze({
						impact,
						strategy,
						backup
					});
				}
				case "applyFieldGroup": return applyFieldGroupChange(tx, string(body.impactToken, "impactToken", 64e3), body.strategy, operationId(body), fieldsContext, {
					backups: contentModelFieldsBackupStore,
					effects: contentModelAdminFieldsDestructiveEffects
				});
				case "createOptionsPage": {
					const definition = body.definition;
					const optionsContext = contentModelAdminFieldsContext(actor.id, proposedOptionsManageCapability(body.definition));
					return createOptionsPage(tx, definition, optionsContext, { operationId: operationId(body) });
				}
				case "updateOptionsPage": {
					const key = string(body.key, "key", 128);
					const optionsContext = await contentModelAdminOptionsFieldsContext(tx, actor.id, key);
					return updateOptionsPage(tx, key, body.patch ?? {}, integer(body.expectedVersion, "expectedVersion"), optionsContext, { operationId: operationId(body) });
				}
				case "previewOptionsDeactivate": {
					const key = string(body.key, "key", 128);
					const optionsContext = await contentModelAdminOptionsFieldsContext(tx, actor.id, key);
					const impact = await previewOptionsPageDeactivation(tx, key, integer(body.expectedVersion, "expectedVersion"), optionsContext);
					if (body.preparePurge !== true) return Object.freeze({
						impact,
						strategy: Object.freeze({ kind: "retain" }),
						backup: null
					});
					const strategy = Object.freeze({
						kind: "purge",
						backupId: crypto.randomUUID()
					});
					const backup = await createFieldsDefinitionBackup(tx, fieldsContext, {
						kind: "optionsPage",
						impact,
						strategy
					});
					return Object.freeze({
						impact,
						strategy,
						backup
					});
				}
				case "applyOptionsDeactivate": {
					const key = string(body.key, "key", 128);
					const optionsContext = await contentModelAdminOptionsFieldsContext(tx, actor.id, key);
					return applyOptionsPageDeactivation(tx, string(body.impactToken, "impactToken", 64e3), body.strategy, operationId(body), optionsContext, {
						backups: contentModelFieldsBackupStore,
						effects: contentModelAdminFieldsDestructiveEffects
					});
				}
				case "createBlock": return createFieldBlock(tx, body.definition, fieldsContext, { operationId: operationId(body) });
				case "previewBlock": {
					const raw = body.strategy;
					const strategy = raw?.kind === "purgeWithBackup" && !raw.backupId ? Object.freeze({
						...raw,
						backupId: crypto.randomUUID()
					}) : raw;
					const impact = await previewFieldBlockChange(tx, fieldsContext, {
						key: string(body.key, "key", 128),
						expectedVersion: integer(body.expectedVersion, "expectedVersion"),
						patch: body.patch,
						deactivate: body.deactivate === true,
						delete: body.delete === true,
						strategy
					});
					const backup = strategy?.kind === "purgeWithBackup" ? await createFieldsDefinitionBackup(tx, fieldsContext, {
						kind: "block",
						impact,
						strategy
					}) : null;
					return Object.freeze({
						impact,
						strategy,
						backup
					});
				}
				case "applyBlock": return applyFieldBlockChange(tx, fieldsContext, {
					impactToken: string(body.impactToken, "impactToken", 64e3),
					operationId: operationId(body),
					strategy: body.strategy
				}, { destructive: {
					backups: contentModelFieldsBackupStore,
					effects: contentModelAdminFieldsDestructiveEffects
				} });
				case "previewBackupRestore": {
					const kind = string(body.kind, "kind", 16);
					if (kind !== "content" && kind !== "fields") throw new ContentModelAdminError("validation", "kind must be content or fields");
					return previewContentModelDefinitionBackupRestore(tx, kind, body.manifest);
				}
				case "restoreContentBackup": return restoreContentBackup(tx, principal, {
					manifest: body.manifest,
					destinationCorpusHash: string(body.destinationCorpusHash, "destinationCorpusHash", 128),
					operationId: operationId(body)
				}, contentModelAdminAuthorization, contentModelAdminContentEffects, { backups: contentModelContentBackupStore });
				case "restoreFieldsBackup": return restoreFieldsBackup(tx, body.manifest, string(body.destinationCorpusHash, "destinationCorpusHash", 128), operationId(body), fieldsContext, contentModelAdminFieldsDestructiveEffects, contentModelFieldsBackupStore);
				default: throw new ContentModelAdminError("validation", `unsupported action ${action}`);
			}
		});
		return jsonOk(result);
	} catch (error) {
		return mapDefinitionAdminError(error);
	}
};
//#endregion
//#region \0virtual:astro:page:src/pages/api/admin/content-model/definitions@_@ts
var page = () => definitions_exports;
//#endregion
export { page };
