Files
gracesalmoun/lib/cms-validation.ts
2026-11-13 12:08:12 +03:00

40 lines
2.9 KiB
TypeScript

import { initialContent, blankProject } from "./cms-defaults";
import type { CmsContent } from "./cms-types";
export function safeAsset(value: string) {
return value === "" || (/^\/(?!\/)[^\\\s]*$/.test(value) && !value.includes("..")) || /^https:\/\/[^\s\\]+$/i.test(value);
}
function validate(value: unknown, template: unknown, path: string): void {
if (Array.isArray(template)) {
if (!Array.isArray(value) || value.length > 200) throw new Error(`قائمة غير صالحة: ${path}`);
value.forEach((entry, index) => validate(entry, template[0] ?? "", `${path}.${index}`)); return;
}
if (template && typeof template === "object") {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`قسم غير صالح: ${path}`);
const record = value as Record<string, unknown>;
for (const key of Object.keys(record)) if (!Object.hasOwn(template, key)) throw new Error(`حقل غير معروف: ${path}.${key}`);
for (const [key, child] of Object.entries(template)) validate(record[key], child, `${path}.${key}`); return;
}
if (typeof value !== typeof template || (typeof value === "string" && value.length > 20000)) throw new Error(`قيمة غير صالحة: ${path}`);
}
export function validateContent(value: unknown): asserts value is CmsContent {
const defaults = initialContent(); defaults.projects = [blankProject()];
validate(value, defaults, "content");
const content = value as CmsContent;
if (!Number.isFinite(Date.parse(content.updatedAt))) throw new Error("تاريخ النسخة غير صالح");
if (!/^#[0-9a-f]{6}$/i.test(content.settings.accentColor)) throw new Error("اللون غير صالح");
const assets = [content.profile.heroImage, content.profile.profileImage, content.profile.logoImage, content.settings.resumeUrl];
const ids = new Set<string>();
for (const p of content.projects) {
if (!p.id || ids.has(p.id) || !["portrait", "landscape"].includes(p.orientation)) throw new Error("معرّف المشروع أو اتجاه الصورة غير صالح");
if (!p.titleAr.trim() || !p.titleEn.trim()) throw new Error("أدخل عنوان المشروع بالعربية والإنجليزية");
ids.add(p.id); assets.push(p.coverImage, p.sheetImage, ...p.additionalSheetImages);
}
if (assets.some(url => !safeAsset(url))) throw new Error("استخدم رابط ملف محلي أو رابط HTTPS صالح");
for (const url of [content.profile.facebook, content.profile.whatsapp, content.profile.locationHref]) {
if (url && !/^https:\/\/[^\s\\]+$/i.test(url)) throw new Error("روابط التواصل والخريطة يجب أن تبدأ بـ https://");
}
if (content.profile.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(content.profile.email)) throw new Error("البريد الإلكتروني غير صالح");
if (content.settings.resumeAvailable && !content.settings.resumeUrl) throw new Error("أضف ملف السيرة الذاتية أو أوقف تنزيله");
}