import type { RequestHandler } from './$types'; import { json, error } from '@sveltejs/kit'; import { env } from '$env/dynamic/private'; import { env as envPublic } from '$env/dynamic/public'; import { invalidateAll } from '$lib/cms'; import { clearImageCache } from '$lib/image-cache.server'; /** * Manual full-cache purge: * - SvelteKit-side TTL cache (cms.ts) * - SvelteKit image cache (memory + disk) * - Optionally: forwards POST to RustyCMS /api/transform/cache/invalidate * when an API key is configured (RUSTYCMS_API_KEY env). * * Auth: same `REVALIDATE_TOKEN` as /api/revalidate. */ export const POST: RequestHandler = async ({ request, url }) => { const token = env.REVALIDATE_TOKEN; if (!token) throw error(500, 'REVALIDATE_TOKEN not configured'); const provided = request.headers.get('x-revalidate-token') ?? request.headers.get('x-webhook-secret') ?? url.searchParams.get('token'); if (provided !== token) throw error(401, 'invalid token'); invalidateAll(); const img = await clearImageCache(); let cms: unknown = 'skipped'; const apiKey = env.RUSTYCMS_API_KEY; const cmsUrl = (envPublic.PUBLIC_CMS_URL || '').replace(/\/$/, ''); if (apiKey && cmsUrl) { try { const res = await fetch(`${cmsUrl}/api/transform/cache/invalidate`, { method: 'POST', headers: { authorization: `Bearer ${apiKey}` }, }); cms = res.ok ? await res.json() : { error: res.status }; } catch (e) { cms = { error: e instanceof Error ? e.message : String(e) }; } } return json({ ok: true, content_cache: 'cleared', image_cache: img, cms }); };