Export/import: fix lost images and malformed-file crashes

- An image URL used more than once in the same string (e.g. rich text) was
  only replaced once, leaving broken __IMG__ placeholders after import.
- Images that failed to export were still replaced by placeholders that the
  import could never resolve; keep the original URL instead.
- Validate the uploaded file's shape and JSON (was a 500 on bad input).
- Build lookup filters with pb.filter so names/slugs with quotes don't
  create duplicates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
This commit is contained in:
agent 2026-10-06 10:46:24 +00:00
parent ff54adb00c
commit 1eb58c71ba
3 changed files with 394 additions and 374 deletions

View file

@ -1,139 +1,150 @@
import type { CalendarEventRecord, ContentBlock } from '$lib/types'; import type { CalendarEventRecord, ContentBlock } from '$lib/types';
/** /**
* The portable export format. * The portable export format.
* Images are stored as base64 data-URIs so the file is fully self-contained. * Images are stored as base64 data-URIs so the file is fully self-contained.
*/ */
export type SiteExport = { export type SiteExport = {
version: 1; version: 1;
exportedAt: string; exportedAt: string;
pages: { pages: {
slug: string; slug: string;
title: string; title: string;
blocks: ContentBlock[]; blocks: ContentBlock[];
published: boolean; published: boolean;
}[]; }[];
globals: { globals: {
key: string; key: string;
data: Record<string, unknown>; data: Record<string, unknown>;
}[]; }[];
events?: Omit<CalendarEventRecord, 'id'>[]; events?: Omit<CalendarEventRecord, 'id'>[];
/** Maps original PocketBase file URLs → base64 data-URI */ /** Maps original PocketBase file URLs → base64 data-URI */
images: Record<string, string>; images: Record<string, string>;
}; };
/** Regex to match PocketBase file URLs */ /** Regex to match PocketBase file URLs */
const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g; const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g;
/** /**
* Extract all PocketBase image URLs from a value (recursive). * Extract all PocketBase image URLs from a value (recursive).
*/ */
export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> { export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> {
if (typeof value === 'string') { if (typeof value === 'string') {
let match: RegExpExecArray | null; let match: RegExpExecArray | null;
const re = new RegExp(PB_FILE_RE.source, 'g'); const re = new RegExp(PB_FILE_RE.source, 'g');
while ((match = re.exec(value)) !== null) { while ((match = re.exec(value)) !== null) {
urls.add(match[0]); urls.add(match[0]);
} }
} else if (Array.isArray(value)) { } else if (Array.isArray(value)) {
for (const item of value) extractImageUrls(item, urls); for (const item of value) extractImageUrls(item, urls);
} else if (value && typeof value === 'object') { } else if (value && typeof value === 'object') {
for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls); for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls);
} }
return urls; return urls;
} }
/** /**
* Replace all PocketBase URLs in a value with a placeholder key. * Replace all PocketBase URLs in a value with a placeholder key.
*/ */
export function replaceUrlsWithKeys( export function replaceUrlsWithKeys(
value: unknown, value: unknown,
urlToKey: Map<string, string> urlToKey: Map<string, string>
): unknown { ): unknown {
if (typeof value === 'string') { if (typeof value === 'string') {
let result = value; let result = value;
for (const [url, key] of urlToKey) { for (const [url, key] of urlToKey) {
result = result.replace(url, `__IMG__${key}__`); result = result.replaceAll(url, `__IMG__${key}__`);
} }
return result; return result;
} }
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map((item) => replaceUrlsWithKeys(item, urlToKey)); return value.map((item) => replaceUrlsWithKeys(item, urlToKey));
} }
if (value && typeof value === 'object') { if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {}; const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) { for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = replaceUrlsWithKeys(v, urlToKey); obj[k] = replaceUrlsWithKeys(v, urlToKey);
} }
return obj; return obj;
} }
return value; return value;
} }
/** /**
* Restore image placeholders back to real URLs after import. * Restore image placeholders back to real URLs after import.
*/ */
export function restorePlaceholders( export function restorePlaceholders(
value: unknown, value: unknown,
keyToUrl: Map<string, string> keyToUrl: Map<string, string>
): unknown { ): unknown {
if (typeof value === 'string') { if (typeof value === 'string') {
let result = value; let result = value;
for (const [key, url] of keyToUrl) { for (const [key, url] of keyToUrl) {
result = result.replace(`__IMG__${key}__`, url); result = result.replaceAll(`__IMG__${key}__`, url);
} }
return result; return result;
} }
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map((item) => restorePlaceholders(item, keyToUrl)); return value.map((item) => restorePlaceholders(item, keyToUrl));
} }
if (value && typeof value === 'object') { if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {}; const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) { for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = restorePlaceholders(v, keyToUrl); obj[k] = restorePlaceholders(v, keyToUrl);
} }
return obj; return obj;
} }
return value; return value;
} }
/** /**
* Generate a short unique key for an image URL. * Generate a short unique key for an image URL.
*/ */
export function urlToKey(url: string): string { export function urlToKey(url: string): string {
const parts = url.split('/'); const parts = url.split('/');
const filename = parts[parts.length - 1] || 'img'; const filename = parts[parts.length - 1] || 'img';
const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown'; const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown';
return `${id}_${filename}`; return `${id}_${filename}`;
} }
/** /**
* Fetch an image and return it as a base64 data-URI string. * Fetch an image and return it as a base64 data-URI string.
*/ */
export async function fetchImageAsBase64(url: string): Promise<string> { export async function fetchImageAsBase64(url: string): Promise<string> {
const response = await fetch(url); const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`); if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`);
const blob = await response.blob(); const blob = await response.blob();
const buffer = await blob.arrayBuffer(); const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer); const bytes = new Uint8Array(buffer);
let binary = ''; let binary = '';
for (let i = 0; i < bytes.length; i++) { for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]); binary += String.fromCharCode(bytes[i]);
} }
const base64 = btoa(binary); const base64 = btoa(binary);
return `data:${blob.type};base64,${base64}`; return `data:${blob.type};base64,${base64}`;
} }
/** /** Shape check for an uploaded export file; returns an error message or null. */
* Convert a base64 data-URI back to a File object for upload. export function validateSiteExport(body: unknown): string | null {
*/ if (!body || typeof body !== 'object') return 'The file is not a CMS export.';
export function dataUriToFile(dataUri: string, filename: string): File { const b = body as Partial<SiteExport>;
const [header, base64] = dataUri.split(','); if (b.version !== 1) return 'Unsupported export version.';
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png'; if (!Array.isArray(b.pages) || !Array.isArray(b.globals)) return 'The export is missing pages or globals.';
const binary = atob(base64); if (b.events !== undefined && !Array.isArray(b.events)) return 'The export has an invalid events list.';
const bytes = new Uint8Array(binary.length); if (!b.images || typeof b.images !== 'object' || Array.isArray(b.images)) return 'The export is missing its images.';
for (let i = 0; i < binary.length; i++) { return null;
bytes[i] = binary.charCodeAt(i); }
}
return new File([bytes], filename, { type: mime }); /**
* Convert a base64 data-URI back to a File object for upload.
*/
export function dataUriToFile(dataUri: string, filename: string): File {
const [header, base64] = dataUri.split(',');
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return new File([bytes], filename, { type: mime });
} }

View file

@ -1,98 +1,101 @@
import { env } from '$env/dynamic/private'; import { env } from '$env/dynamic/private';
import { json } from '@sveltejs/kit'; import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { import {
extractImageUrls, extractImageUrls,
fetchImageAsBase64, fetchImageAsBase64,
replaceUrlsWithKeys, replaceUrlsWithKeys,
urlToKey, urlToKey,
type SiteExport type SiteExport
} from '$lib/exportImport'; } from '$lib/exportImport';
import { normalizeEvent } from '$lib/calendar'; import { normalizeEvent } from '$lib/calendar';
export const GET: RequestHandler = async ({ locals }) => { export const GET: RequestHandler = async ({ locals }) => {
// Fetch all pages // Fetch all pages
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' }); const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
// Fetch all globals // Fetch all globals
const globals = await locals.pb.collection('globals').getFullList(); const globals = await locals.pb.collection('globals').getFullList();
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []); const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
// Collect all image URLs from pages and globals // Collect all image URLs from pages and globals
const allUrls = new Set<string>(); const allUrls = new Set<string>();
for (const page of pages) { for (const page of pages) {
for (const url of extractImageUrls(page)) allUrls.add(url); for (const url of extractImageUrls(page)) allUrls.add(url);
} }
for (const g of globals) { for (const g of globals) {
for (const url of extractImageUrls(g)) allUrls.add(url); for (const url of extractImageUrls(g)) allUrls.add(url);
} }
// Fetch each image as base64. Stored image URLs may use any public host // Fetch each image as base64. Stored image URLs may use any public host
// (e.g. http://localhost:8080 from before a domain migration, or // (e.g. http://localhost:8080 from before a domain migration, or
// http://db.localhost:8080 after). The app container can only reach // http://db.localhost:8080 after). The app container can only reach
// PocketBase via the internal Docker network URL, so rewrite the host // PocketBase via the internal Docker network URL, so rewrite the host
// of every matched URL to the internal base. // of every matched URL to the internal base.
const internalBase = env.POCKETBASE_INTERNAL_URL!; const internalBase = env.POCKETBASE_INTERNAL_URL!;
const images: Record<string, string> = {}; const images: Record<string, string> = {};
for (const url of allUrls) { for (const url of allUrls) {
try { try {
// Replace the host (and optional port) with the internal base. // Replace the host (and optional port) with the internal base.
const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase); const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase);
const key = urlToKey(url); const key = urlToKey(url);
images[key] = await fetchImageAsBase64(fetchUrl); images[key] = await fetchImageAsBase64(fetchUrl);
} catch (e) { } catch (e) {
console.warn(`Could not fetch image: ${url}`, e); console.warn(`Could not fetch image: ${url}`, e);
} }
} }
// Build URL → key mapping // Build URL → key mapping — only for images that were actually exported.
const urlToKeyMap = new Map<string, string>(); // A URL whose image couldn't be fetched is left as-is rather than turned
for (const url of allUrls) { // into a placeholder the import could never resolve.
urlToKeyMap.set(url, urlToKey(url)); const urlToKeyMap = new Map<string, string>();
} for (const url of allUrls) {
const key = urlToKey(url);
// Replace URLs with placeholders in pages if (key in images) urlToKeyMap.set(url, key);
const exportPages = pages.map((p) => ({ }
slug: p.slug,
title: p.title, // Replace URLs with placeholders in pages
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks, const exportPages = pages.map((p) => ({
published: p.published slug: p.slug,
})); title: p.title,
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
// Replace URLs with placeholders in globals published: p.published
const exportGlobals = globals.map((g) => ({ }));
key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown> // Replace URLs with placeholders in globals
})); const exportGlobals = globals.map((g) => ({
key: g.key,
const exportEvents = events.map((record) => { data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
const event = normalizeEvent(record); }));
return {
name: event.name, const exportEvents = events.map((record) => {
start: event.start, const event = normalizeEvent(record);
end: event.end, return {
description: event.description, name: event.name,
color: event.color, start: event.start,
link: event.link, end: event.end,
categories: event.categories, description: event.description,
published: event.published, color: event.color,
allDay: event.allDay link: event.link,
}; categories: event.categories,
}); published: event.published,
allDay: event.allDay
const exportData: SiteExport = { };
version: 1, });
exportedAt: new Date().toISOString(),
pages: exportPages, const exportData: SiteExport = {
globals: exportGlobals, version: 1,
events: exportEvents, exportedAt: new Date().toISOString(),
images pages: exportPages,
}; globals: exportGlobals,
events: exportEvents,
return json(exportData, { images
headers: { };
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
} return json(exportData, {
}); headers: {
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
}
});
}; };

View file

@ -1,140 +1,146 @@
import { env } from '$env/dynamic/public'; import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit'; import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { import {
dataUriToFile, dataUriToFile,
restorePlaceholders, restorePlaceholders,
type SiteExport validateSiteExport,
} from '$lib/exportImport'; type SiteExport
} from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => {
const body = (await request.json()) as SiteExport; export const POST: RequestHandler = async ({ request, locals }) => {
let body: SiteExport;
if (!body || body.version !== 1) { try {
throw error(400, 'Invalid or unsupported export file.'); body = await request.json();
} } catch {
throw error(400, 'The file is not valid JSON.');
const results = { }
imagesUploaded: 0, const invalid = validateSiteExport(body);
pagesImported: 0, if (invalid) throw error(400, invalid);
globalsImported: 0,
eventsImported: 0, const results = {
errors: [] as string[] imagesUploaded: 0,
}; pagesImported: 0,
globalsImported: 0,
// 1. Upload images to PocketBase media collection eventsImported: 0,
// Build a map: placeholder key → new PocketBase URL errors: [] as string[]
const keyToUrl = new Map<string, string>(); };
for (const [key, dataUri] of Object.entries(body.images)) { // 1. Upload images to PocketBase media collection
try { // Build a map: placeholder key → new PocketBase URL
// Derive a filename from the key (e.g. "abc12345_logo.png") const keyToUrl = new Map<string, string>();
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
const file = dataUriToFile(dataUri, filename); for (const [key, dataUri] of Object.entries(body.images)) {
try {
const formData = new FormData(); // Derive a filename from the key (e.g. "abc12345_logo.png")
formData.append('file', file); const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); const file = dataUriToFile(dataUri, filename);
const record = await locals.pb.collection('media').create(formData); const formData = new FormData();
const publicUrl = env.PUBLIC_POCKETBASE_URL; formData.append('file', file);
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`; formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
keyToUrl.set(key, newUrl); const record = await locals.pb.collection('media').create(formData);
results.imagesUploaded++; const publicUrl = env.PUBLIC_POCKETBASE_URL;
} catch (e) { const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
} keyToUrl.set(key, newUrl);
} results.imagesUploaded++;
} catch (e) {
// 2. Import pages results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
for (const page of body.pages) { }
try { }
const blocks = restorePlaceholders(page.blocks, keyToUrl);
// 2. Import pages
// Try to find existing page by slug for (const page of body.pages) {
let existing; try {
try { const blocks = restorePlaceholders(page.blocks, keyToUrl);
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
} catch { // Try to find existing page by slug
existing = null; let existing;
} try {
existing = await locals.pb.collection('pages').getFirstListItem(locals.pb.filter('slug = {:slug}', { slug: page.slug }));
if (existing) { } catch {
await locals.pb.collection('pages').update(existing.id, { existing = null;
title: page.title, }
blocks,
published: page.published if (existing) {
}); await locals.pb.collection('pages').update(existing.id, {
} else { title: page.title,
await locals.pb.collection('pages').create({ blocks,
slug: page.slug, published: page.published
title: page.title, });
blocks, } else {
published: page.published await locals.pb.collection('pages').create({
}); slug: page.slug,
} title: page.title,
results.pagesImported++; blocks,
} catch (e) { published: page.published
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`); });
} }
} results.pagesImported++;
} catch (e) {
// 3. Import globals results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
for (const g of body.globals) { }
try { }
const data = restorePlaceholders(g.data, keyToUrl);
// 3. Import globals
let existing; for (const g of body.globals) {
try { try {
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`); const data = restorePlaceholders(g.data, keyToUrl);
} catch {
existing = null; let existing;
} try {
existing = await locals.pb.collection('globals').getFirstListItem(locals.pb.filter('key = {:key}', { key: g.key }));
if (existing) { } catch {
await locals.pb.collection('globals').update(existing.id, { data }); existing = null;
} else { }
await locals.pb.collection('globals').create({ key: g.key, data });
} if (existing) {
results.globalsImported++; await locals.pb.collection('globals').update(existing.id, { data });
} catch (e) { } else {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`); await locals.pb.collection('globals').create({ key: g.key, data });
} }
} results.globalsImported++;
} catch (e) {
// 4. Import events results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
for (const event of body.events || []) { }
try { }
let existing;
try { // 4. Import events
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`); for (const event of body.events || []) {
} catch { try {
existing = null; let existing;
} try {
existing = await locals.pb
const payload = { .collection('events')
name: event.name, .getFirstListItem(locals.pb.filter('name = {:name} && start = {:start}', { name: event.name, start: event.start }));
start: event.start, } catch {
end: event.end || null, existing = null;
description: event.description || '', }
color: event.color || '#8a9a7b',
link: event.link || '', const payload = {
categories: event.categories || [], name: event.name,
published: Boolean(event.published), start: event.start,
allDay: event.allDay !== false end: event.end || null,
}; description: event.description || '',
color: event.color || '#8a9a7b',
if (existing) { link: event.link || '',
await locals.pb.collection('events').update(existing.id, payload); categories: event.categories || [],
} else { published: Boolean(event.published),
await locals.pb.collection('events').create(payload); allDay: event.allDay !== false
} };
results.eventsImported++;
} catch (e) { if (existing) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`); await locals.pb.collection('events').update(existing.id, payload);
} } else {
} await locals.pb.collection('events').create(payload);
}
return json(results); results.eventsImported++;
} catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
}
}
return json(results);
}; };