added import export functionality
This commit is contained in:
parent
af58adb345
commit
7d6351f2c5
5 changed files with 388 additions and 2 deletions
138
app/src/lib/exportImport.ts
Normal file
138
app/src/lib/exportImport.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
||||||
|
import type { ContentBlock, PageRecord } from '$lib/types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The portable export format.
|
||||||
|
* Images are stored as base64 data-URIs so the file is fully self-contained.
|
||||||
|
*/
|
||||||
|
export type SiteExport = {
|
||||||
|
version: 1;
|
||||||
|
exportedAt: string;
|
||||||
|
pages: {
|
||||||
|
slug: string;
|
||||||
|
title: string;
|
||||||
|
blocks: ContentBlock[];
|
||||||
|
published: boolean;
|
||||||
|
}[];
|
||||||
|
globals: {
|
||||||
|
key: string;
|
||||||
|
data: Record<string, unknown>;
|
||||||
|
}[];
|
||||||
|
/** Maps original PocketBase file URLs → base64 data-URI */
|
||||||
|
images: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Regex to match PocketBase file URLs */
|
||||||
|
const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract all PocketBase image URLs from a value (recursive).
|
||||||
|
*/
|
||||||
|
export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
let match: RegExpExecArray | null;
|
||||||
|
const re = new RegExp(PB_FILE_RE.source, 'g');
|
||||||
|
while ((match = re.exec(value)) !== null) {
|
||||||
|
urls.add(match[0]);
|
||||||
|
}
|
||||||
|
} else if (Array.isArray(value)) {
|
||||||
|
for (const item of value) extractImageUrls(item, urls);
|
||||||
|
} else if (value && typeof value === 'object') {
|
||||||
|
for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls);
|
||||||
|
}
|
||||||
|
return urls;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace all PocketBase URLs in a value with a placeholder key.
|
||||||
|
*/
|
||||||
|
export function replaceUrlsWithKeys(
|
||||||
|
value: unknown,
|
||||||
|
urlToKey: Map<string, string>
|
||||||
|
): unknown {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
let result = value;
|
||||||
|
for (const [url, key] of urlToKey) {
|
||||||
|
result = result.replace(url, `__IMG__${key}__`);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map((item) => replaceUrlsWithKeys(item, urlToKey));
|
||||||
|
}
|
||||||
|
if (value && typeof value === 'object') {
|
||||||
|
const obj: Record<string, unknown> = {};
|
||||||
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||||
|
obj[k] = replaceUrlsWithKeys(v, urlToKey);
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restore image placeholders back to real URLs after import.
|
||||||
|
*/
|
||||||
|
export function restorePlaceholders(
|
||||||
|
value: unknown,
|
||||||
|
keyToUrl: Map<string, string>
|
||||||
|
): unknown {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
let result = value;
|
||||||
|
for (const [key, url] of keyToUrl) {
|
||||||
|
result = result.replace(`__IMG__${key}__`, url);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map((item) => restorePlaceholders(item, keyToUrl));
|
||||||
|
}
|
||||||
|
if (value && typeof value === 'object') {
|
||||||
|
const obj: Record<string, unknown> = {};
|
||||||
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||||
|
obj[k] = restorePlaceholders(v, keyToUrl);
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a short unique key for an image URL.
|
||||||
|
*/
|
||||||
|
export function urlToKey(url: string): string {
|
||||||
|
const parts = url.split('/');
|
||||||
|
const filename = parts[parts.length - 1] || 'img';
|
||||||
|
const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown';
|
||||||
|
return `${id}_${filename}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch an image and return it as a base64 data-URI string.
|
||||||
|
*/
|
||||||
|
export async function fetchImageAsBase64(url: string): Promise<string> {
|
||||||
|
const response = await fetch(url);
|
||||||
|
if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`);
|
||||||
|
const blob = await response.blob();
|
||||||
|
const buffer = await blob.arrayBuffer();
|
||||||
|
const bytes = new Uint8Array(buffer);
|
||||||
|
let binary = '';
|
||||||
|
for (let i = 0; i < bytes.length; i++) {
|
||||||
|
binary += String.fromCharCode(bytes[i]);
|
||||||
|
}
|
||||||
|
const base64 = btoa(binary);
|
||||||
|
return `data:${blob.type};base64,${base64}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 });
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,54 @@
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
let { children } = $props();
|
let { children } = $props();
|
||||||
|
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
|
||||||
|
let importing = $state(false);
|
||||||
|
|
||||||
|
async function handleExport() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/admin/api/export');
|
||||||
|
if (!res.ok) throw new Error(`Export failed (${res.status})`);
|
||||||
|
const blob = await res.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (e) {
|
||||||
|
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleImport(event: Event) {
|
||||||
|
const input = event.target as HTMLInputElement;
|
||||||
|
const file = input.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
importing = true;
|
||||||
|
importStatus = null;
|
||||||
|
try {
|
||||||
|
const text = await file.text();
|
||||||
|
const json = JSON.parse(text);
|
||||||
|
const res = await fetch('/admin/api/import', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(json)
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(err?.message || `Import failed (${res.status})`);
|
||||||
|
}
|
||||||
|
const result = await res.json();
|
||||||
|
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.imagesUploaded} image(s).`;
|
||||||
|
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
|
||||||
|
setTimeout(() => location.reload(), 1500);
|
||||||
|
} catch (e) {
|
||||||
|
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
|
||||||
|
} finally {
|
||||||
|
importing = false;
|
||||||
|
input.value = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="min-h-screen bg-base-200">
|
<div class="min-h-screen bg-base-200">
|
||||||
|
|
@ -10,11 +59,34 @@
|
||||||
<div class="flex-none gap-2">
|
<div class="flex-none gap-2">
|
||||||
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
|
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
|
||||||
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
|
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
|
||||||
|
<div class="dropdown dropdown-end">
|
||||||
|
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
|
||||||
|
Export/Import
|
||||||
|
</button>
|
||||||
|
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
|
||||||
|
<li><button type="button" onclick={handleExport}>Export all</button></li>
|
||||||
|
<li>
|
||||||
|
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
|
||||||
|
{importing ? 'Importing…' : 'Import'}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
|
||||||
<form class="inline" method="POST" action="/admin/login?/logout">
|
<form class="inline" method="POST" action="/admin/login?/logout">
|
||||||
<button class="btn btn-outline" type="submit">Logout</button>
|
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{#if importStatus}
|
||||||
|
<div class="mx-auto max-w-7xl px-4 pt-2">
|
||||||
|
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
|
||||||
|
{importStatus.message}
|
||||||
|
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
<main class="mx-auto max-w-7xl p-4 md:p-8">
|
<main class="mx-auto max-w-7xl p-4 md:p-8">
|
||||||
{@render children()}
|
{@render children()}
|
||||||
</main>
|
</main>
|
||||||
|
|
|
||||||
71
app/src/routes/admin/api/export/+server.ts
Normal file
71
app/src/routes/admin/api/export/+server.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import {
|
||||||
|
extractImageUrls,
|
||||||
|
fetchImageAsBase64,
|
||||||
|
replaceUrlsWithKeys,
|
||||||
|
urlToKey,
|
||||||
|
type SiteExport
|
||||||
|
} from '$lib/exportImport';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals }) => {
|
||||||
|
// Fetch all pages
|
||||||
|
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||||
|
|
||||||
|
// Fetch all globals
|
||||||
|
const globals = await locals.pb.collection('globals').getFullList();
|
||||||
|
|
||||||
|
// Collect all image URLs from pages and globals
|
||||||
|
const allUrls = new Set<string>();
|
||||||
|
for (const page of pages) {
|
||||||
|
for (const url of extractImageUrls(page)) allUrls.add(url);
|
||||||
|
}
|
||||||
|
for (const g of globals) {
|
||||||
|
for (const url of extractImageUrls(g)) allUrls.add(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch each image as base64
|
||||||
|
const images: Record<string, string> = {};
|
||||||
|
for (const url of allUrls) {
|
||||||
|
try {
|
||||||
|
const key = urlToKey(url);
|
||||||
|
images[key] = await fetchImageAsBase64(url);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Could not fetch image: ${url}`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build URL → key mapping
|
||||||
|
const urlToKeyMap = new Map<string, string>();
|
||||||
|
for (const url of allUrls) {
|
||||||
|
urlToKeyMap.set(url, urlToKey(url));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace URLs with placeholders in pages
|
||||||
|
const exportPages = pages.map((p) => ({
|
||||||
|
slug: p.slug,
|
||||||
|
title: p.title,
|
||||||
|
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
|
||||||
|
published: p.published
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Replace URLs with placeholders in globals
|
||||||
|
const exportGlobals = globals.map((g) => ({
|
||||||
|
key: g.key,
|
||||||
|
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
|
||||||
|
}));
|
||||||
|
|
||||||
|
const exportData: SiteExport = {
|
||||||
|
version: 1,
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
pages: exportPages,
|
||||||
|
globals: exportGlobals,
|
||||||
|
images
|
||||||
|
};
|
||||||
|
|
||||||
|
return json(exportData, {
|
||||||
|
headers: {
|
||||||
|
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
106
app/src/routes/admin/api/import/+server.ts
Normal file
106
app/src/routes/admin/api/import/+server.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
import { env } from '$env/dynamic/public';
|
||||||
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import {
|
||||||
|
dataUriToFile,
|
||||||
|
restorePlaceholders,
|
||||||
|
type SiteExport
|
||||||
|
} from '$lib/exportImport';
|
||||||
|
|
||||||
|
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||||
|
const body = (await request.json()) as SiteExport;
|
||||||
|
|
||||||
|
if (!body || body.version !== 1) {
|
||||||
|
throw error(400, 'Invalid or unsupported export file.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = {
|
||||||
|
imagesUploaded: 0,
|
||||||
|
pagesImported: 0,
|
||||||
|
globalsImported: 0,
|
||||||
|
errors: [] as string[]
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Upload images to PocketBase media collection
|
||||||
|
// Build a map: placeholder key → new PocketBase URL
|
||||||
|
const keyToUrl = new Map<string, string>();
|
||||||
|
|
||||||
|
for (const [key, dataUri] of Object.entries(body.images)) {
|
||||||
|
try {
|
||||||
|
// Derive a filename from the key (e.g. "abc12345_logo.png")
|
||||||
|
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
|
||||||
|
const file = dataUriToFile(dataUri, filename);
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
|
||||||
|
|
||||||
|
const record = await locals.pb.collection('media').create(formData);
|
||||||
|
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090';
|
||||||
|
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
|
||||||
|
|
||||||
|
keyToUrl.set(key, newUrl);
|
||||||
|
results.imagesUploaded++;
|
||||||
|
} catch (e) {
|
||||||
|
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Import pages
|
||||||
|
for (const page of body.pages) {
|
||||||
|
try {
|
||||||
|
const blocks = restorePlaceholders(page.blocks, keyToUrl);
|
||||||
|
|
||||||
|
// Try to find existing page by slug
|
||||||
|
let existing;
|
||||||
|
try {
|
||||||
|
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
|
||||||
|
} catch {
|
||||||
|
existing = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
await locals.pb.collection('pages').update(existing.id, {
|
||||||
|
title: page.title,
|
||||||
|
blocks,
|
||||||
|
published: page.published
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await locals.pb.collection('pages').create({
|
||||||
|
slug: page.slug,
|
||||||
|
title: page.title,
|
||||||
|
blocks,
|
||||||
|
published: page.published
|
||||||
|
});
|
||||||
|
}
|
||||||
|
results.pagesImported++;
|
||||||
|
} catch (e) {
|
||||||
|
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Import globals
|
||||||
|
for (const g of body.globals) {
|
||||||
|
try {
|
||||||
|
const data = restorePlaceholders(g.data, keyToUrl);
|
||||||
|
|
||||||
|
let existing;
|
||||||
|
try {
|
||||||
|
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
|
||||||
|
} catch {
|
||||||
|
existing = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
await locals.pb.collection('globals').update(existing.id, { data });
|
||||||
|
} else {
|
||||||
|
await locals.pb.collection('globals').create({ key: g.key, data });
|
||||||
|
}
|
||||||
|
results.globalsImported++;
|
||||||
|
} catch (e) {
|
||||||
|
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return json(results);
|
||||||
|
};
|
||||||
|
|
@ -5,7 +5,6 @@
|
||||||
let header = $state(structuredClone(data.header.data));
|
let header = $state(structuredClone(data.header.data));
|
||||||
let footer = $state(structuredClone(data.footer.data));
|
let footer = $state(structuredClone(data.footer.data));
|
||||||
let colors = $state(structuredClone(data.colors.data));
|
let colors = $state(structuredClone(data.colors.data));
|
||||||
|
|
||||||
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
|
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
|
||||||
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
|
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue