globalThis.process ??= {};
globalThis.process.env ??= {};
import { Tt as sql } from "./d1_DTqC4o_t.mjs";
import { A as resolveContentTypes, O as resolveContentStatuses, a as contentBackupDestinationHash, r as canonicalContentMigrationHash } from "./dist_YU938xCs.mjs";
import { n as getFullDb, r as getMutationDb } from "./db_BQ9NAt8x.mjs";
import { B as resolveOptionsPages, R as resolveFieldBlocks, nt as fieldsBackupDestinationHash, pt as canonicalFieldsMigrationHash, ut as resolveFinalFieldGroups, v as exportFields } from "./dist_BBLvfyU8.mjs";
//#region src/lib/content-model-admin.ts
var CONTENT_MODEL_ADMIN_POLICY_VERSION = "mod-cms-admin-definitions-v1";
var ContentModelAdminError = class extends Error {
	code;
	detail;
	name = "ContentModelAdminError";
	constructor(code, detail) {
		super(`content model admin ${code}: ${detail}`);
		this.code = code;
		this.detail = detail;
	}
};
function rowsOf(value) {
	if (Array.isArray(value)) return value;
	const rows = value?.rows;
	if (Array.isArray(rows)) return rows;
	throw new ContentModelAdminError("validation", "database returned an invalid row envelope");
}
function record(value, field) {
	const parsed = typeof value === "string" ? (() => {
		try {
			return JSON.parse(value);
		} catch {
			return value;
		}
	})() : value;
	if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ContentModelAdminError("backup-invalid", `${field} is malformed`);
	return parsed;
}
function counts(value) {
	const input = record(value, "backup.itemCounts");
	const output = {};
	for (const [key, raw] of Object.entries(input)) {
		const number = Number(raw);
		if (!Number.isSafeInteger(number) || number < 0) throw new ContentModelAdminError("backup-invalid", "backup item counts are malformed");
		output[key] = number;
	}
	return Object.freeze(output);
}
function sameCounts(left, right) {
	return JSON.stringify(Object.entries(left).sort()) === JSON.stringify(Object.entries(right).sort());
}
var CONTENT_MODEL_ADMIN_CONTENT_CAPABILITY = "content.manage";
var CONTENT_MODEL_ADMIN_FIELDS_CAPABILITY = "fields.manage";
var CONTENT_MODEL_ADMIN_CONTENT_CAPABILITIES = /* @__PURE__ */ new Set([CONTENT_MODEL_ADMIN_CONTENT_CAPABILITY]);
var CONTENT_MODEL_ADMIN_FIELDS_CAPABILITIES = /* @__PURE__ */ new Set([CONTENT_MODEL_ADMIN_FIELDS_CAPABILITY]);
function assertAdminCapability(principal, capability) {
	if (!principal.id || !principal.capabilities.has(capability)) throw new ContentModelAdminError("validation", "admin principal is unavailable");
}
function contentModelAdminPrincipal(userId) {
	if (!userId) throw new ContentModelAdminError("validation", "admin principal id is required");
	return Object.freeze({
		id: userId,
		capabilities: CONTENT_MODEL_ADMIN_CONTENT_CAPABILITIES,
		system: false
	});
}
function adminFieldCapability(value) {
	if (!value || value.length > 256) throw new ContentModelAdminError("validation", "admin field capability must be a bounded string");
	return value;
}
function contentModelAdminFieldsContext(userId, extraCapabilities = []) {
	if (!userId) throw new ContentModelAdminError("validation", "admin principal id is required");
	const capabilities = new Set(CONTENT_MODEL_ADMIN_FIELDS_CAPABILITIES);
	for (const capability of extraCapabilities) capabilities.add(adminFieldCapability(capability));
	const principal = Object.freeze({
		id: userId,
		capabilities
	});
	const authorization = Object.freeze({
		assert: (candidate, _action) => assertAdminCapability(candidate, CONTENT_MODEL_ADMIN_FIELDS_CAPABILITY),
		assertDefinitionMigration: (candidate) => {
			assertAdminCapability(candidate, CONTENT_MODEL_ADMIN_FIELDS_CAPABILITY);
			return Object.freeze({ policyVersion: CONTENT_MODEL_ADMIN_POLICY_VERSION });
		}
	});
	return Object.freeze({
		principal,
		authorization
	});
}
async function contentModelAdminOptionsFieldsContext(tx, userId, key) {
	const normalizedKey = key.trim();
	if (!normalizedKey || normalizedKey.length > 128) throw new ContentModelAdminError("validation", "options page key must be a bounded string");
	const page = (await resolveOptionsPages(tx)).find((candidate) => candidate.key === normalizedKey);
	return contentModelAdminFieldsContext(userId, page ? [page.manageCapability] : []);
}
var contentModelAdminAuthorization = Object.freeze({ assert: async (_tx, principal) => {
	assertAdminCapability(principal, CONTENT_MODEL_ADMIN_CONTENT_CAPABILITY);
	return Object.freeze({ policyVersion: CONTENT_MODEL_ADMIN_POLICY_VERSION });
} });
async function appendAdminEvent(tx, channel, event) {
	const row = record(event, "event");
	const kind = typeof row.kind === "string" && row.kind ? row.kind : "definition-event";
	const entityType = typeof row.definitionKind === "string" ? `content-model:${row.definitionKind}` : "content-model:definitions";
	const entityId = typeof row.definitionKey === "string" ? row.definitionKey : typeof row.manifestId === "string" ? row.manifestId : typeof row.id === "string" ? row.id : kind;
	if (channel === "audit") {
		const actorId = typeof row.principalId === "string" ? row.principalId : null;
		await tx.execute(sql`INSERT INTO audit_log (id,actor_id,actor_type,actor_label,action,entity_type,entity_id,metadata,ip,tenant_id,created_at)
      VALUES (${crypto.randomUUID()},${actorId},'admin',NULL,${`content-model.${kind}`},${entityType},${entityId},${JSON.stringify(row)},NULL,NULL,${(/* @__PURE__ */ new Date()).toISOString()})`);
		return;
	}
	await tx.execute(sql`INSERT INTO content_model_admin_outbox (id,kind,payload,created_at)
    VALUES (${crypto.randomUUID()},${kind},${JSON.stringify(row)},${(/* @__PURE__ */ new Date()).toISOString()})`);
}
var contentModelAdminContentEffects = Object.freeze({
	audit: Object.freeze({ record: (tx, event) => appendAdminEvent(tx, "audit", event) }),
	outbox: Object.freeze({ enqueue: (tx, event) => appendAdminEvent(tx, "outbox", event) })
});
Object.freeze({
	audit: (tx, event) => appendAdminEvent(tx, "audit", event),
	enqueue: (tx, event) => appendAdminEvent(tx, "outbox", event)
});
var contentModelAdminFieldsDestructiveEffects = Object.freeze({
	audit: Object.freeze({ record: (tx, event) => appendAdminEvent(tx, "audit", event) }),
	outbox: Object.freeze({ enqueue: (tx, event) => appendAdminEvent(tx, "outbox", event) })
});
async function readBackup(tx, id) {
	return rowsOf(await tx.execute(sql`SELECT id,kind,scope_hash AS "scopeHash",corpus_version AS "corpusVersion",corpus_hash AS "corpusHash",item_counts AS "itemCounts",byte_count AS "byteCount",payload_hash AS "payloadHash",payload,created_at AS "createdAt" FROM content_model_definition_backups WHERE id=${id} LIMIT 1`))[0] ?? null;
}
async function backupPayloadHash(kind, payload) {
	return kind === "content" ? canonicalContentMigrationHash(payload) : canonicalFieldsMigrationHash(payload);
}
async function assertStoredPayloadIdentity(row) {
	if (!row.payloadHash || await backupPayloadHash(row.kind, jsonValue(row.payload)) !== row.payloadHash) throw new ContentModelAdminError("backup-invalid", "backup payload identity does not match immutable storage");
}
function manifestFromRow(row) {
	const byteCount = Number(row.byteCount);
	if (!Number.isSafeInteger(byteCount) || byteCount < 0) throw new ContentModelAdminError("backup-invalid", "backup byte count is malformed");
	return Object.freeze({
		id: row.id,
		scopeHash: row.scopeHash,
		corpusVersion: row.corpusVersion,
		corpusHash: row.corpusHash,
		itemCounts: counts(row.itemCounts),
		byteCount,
		immutable: true
	});
}
async function persistContentModelDefinitionBackup(tx, input) {
	const id = input.id ?? crypto.randomUUID();
	const serialized = JSON.stringify(input.payload);
	const byteCount = new TextEncoder().encode(serialized).byteLength;
	const payloadHash = await backupPayloadHash(input.kind, input.payload);
	await tx.execute(sql`INSERT INTO content_model_definition_backups (id,kind,scope_hash,corpus_version,corpus_hash,item_counts,byte_count,payload_hash,payload,created_at)
    VALUES (${id},${input.kind},${input.scopeHash},${input.corpusVersion},${input.corpusHash},${JSON.stringify(input.itemCounts)},${byteCount},${payloadHash},${serialized},${(/* @__PURE__ */ new Date()).toISOString()})`);
	return Object.freeze({
		id,
		scopeHash: input.scopeHash,
		corpusVersion: input.corpusVersion,
		corpusHash: input.corpusHash,
		itemCounts: Object.freeze({ ...input.itemCounts }),
		byteCount,
		immutable: true
	});
}
async function verifyStoredBackup(tx, kind, backupId, scopeHash, corpusVersion, corpusHash, expectedCounts) {
	const row = await readBackup(tx, backupId);
	if (!row || row.kind !== kind) throw new ContentModelAdminError("backup-invalid", "backup is unavailable");
	await assertStoredPayloadIdentity(row);
	const manifest = manifestFromRow(row);
	if (manifest.scopeHash !== scopeHash || manifest.corpusVersion !== corpusVersion || manifest.corpusHash !== corpusHash || !sameCounts(manifest.itemCounts, expectedCounts)) throw new ContentModelAdminError("backup-invalid", "backup identity does not match the requested destructive scope");
	return manifest;
}
async function readStoredBackup(tx, kind, manifest) {
	const row = await readBackup(tx, manifest.id);
	if (!row || row.kind !== kind) throw new ContentModelAdminError("backup-invalid", "backup is unavailable");
	await assertStoredPayloadIdentity(row);
	const verified = manifestFromRow(row);
	if (verified.scopeHash !== manifest.scopeHash || verified.corpusVersion !== manifest.corpusVersion || verified.corpusHash !== manifest.corpusHash || !sameCounts(verified.itemCounts, manifest.itemCounts)) throw new ContentModelAdminError("backup-invalid", "backup manifest changed identity");
	return {
		manifest: verified,
		payload: typeof row.payload === "string" ? JSON.parse(row.payload) : row.payload
	};
}
var contentModelContentBackupStore = Object.freeze({
	verify(tx, backupId, scopeHash, corpusVersion, corpusHash, expectedCounts) {
		return verifyStoredBackup(tx, "content", backupId, scopeHash, corpusVersion, corpusHash, expectedCounts);
	},
	async read(tx, manifest) {
		const snapshot = await readStoredBackup(tx, "content", manifest);
		return Object.freeze({
			manifest: snapshot.manifest,
			payload: snapshot.payload
		});
	}
});
var contentModelFieldsBackupStore = Object.freeze({
	verify(tx, backupId, scopeHash, corpusVersion, corpusHash, expectedCounts) {
		return verifyStoredBackup(tx, "fields", backupId, scopeHash, corpusVersion, corpusHash, expectedCounts);
	},
	async read(tx, manifest) {
		const snapshot = await readStoredBackup(tx, "fields", manifest);
		return Object.freeze({
			manifest: snapshot.manifest,
			payload: snapshot.payload
		});
	}
});
async function listDefinitionBackups(tx) {
	const rows = rowsOf(await tx.execute(sql`SELECT id,kind,scope_hash AS "scopeHash",corpus_version AS "corpusVersion",corpus_hash AS "corpusHash",item_counts AS "itemCounts",byte_count AS "byteCount",payload_hash AS "payloadHash",payload,created_at AS "createdAt" FROM content_model_definition_backups WHERE kind IN ('content','fields') ORDER BY created_at DESC,id DESC LIMIT 50`));
	return Object.freeze(rows.map((row) => {
		if (row.kind !== "content" && row.kind !== "fields") throw new ContentModelAdminError("backup-invalid", "backup kind is malformed");
		const createdAt = row.createdAt instanceof Date ? row.createdAt.toISOString() : new Date(row.createdAt).toISOString();
		if (Number.isNaN(new Date(createdAt).getTime())) throw new ContentModelAdminError("backup-invalid", "backup createdAt is malformed");
		return Object.freeze({
			kind: row.kind,
			manifest: manifestFromRow(row),
			createdAt
		});
	}));
}
async function previewContentModelDefinitionBackupRestore(tx, kind, manifest) {
	const snapshot = await readStoredBackup(tx, kind, manifest);
	const destinationCorpusHash = kind === "content" ? await contentBackupDestinationHash(tx, snapshot.payload) : await fieldsBackupDestinationHash(tx, snapshot.payload);
	return Object.freeze({
		kind,
		manifest: snapshot.manifest,
		destinationCorpusHash
	});
}
function jsonValue(value) {
	if (typeof value !== "string") return value;
	try {
		return JSON.parse(value);
	} catch {
		return value;
	}
}
function fieldStorage(value, field = "backup") {
	if (value === null || typeof value === "string" || typeof value === "boolean") return value;
	if (typeof value === "number") {
		if (!Number.isFinite(value)) throw new ContentModelAdminError("backup-invalid", `${field} contains a non-finite number`);
		return value;
	}
	if (Array.isArray(value)) return Object.freeze(value.map((item, index) => fieldStorage(item, `${field}.${index}`)));
	if (typeof value === "object") {
		const output = {};
		for (const [key, item] of Object.entries(value)) if (item !== void 0) output[key] = fieldStorage(item, `${field}.${key}`);
		return Object.freeze(output);
	}
	throw new ContentModelAdminError("backup-invalid", `${field} contains a non-serializable value`);
}
function definitionVersions(value) {
	const source = record(jsonValue(value), "definitionVersions");
	const output = {};
	for (const [key, raw] of Object.entries(source)) {
		const revision = Number(raw);
		if (!Number.isSafeInteger(revision) || revision < 1) throw new ContentModelAdminError("backup-invalid", "definition version map is malformed");
		output[key] = revision;
	}
	return Object.freeze(output);
}
function documentContains(value, predicate) {
	const parsed = jsonValue(value);
	if (Array.isArray(parsed)) return parsed.some((item) => documentContains(item, predicate));
	if (typeof parsed !== "object" || parsed === null) return false;
	const object = parsed;
	if (predicate(object)) return true;
	return Object.values(object).some((item) => documentContains(item, predicate));
}
function containsGroup(value, key) {
	return documentContains(value, (row) => row.groupKey === key);
}
function containsBlock(value, key) {
	return documentContains(value, (row) => row.kind === "inline" && row.type === key);
}
function versionReferences(value, key) {
	const versions = definitionVersions(value);
	return versions[key] !== void 0 || versions[`group:${key}`] !== void 0 || versions[`block:${key}`] !== void 0;
}
function entityRef(entityType, entityId) {
	if (typeof entityType !== "string" || !entityType || typeof entityId !== "string" || !entityId) throw new ContentModelAdminError("backup-invalid", "backup entity reference is malformed");
	return Object.freeze({
		entityType,
		entityId
	});
}
function uniqueRefs(refs) {
	const map = new Map(refs.map((ref) => [`${ref.entityType}\u0000${ref.entityId}`, ref]));
	return Object.freeze([...map.values()].sort((a, b) => a.entityType.localeCompare(b.entityType) || a.entityId.localeCompare(b.entityId)));
}
async function fieldBackupReferenceRows(tx) {
	return {
		documents: rowsOf(await tx.execute(sql`SELECT entity_type AS "entityType",entity_id AS "entityId",document,definition_versions AS "definitionVersions",parent_revision_id AS "parentRevisionId" FROM field_block_documents ORDER BY entity_type,entity_id`)),
		reusables: rowsOf(await tx.execute(sql`SELECT id,document,definition_versions AS "definitionVersions" FROM field_reusable_blocks WHERE deleted_at IS NULL ORDER BY id`)),
		revisions: rowsOf(await tx.execute(sql`SELECT id,entity_type AS "entityType",entity_id AS "entityId",definition_versions AS "definitionVersions",block_document AS "blockDocument" FROM field_revisions ORDER BY created_at,id`))
	};
}
async function buildFieldsBackupPayload(tx, input, context) {
	const refs = [];
	const referenceRows = await fieldBackupReferenceRows(tx);
	if (input.definitionKind === "group") {
		const valueRefs = rowsOf(await tx.execute(sql`SELECT DISTINCT entity_type AS "entityType",entity_id AS "entityId" FROM field_value_nodes WHERE group_key=${input.definitionKey} ORDER BY entity_type,entity_id`));
		refs.push(...valueRefs.map((row) => entityRef(row.entityType, row.entityId)));
		for (const row of referenceRows.revisions) if (versionReferences(row.definitionVersions, input.definitionKey)) refs.push(entityRef(row.entityType, row.entityId));
		for (const row of referenceRows.documents) if (containsGroup(row.document, input.definitionKey)) refs.push(entityRef(row.entityType, row.entityId));
	} else if (input.definitionKind === "optionsPage") refs.push(Object.freeze({
		entityType: "options",
		entityId: input.definitionKey
	}));
	else {
		for (const row of referenceRows.revisions) if (containsBlock(row.blockDocument, input.definitionKey)) refs.push(entityRef(row.entityType, row.entityId));
		for (const row of referenceRows.documents) if (containsBlock(row.document, input.definitionKey)) refs.push(entityRef(row.entityType, row.entityId));
	}
	const selection = uniqueRefs(refs);
	const manifest = await exportFields(tx, {
		...input.definitionKind === "group" ? { groups: [input.definitionKey] } : {},
		entities: selection,
		includeRevisions: true,
		includeOptions: input.definitionKind === "optionsPage",
		includeBlocks: input.definitionKind === "block"
	}, context);
	if (manifest.omissions.length > 0) throw new ContentModelAdminError("backup-invalid", "destructive backup contains sensitive or unauthorized omissions");
	if (input.definitionKind === "group") {
		const definition = manifest.definitions.groups.find((group) => group.key === input.definitionKey);
		if (!definition) throw new ContentModelAdminError("backup-invalid", "field group definition is unavailable");
		const values = (manifest.entities ?? []).flatMap((item) => {
			const value = item.values[input.definitionKey], revision = item.definitionVersions[input.definitionKey];
			return value === void 0 || revision === void 0 ? [] : [Object.freeze({
				ref: item.sourceRef,
				groupKey: input.definitionKey,
				definitionRevision: revision,
				values: fieldStorage(value, `values.${input.definitionKey}`)
			})];
		});
		const revisions = (manifest.revisions ?? []).filter((item) => item.definitionVersions[input.definitionKey] !== void 0 || item.definitionVersions[`group:${input.definitionKey}`] !== void 0).map((item) => Object.freeze({
			id: item.sourceRevisionKey,
			ref: item.sourceRef,
			parentRevisionId: item.parentRevisionKey,
			kind: "revision",
			definitionVersions: item.definitionVersions,
			values: fieldStorage(item.values, "revision.values"),
			...item.blockDocument ? { blockDocument: fieldStorage(item.blockDocument, "revision.blockDocument") } : {},
			createdAt: item.createdAt,
			createdBy: item.createdBySourceId,
			sourceVersion: String(item.sourceVersion)
		}));
		const blockDocuments = referenceRows.documents.filter((row) => containsGroup(row.document, input.definitionKey)).map((row) => Object.freeze({
			ref: entityRef(row.entityType, row.entityId),
			document: jsonValue(row.document),
			definitionVersions: definitionVersions(row.definitionVersions),
			parentRevisionId: row.parentRevisionId
		}));
		const reusableBlocks = referenceRows.reusables.filter((row) => containsGroup(row.document, input.definitionKey)).map((row) => Object.freeze({
			id: row.id,
			document: jsonValue(row.document),
			definitionVersions: definitionVersions(row.definitionVersions)
		}));
		return Object.freeze({
			version: 1,
			groupDefinitions: Object.freeze([{
				key: input.definitionKey,
				definition
			}]),
			values: Object.freeze(values),
			blockDocuments: Object.freeze(blockDocuments),
			reusableBlocks: Object.freeze(reusableBlocks),
			revisions: Object.freeze(revisions)
		});
	}
	if (input.definitionKind === "optionsPage") {
		const definition = manifest.definitions.optionsPages.find((page) => page.key === input.definitionKey);
		if (!definition) throw new ContentModelAdminError("backup-invalid", "options page definition is unavailable");
		const entity = (manifest.entities ?? []).find((item) => item.sourceRef.entityType === "options" && item.sourceRef.entityId === input.definitionKey);
		const values = entity ? Object.entries(entity.values).flatMap(([groupKey, value]) => {
			const revision = entity.definitionVersions[groupKey];
			return revision === void 0 ? [] : [Object.freeze({
				ref: entity.sourceRef,
				groupKey,
				definitionRevision: revision,
				values: fieldStorage(value, `options.${groupKey}`)
			})];
		}) : [];
		const revisions = (manifest.revisions ?? []).filter((item) => item.sourceRef.entityType === "options" && item.sourceRef.entityId === input.definitionKey).map((item) => Object.freeze({
			id: item.sourceRevisionKey,
			ref: item.sourceRef,
			parentRevisionId: item.parentRevisionKey,
			kind: "revision",
			definitionVersions: item.definitionVersions,
			values: fieldStorage(item.values, "revision.values"),
			...item.blockDocument ? { blockDocument: fieldStorage(item.blockDocument, "revision.blockDocument") } : {},
			createdAt: item.createdAt,
			createdBy: item.createdBySourceId,
			sourceVersion: String(item.sourceVersion)
		}));
		return Object.freeze({
			version: 1,
			optionsDefinitions: Object.freeze([{
				key: input.definitionKey,
				definition,
				active: true
			}]),
			values: Object.freeze(values),
			revisions: Object.freeze(revisions)
		});
	}
	const definition = manifest.definitions.blocks.find((block) => block.key === input.definitionKey);
	if (!definition) throw new ContentModelAdminError("backup-invalid", "block definition is unavailable");
	const blockDocuments = referenceRows.documents.filter((row) => containsBlock(row.document, input.definitionKey)).map((row) => Object.freeze({
		ref: entityRef(row.entityType, row.entityId),
		document: jsonValue(row.document),
		definitionVersions: definitionVersions(row.definitionVersions),
		parentRevisionId: row.parentRevisionId
	}));
	const reusableBlocks = referenceRows.reusables.filter((row) => containsBlock(row.document, input.definitionKey)).map((row) => Object.freeze({
		id: row.id,
		document: jsonValue(row.document),
		definitionVersions: definitionVersions(row.definitionVersions)
	}));
	const revisions = (manifest.revisions ?? []).filter((item) => item.blockDocument && containsBlock(item.blockDocument, input.definitionKey)).map((item) => Object.freeze({
		id: item.sourceRevisionKey,
		ref: item.sourceRef,
		parentRevisionId: item.parentRevisionKey,
		kind: "revision",
		definitionVersions: item.definitionVersions,
		values: fieldStorage(item.values, "revision.values"),
		blockDocument: fieldStorage(item.blockDocument, "revision.blockDocument"),
		createdAt: item.createdAt,
		createdBy: item.createdBySourceId,
		sourceVersion: String(item.sourceVersion)
	}));
	return Object.freeze({
		version: 1,
		blockDefinitions: Object.freeze([{
			key: input.definitionKey,
			definition,
			active: true
		}]),
		blockDocuments: Object.freeze(blockDocuments),
		reusableBlocks: Object.freeze(reusableBlocks),
		revisions: Object.freeze(revisions)
	});
}
async function createContentTypeDefinitionBackup(tx, impact, strategy) {
	const features = Object.freeze([...new Set(strategy.features)].sort());
	const scopeHash = await canonicalContentMigrationHash({
		definitionKey: impact.definitionKey,
		features,
		policyVersion: impact.authorizationPolicyVersion,
		corpusVersion: impact.corpusVersion,
		corpusHash: impact.corpusHash
	});
	const expectedCounts = Object.freeze(Object.fromEntries(features.map((feature) => [`feature:${feature}`, impact.affectedCounts[`feature:${feature}`] ?? 0])));
	const entries = rowsOf(await tx.execute(sql`SELECT id,excerpt,featured_media AS "featuredMedia",parent_id AS "parentId",menu_order AS "menuOrder",template_key AS "templateKey",format FROM content_entries WHERE type=${impact.definitionKey} ORDER BY id`)).map((row) => {
		const item = { id: String(row.id) };
		if (features.includes("excerpt")) item.excerpt = typeof row.excerpt === "string" ? row.excerpt : "";
		if (features.includes("featuredImage")) item.featuredMedia = jsonValue(row.featuredMedia) ?? null;
		if (features.includes("pageAttributes")) {
			item.parentId = row.parentId === null ? null : String(row.parentId);
			item.menuOrder = Number(row.menuOrder ?? 0);
			item.templateKey = row.templateKey === null ? null : String(row.templateKey);
		}
		if (features.includes("postFormats")) item.format = row.format === null ? null : String(row.format);
		return Object.freeze(item);
	});
	const payload = Object.freeze({
		version: 1,
		entries: Object.freeze(entries)
	});
	return persistContentModelDefinitionBackup(tx, {
		id: strategy.backupId,
		kind: "content",
		scopeHash,
		corpusVersion: impact.corpusVersion,
		corpusHash: impact.corpusHash,
		itemCounts: expectedCounts,
		payload
	});
}
async function createFieldsDefinitionBackup(tx, context, input) {
	const definitionKind = input.kind, definitionKey = input.kind === "group" ? input.impact.groupKey : input.kind === "optionsPage" ? input.impact.pageKey : input.impact.blockKey;
	const corpusVersion = input.kind === "block" ? input.impact.documentCorpusVersion : input.impact.valueCorpusVersion;
	const corpusHash = input.kind === "block" ? input.impact.documentCorpusHash : input.impact.valueCorpusHash;
	const affectedCounts = input.kind === "block" ? Object.freeze({
		documents: input.impact.affectedDocuments,
		definitionVersions: input.impact.affectedDefinitionVersions
	}) : input.impact.affectedCounts;
	const authorizationPolicyVersion = input.impact.authorizationPolicyVersion;
	const previewToken = input.impact.token;
	const scopeHash = await canonicalFieldsMigrationHash({
		definitionKind,
		definitionKey,
		strategy: input.strategy,
		authorizationPolicyVersion,
		corpusVersion,
		corpusHash,
		previewToken,
		affectedCounts
	});
	const payload = await buildFieldsBackupPayload(tx, {
		definitionKind,
		definitionKey
	}, context);
	return persistContentModelDefinitionBackup(tx, {
		id: input.strategy.backupId,
		kind: "fields",
		scopeHash,
		corpusVersion,
		corpusHash,
		itemCounts: affectedCounts,
		payload: fieldStorage(payload, "fieldsBackup")
	});
}
async function listContentModelAdminDefinitions(env, sources = {}) {
	const db = getFullDb(env).db;
	const [contentTypes, contentStatuses, fieldGroups, optionsPages, blockRegistry, backups] = await Promise.all([
		resolveContentTypes(db, { codeTypes: sources.contentTypes }),
		resolveContentStatuses(db, { codeStatuses: sources.contentStatuses }),
		resolveFinalFieldGroups(db, { codeGroups: sources.fieldGroups }),
		resolveOptionsPages(db, { codePages: sources.optionsPages }),
		resolveFieldBlocks(db, { codeBlocks: sources.blocks }),
		listDefinitionBackups(db)
	]);
	return Object.freeze({
		contentTypes: Object.freeze(contentTypes),
		contentStatuses: Object.freeze(contentStatuses),
		fieldGroups: Object.freeze(fieldGroups),
		optionsPages: Object.freeze(optionsPages),
		blocks: Object.freeze([...blockRegistry.blocks.values()]),
		blockRegistryVersion: blockRegistry.version,
		backups
	});
}
async function runContentModelAdminMutation(env, operation) {
	const capability = getMutationDb(env);
	if (capability.dialect !== "postgres") throw new ContentModelAdminError("unsupported-capability", "definition administration requires one callback transaction or one host-owned D1 atomic prepared batch; definition lifecycle prepared contributions are not available");
	return capability.db.transaction((tx) => operation(tx));
}
//#endregion
export { contentModelAdminFieldsDestructiveEffects as a, contentModelContentBackupStore as c, createFieldsDefinitionBackup as d, listContentModelAdminDefinitions as f, contentModelAdminFieldsContext as i, contentModelFieldsBackupStore as l, runContentModelAdminMutation as m, contentModelAdminAuthorization as n, contentModelAdminOptionsFieldsContext as o, previewContentModelDefinitionBackupRestore as p, contentModelAdminContentEffects as r, contentModelAdminPrincipal as s, ContentModelAdminError as t, createContentTypeDefinitionBackup as u };
