Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(admin): local-only news CMS at /admin/news

nirholas948e891c342f
diff --git a/api/admin/news/[action].js b/api/admin/news/[action].js
new file mode 100644
index 000000000..3ec1a9582
--- /dev/null
+++ b/api/admin/news/[action].js
@@ -0,0 +1,175 @@
+// Local-only admin CRUD for the news/RSS feed.
+//
+// Endpoints:
+// GET /api/admin/news/list → list every item (incl. drafts)
+// POST /api/admin/news/save → create/update one item
+// POST /api/admin/news/delete → delete one item by id
+// POST /api/admin/news/upload-image → upload a cover image
+//
+// Local-only: refuses to run on Vercel (process.env.VERCEL === '1') or any
+// non-localhost host. The Vercel filesystem is read-only at runtime anyway,
+// so writes would fail — this just returns a clean 403 with an explanation.
+
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { json, error, method, cors, readJson, wrap } from '../../_lib/http.js';
+import { loadCuratedItems } from '../../_lib/rss-feed.js';
+import { writeAllPages } from '../../../scripts/build-news.mjs';
+
+const ROOT = path.resolve(fileURLToPath(import.meta.url), '..', '..', '..', '..');
+const ITEMS_FILE = path.join(ROOT, 'data', 'rss', 'items.json');
+const IMAGES_DIR = path.join(ROOT, 'public', 'news-images');
+
+const MAX_IMAGE_BYTES = 4 * 1024 * 1024;
+const ALLOWED_IMAGE_EXT = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg']);
+
+function refuseIfNotLocal(req, res) {
+ if (process.env.VERCEL === '1') {
+ error(res, 403, 'local_only', 'The news admin runs only in local dev (vite/vercel-dev). The Vercel runtime filesystem is read-only.');
+ return true;
+ }
+ const host = String(req.headers.host || '').toLowerCase();
+ const isLocalHost = host === '' || host.startsWith('localhost') || host.startsWith('127.0.0.1') || host.startsWith('0.0.0.0');
+ if (!isLocalHost && process.env.NODE_ENV === 'production') {
+ error(res, 403, 'local_only', `The news admin only accepts localhost requests in production builds (host=${host}).`);
+ return true;
+ }
+ return false;
+}
+
+async function readItemsFile() {
+ const raw = await readFile(ITEMS_FILE, 'utf8');
+ return JSON.parse(raw);
+}
+
+async function writeItemsFile(data) {
+ const out = JSON.stringify(data, null, 2) + '\n';
+ await writeFile(ITEMS_FILE, out, 'utf8');
+}
+
+// After items.json changes, regenerate every permalink page + the
+// listing + the sitemap routes file. Same code path the prebuild runs.
+async function regeneratePages() {
+ const items = await loadCuratedItems();
+ if (!items.length) return { written: 0, routes: 0 };
+ return writeAllPages(items);
+}
+
+function sanitizeImageFilename(name) {
+ const base = String(name || '').toLowerCase().replace(/[^a-z0-9._-]/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');
+ if (!base) return '';
+ const ext = base.split('.').pop();
+ if (!ALLOWED_IMAGE_EXT.has(ext)) return '';
+ return base.slice(0, 100);
+}
+
+const VALID_FIELDS = new Set([
+ 'id', 'slug', 'title', 'date', 'body_html', 'summary', 'author', 'tags',
+ 'image', 'image_alt', 'image_width', 'image_height',
+ 'og_title', 'og_description', 'external_link', 'link', 'published',
+]);
+
+function sanitizeItem(input) {
+ const out = {};
+ for (const [k, v] of Object.entries(input || {})) {
+ if (!VALID_FIELDS.has(k)) continue;
+ if (v === null || v === undefined || v === '') continue;
+ out[k] = v;
+ }
+ if (typeof out.id !== 'string' || !out.id.trim()) {
+ const err = new Error('id is required');
+ err.status = 400;
+ err.code = 'invalid_item';
+ throw err;
+ }
+ if (typeof out.title !== 'string' || !out.title.trim()) {
+ const err = new Error('title is required');
+ err.status = 400;
+ err.code = 'invalid_item';
+ throw err;
+ }
+ if (typeof out.date !== 'string' || Number.isNaN(new Date(out.date).getTime())) {
+ const err = new Error('date must be an ISO 8601 timestamp');
+ err.status = 400;
+ err.code = 'invalid_item';
+ throw err;
+ }
+ if (typeof out.body_html !== 'string' || !out.body_html.trim()) {
+ const err = new Error('body_html is required');
+ err.status = 400;
+ err.code = 'invalid_item';
+ throw err;
+ }
+ if (Array.isArray(out.tags)) {
+ out.tags = out.tags.filter((t) => typeof t === 'string' && t.trim()).map((t) => t.trim().toLowerCase());
+ }
+ if (out.image && !out.image_alt) {
+ const err = new Error('image_alt is required when image is set');
+ err.status = 400;
+ err.code = 'invalid_item';
+ throw err;
+ }
+ return out;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: false })) return;
+ if (refuseIfNotLocal(req, res)) return;
+
+ const action = String(req.query?.action || '').toLowerCase();
+
+ if (action === 'list') {
+ if (!method(req, res, ['GET'])) return;
+ const data = await readItemsFile();
+ const items = Array.isArray(data?.items) ? data.items : [];
+ return json(res, 200, { count: items.length, items });
+ }
+
+ if (action === 'save') {
+ if (!method(req, res, ['POST'])) return;
+ const body = await readJson(req);
+ const item = sanitizeItem(body?.item);
+ const data = await readItemsFile();
+ const items = Array.isArray(data.items) ? data.items : [];
+ const i = items.findIndex((e) => e.id === item.id);
+ if (i >= 0) items[i] = item;
+ else items.unshift(item);
+ data.items = items;
+ await writeItemsFile(data);
+ const stats = await regeneratePages();
+ return json(res, 200, { ok: true, item, rebuild: stats });
+ }
+
+ if (action === 'delete') {
+ if (!method(req, res, ['POST'])) return;
+ const body = await readJson(req);
+ const id = String(body?.id || '').trim();
+ if (!id) return error(res, 400, 'missing_id', 'id is required');
+ const data = await readItemsFile();
+ const items = Array.isArray(data.items) ? data.items : [];
+ const before = items.length;
+ data.items = items.filter((e) => e.id !== id);
+ if (data.items.length === before) return error(res, 404, 'not_found', `no item with id "${id}"`);
+ await writeItemsFile(data);
+ const stats = await regeneratePages();
+ return json(res, 200, { ok: true, removed: id, rebuild: stats });
+ }
+
+ if (action === 'upload-image') {
+ if (!method(req, res, ['POST'])) return;
+ const body = await readJson(req);
+ const filename = sanitizeImageFilename(body?.filename);
+ if (!filename) return error(res, 400, 'invalid_filename', 'filename must end in .jpg/.jpeg/.png/.webp/.gif/.svg');
+ const dataB64 = typeof body?.data_base64 === 'string' ? body.data_base64 : '';
+ if (!dataB64) return error(res, 400, 'missing_data', 'data_base64 is required');
+ const buf = Buffer.from(dataB64.replace(/^data:[^;]+;base64,/, ''), 'base64');
+ if (buf.length === 0) return error(res, 400, 'empty_payload', 'decoded image is 0 bytes');
+ if (buf.length > MAX_IMAGE_BYTES) return error(res, 413, 'too_large', `image exceeds ${MAX_IMAGE_BYTES} bytes`);
+ await mkdir(IMAGES_DIR, { recursive: true });
+ await writeFile(path.join(IMAGES_DIR, filename), buf);
+ return json(res, 200, { ok: true, path: `/news-images/${filename}`, bytes: buf.length });
+ }
+
+ return error(res, 404, 'unknown_action', `unknown action "${action}" (valid: list, save, delete, upload-image)`);
+});
diff --git a/public/admin/index.html b/public/admin/index.html
index 57c22e8f0..69cae1f2f 100644
--- a/public/admin/index.html
+++ b/public/admin/index.html
@@ -104,6 +104,7 @@
<span class="sidebar-brand">three.ws <span class="sidebar-badge">ADMIN</span></span>
<a class="nav-item active" data-tab="overview" onclick="switchTab('overview')">Overview</a>
<a class="nav-item" data-tab="users" onclick="switchTab('users')">Users</a>
+ <a class="nav-item" href="/admin/news">News</a>
<a class="nav-item" href="/dashboard/">Dashboard</a>
</nav>
<main class="main">
diff --git a/public/admin/news.html b/public/admin/news.html
new file mode 100644
index 000000000..e9b30f94e
--- /dev/null
+++ b/public/admin/news.html
@@ -0,0 +1,475 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8"/>
+<meta name="viewport" content="width=device-width,initial-scale=1"/>
+<title>News &middot; Admin &middot; three.ws</title>
+<link rel="icon" href="/favicon.ico"/>
+<style>
+:root { color-scheme: dark; --accent: #6a5cff; --accent2: #ff5ca8; --ok: #14f195; --warn: #ffa64d; --err: #ff5c5c; }
+* { box-sizing: border-box; margin: 0; padding: 0; }
+body { font: 14px/1.5 -apple-system,system-ui,'Segoe UI',sans-serif; background: #080814; color: #ccc; min-height: 100vh; }
+a { color: #9a8cff; text-decoration: none; }
+a:hover { text-decoration: underline; }
+.layout { display: flex; min-height: 100vh; }
+.sidebar { width: 200px; background: #0d0d1a; border-right: 1px solid #1e1e2e; padding: 20px 0; flex-shrink: 0; }
+.sidebar-brand { font-size: 11px; letter-spacing: .1em; text-transform: uppercase; color: var(--accent); padding: 0 20px 20px; display: block; }
+.sidebar-badge { display: inline-block; background: rgba(255,70,70,.15); color: #ff6060; font-size: 10px; padding: 1px 6px; border-radius: 4px; margin-left: 6px; }
+.nav-item { display: block; padding: 9px 20px; color: #888; cursor: pointer; border-left: 2px solid transparent; font-size: 13px; }
+.nav-item:hover { color: #eee; background: #12121e; }
+.nav-item.active { color: #eee; border-left-color: var(--accent); background: #12121e; }
+.main { flex: 1; padding: 28px 32px; overflow-y: auto; }
+.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
+.page-title { font-size: 20px; color: #eee; font-weight: 600; }
+.btn { display: inline-flex; align-items: center; gap: 6px; padding: 7px 14px; border-radius: 6px; border: 1px solid #2a2a3e; background: #14141e; color: #ccc; font-size: 13px; cursor: pointer; transition: all .12s; font-family: inherit; }
+.btn:hover { background: #1c1c2a; border-color: #3a3a4e; color: #eee; }
+.btn-primary { background: var(--accent); border-color: var(--accent); color: #fff; }
+.btn-primary:hover { background: #5848e8; border-color: #5848e8; color: #fff; }
+.btn-danger { color: #ff8c8c; border-color: rgba(255,92,92,.3); }
+.btn-danger:hover { background: rgba(255,92,92,.1); color: #ffb0b0; border-color: rgba(255,92,92,.5); }
+.btn[disabled] { opacity: .5; cursor: not-allowed; }
+.workspace { display: grid; grid-template-columns: 340px 1fr; gap: 24px; align-items: start; }
+@media (max-width: 1000px) { .workspace { grid-template-columns: 1fr; } }
+.panel { background: #0f0f1a; border: 1px solid #1e1e2e; border-radius: 10px; }
+.panel-head { padding: 12px 16px; border-bottom: 1px solid #1e1e2e; display: flex; align-items: center; justify-content: space-between; }
+.panel-title { font-size: 13px; color: #eee; font-weight: 500; }
+.panel-body { padding: 0; }
+.list-empty { padding: 24px; color: #666; text-align: center; font-size: 13px; }
+.post-row { padding: 12px 16px; border-bottom: 1px solid #1a1a26; cursor: pointer; transition: background .1s; }
+.post-row:last-child { border-bottom: none; }
+.post-row:hover { background: #14141e; }
+.post-row.active { background: #1a1530; border-left: 2px solid var(--accent); padding-left: 14px; }
+.post-row-title { font-size: 13px; color: #eee; font-weight: 500; margin-bottom: 4px; line-height: 1.35; }
+.post-row-meta { font-size: 11px; color: #666; display: flex; gap: 8px; align-items: center; }
+.dot { width: 5px; height: 5px; border-radius: 50%; background: var(--ok); display: inline-block; }
+.dot.draft { background: var(--warn); }
+.editor-form { padding: 20px; }
+.field { margin-bottom: 16px; }
+.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
+label { display: block; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: #777; margin-bottom: 6px; font-weight: 500; }
+label .hint { text-transform: none; letter-spacing: 0; color: #555; font-weight: 400; margin-left: 6px; }
+input[type=text], input[type=number], input[type=datetime-local], textarea, select {
+\twidth: 100%; padding: 8px 10px; background: #0a0a14; border: 1px solid #1e1e2e; border-radius: 6px;
+\tcolor: #eee; font: inherit; font-size: 13px; font-family: inherit;
+}
+input:focus, textarea:focus, select:focus { outline: none; border-color: var(--accent); }
+textarea { resize: vertical; min-height: 220px; font-family: 'SF Mono', Menlo, monospace; line-height: 1.55; }
+.toggle { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
+.toggle input { width: auto; }
+.body-area { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
+@media (max-width: 700px) { .body-area { grid-template-columns: 1fr; } }
+.preview { padding: 14px 16px; background: #0a0a14; border: 1px solid #1e1e2e; border-radius: 6px; min-height: 220px;
+\tcolor: #ddd; font-size: 14px; line-height: 1.65; overflow-y: auto; max-height: 600px; }
+.preview p { margin: 0 0 12px; }
+.preview a { color: #ffd76a; border-bottom: 1px solid rgba(255,215,106,.3); }
+.preview h2 { font-size: 20px; margin: 24px 0 10px; color: #fff; }
+.preview h3 { font-size: 16px; margin: 18px 0 8px; color: #fff; }
+.preview ul, .preview ol { padding-left: 20px; margin: 0 0 12px; }
+.preview code { background: #1a1a26; padding: 1px 6px; border-radius: 3px; font-size: .92em; }
+.preview pre { background: #1a1a26; padding: 10px; border-radius: 6px; overflow-x: auto; }
+.preview blockquote { border-left: 3px solid #ffd76a; padding: 6px 14px; background: rgba(255,215,106,.04); color: #aaa; margin: 12px 0; }
+.image-controls { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
+.image-preview { width: 80px; height: 50px; border-radius: 4px; background: #0a0a14; border: 1px solid #1e1e2e; object-fit: cover; }
+.actions { display: flex; gap: 10px; justify-content: space-between; padding-top: 14px; border-top: 1px solid #1e1e2e; margin-top: 22px; }
+.actions-left, .actions-right { display: flex; gap: 8px; }
+.toast { position: fixed; bottom: 20px; right: 20px; padding: 10px 14px; border-radius: 8px; font-size: 13px; z-index: 100;
+\tanimation: toast-in .2s ease; box-shadow: 0 4px 16px rgba(0,0,0,.4); }
+.toast-ok { background: rgba(20,241,149,.12); border: 1px solid rgba(20,241,149,.3); color: var(--ok); }
+.toast-err { background: rgba(255,92,92,.12); border: 1px solid rgba(255,92,92,.3); color: var(--err); }
+@keyframes toast-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
+.empty-state { padding: 60px 20px; text-align: center; color: #666; }
+.empty-state h2 { color: #ccc; font-weight: 500; margin-bottom: 8px; }
+.kbd { background: #14141e; border: 1px solid #2a2a3e; padding: 1px 6px; border-radius: 4px; font-size: 11px; font-family: 'SF Mono', Menlo, monospace; color: #aaa; }
+</style>
+</head>
+<body>
+<div class="layout">
+\t<aside class="sidebar">
+\t\t<span class="sidebar-brand">three.ws admin</span>
+\t\t<a class="nav-item" href="/admin">Overview</a>
+\t\t<a class="nav-item active" href="/admin/news">News<span class="sidebar-badge" id="post-count" style="display:none"></span></a>
+\t\t<a class="nav-item" href="/sitemap" target="_blank">Sitemap &uarr;</a>
+\t\t<a class="nav-item" href="/news" target="_blank">View live &uarr;</a>
+\t\t<a class="nav-item" href="/rss/announcements.xml" target="_blank">RSS feed &uarr;</a>
+\t</aside>
+\t<main class="main">
+\t\t<div class="page-header">
+\t\t\t<div>
+\t\t\t\t<h1 class="page-title">News &amp; Announcements</h1>
+\t\t\t\t<p style="font-size:12px;color:#666;margin-top:4px">Local-only admin &middot; edits write to <span class="kbd">data/rss/items.json</span> + regenerate <span class="kbd">public/news/</span></p>
+\t\t\t</div>
+\t\t\t<button class="btn btn-primary" id="new-btn">+ New post</button>
+\t\t</div>
+\t\t<div class="workspace">
+\t\t\t<div class="panel">
+\t\t\t\t<div class="panel-head">
+\t\t\t\t\t<span class="panel-title">All posts</span>
+\t\t\t\t\t<span style="font-size:11px;color:#666" id="list-meta"></span>
+\t\t\t\t</div>
+\t\t\t\t<div class="panel-body" id="post-list"></div>
+\t\t\t</div>
+\t\t\t<div class="panel">
+\t\t\t\t<div class="panel-head">
+\t\t\t\t\t<span class="panel-title" id="editor-title">Select a post or create a new one</span>
+\t\t\t\t</div>
+\t\t\t\t<div class="panel-body" id="editor-pane">
+\t\t\t\t\t<div class="empty-state">
+\t\t\t\t\t\t<h2>Nothing selected</h2>
+\t\t\t\t\t\t<p>Click a post on the left to edit, or hit <span class="kbd">+ New post</span> to start one.</p>
+\t\t\t\t\t</div>
+\t\t\t\t</div>
+\t\t\t</div>
+\t\t</div>
+\t</main>
+</div>
+<script>
+const API = '/api/admin/news';
+let posts = [];
+let activeId = null;
+let dirty = false;
+
+function $(sel) { return document.querySelector(sel); }
+function fmt(iso) {
+\ttry { return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); }
+\tcatch { return iso; }
+}
+function escapeHtml(s) {
+\treturn String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
+}
+function escapeAttr(s) { return escapeHtml(s); }
+function toast(msg, kind = 'ok') {
+\tconst el = document.createElement('div');
+\tel.className = 'toast toast-' + (kind === 'err' ? 'err' : 'ok');
+\tel.textContent = msg;
+\tdocument.body.appendChild(el);
+\tsetTimeout(() => el.remove(), 3000);
+}
+async function api(action, body) {
+\tconst opts = { method: body ? 'POST' : 'GET' };
+\tif (body) { opts.headers = { 'content-type': 'application/json' }; opts.body = JSON.stringify(body); }
+\tconst r = await fetch(`${API}/${action}`, opts);
+\tconst j = await r.json();
+\tif (!r.ok) throw new Error(j?.error_description || j?.error || 'request failed');
+\treturn j;
+}
+
+async function refresh() {
+\ttry {
+\t\tconst { items } = await api('list');
+\t\tposts = items.slice().sort((a, b) => new Date(b.date) - new Date(a.date));
+\t\trenderList();
+\t} catch (e) {
+\t\ttoast('Load failed: ' + e.message, 'err');
+\t}
+}
+
+function renderList() {
+\t$('#list-meta').textContent = `${posts.length} item${posts.length === 1 ? '' : 's'}`;
+\tconst badge = $('#post-count');
+\tbadge.textContent = posts.length;
+\tbadge.style.display = posts.length ? 'inline-block' : 'none';
+\tbadge.style.background = 'rgba(106,92,255,.18)';
+\tbadge.style.color = '#9a8cff';
+\tif (!posts.length) {
+\t\t$('#post-list').innerHTML = '<div class="list-empty">No posts yet. Click <strong>+ New post</strong> to start.</div>';
+\t\treturn;
+\t}
+\t$('#post-list').innerHTML = posts.map((p) => `
+\t\t<div class="post-row ${p.id === activeId ? 'active' : ''}" data-id="${escapeAttr(p.id)}">
+\t\t\t<div class="post-row-title">${escapeHtml(p.title)}</div>
+\t\t\t<div class="post-row-meta">
+\t\t\t\t<span class="dot ${p.published === false ? 'draft' : ''}"></span>
+\t\t\t\t<span>${escapeHtml(fmt(p.date))}</span>
+\t\t\t\t${p.image ? '<span>&middot; image</span>' : ''}
+\t\t\t\t${p.published === false ? '<span>&middot; draft</span>' : ''}
+\t\t\t</div>
+\t\t</div>
+\t`).join('');
+\t$('#post-list').querySelectorAll('.post-row').forEach((row) => {
+\t\trow.addEventListener('click', () => {
+\t\t\tif (dirty && !confirm('Discard unsaved changes?')) return;
+\t\t\tloadEditor(row.dataset.id);
+\t\t});
+\t});
+}
+
+function blankPost() {
+\tconst now = new Date();
+\treturn {
+\t\tid: 'post-' + Date.now().toString(36),
+\t\tslug: '',
+\t\ttitle: '',
+\t\tdate: now.toISOString(),
+\t\tauthor: 'three.ws',
+\t\ttags: [],
+\t\tsummary: '',
+\t\tbody_html: '<p></p>',
+\t\timage: '',
+\t\timage_alt: '',
+\t\timage_width: '',
+\t\timage_height: '',
+\t\tog_title: '',
+\t\tog_description: '',
+\t\texternal_link: '',
+\t\tpublished: true,
+\t};
+}
+
+function loadEditor(id) {
+\tconst post = id === null ? blankPost() : posts.find((p) => p.id === id);
+\tif (!post) return;
+\tactiveId = id;
+\tdirty = false;
+\trenderList();
+\trenderEditor(post);
+}
+
+function renderEditor(p) {
+\t$('#editor-title').textContent = activeId === null ? 'New post' : `Editing: ${p.title || p.id}`;
+\tconst dateLocal = (() => {
+\t\tconst d = new Date(p.date);
+\t\tif (Number.isNaN(d.getTime())) return '';
+\t\tconst pad = (n) => String(n).padStart(2, '0');
+\t\treturn `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
+\t})();
+\t$('#editor-pane').innerHTML = `
+\t\t<form class="editor-form" id="editor-form">
+\t\t\t<div class="field-row">
+\t\t\t\t<div class="field">
+\t\t\t\t\t<label for="f-id">ID <span class="hint">stable, kebab-case</span></label>
+\t\t\t\t\t<input id="f-id" name="id" value="${escapeAttr(p.id)}" ${activeId !== null ? 'readonly' : ''}/>
+\t\t\t\t</div>
+\t\t\t\t<div class="field">
+\t\t\t\t\t<label for="f-slug">Slug <span class="hint">auto from id if blank</span></label>
+\t\t\t\t\t<input id="f-slug" name="slug" value="${escapeAttr(p.slug || '')}" placeholder="e.g. live-on-alibaba-cloud"/>
+\t\t\t\t</div>
+\t\t\t</div>
+\t\t\t<div class="field">
+\t\t\t\t<label for="f-title">Title</label>
+\t\t\t\t<input id="f-title" name="title" value="${escapeAttr(p.title)}" required/>
+\t\t\t</div>
+\t\t\t<div class="field-row">
+\t\t\t\t<div class="field">
+\t\t\t\t\t<label for="f-date">Date</label>
+\t\t\t\t\t<input id="f-date" type="datetime-local" name="date" value="${escapeAttr(dateLocal)}" required/>
+\t\t\t\t</div>
+\t\t\t\t<div class="field">
+\t\t\t\t\t<label for="f-author">Author</label>
+\t\t\t\t\t<input id="f-author" name="author" value="${escapeAttr(p.author || 'three.ws')}"/>
+\t\t\t\t</div>
+\t\t\t</div>
+\t\t\t<div class="field">
+\t\t\t\t<label for="f-tags">Tags <span class="hint">comma-separated, lowercase</span></label>
+\t\t\t\t<input id="f-tags" name="tags" value="${escapeAttr((p.tags || []).join(', '))}" placeholder="launch, integration, x402"/>
+\t\t\t</div>
+\t\t\t<div class="field">
+\t\t\t\t<label for="f-summary">Summary <span class="hint">&le;280 chars; auto from body if blank</span></label>
+\t\t\t\t<input id="f-summary" name="summary" value="${escapeAttr(p.summary || '')}" maxlength="280"/>
+\t\t\t</div>
+\t\t\t<div class="field">
+\t\t\t\t<label>Cover image <span class="hint">stored under /news-images/</span></label>
+\t\t\t\t<div class="image-controls">
+\t\t\t\t\t${p.image ? `<img class="image-preview" src="${escapeAttr(p.image)}" alt=""/>` : '<div class="image-preview" id="image-placeholder"></div>'}
+\t\t\t\t\t<input id="f-image" name="image" value="${escapeAttr(p.image || '')}" placeholder="/news-images/cover.jpg or https://..." style="flex:1;min-width:200px"/>
+\t\t\t\t\t<input type="file" id="image-file" accept="image/*" style="display:none"/>
+\t\t\t\t\t<button type="button" class="btn" id="upload-btn">Upload&hellip;</button>
+\t\t\t\t</div>
+\t\t\t</div>
+\t\t\t<div class="field-row">
+\t\t\t\t<div class="field">
+\t\t\t\t\t<label for="f-image-alt">Image alt <span class="hint">required if image set</span></label>
+\t\t\t\t\t<input id="f-image-alt" name="image_alt" value="${escapeAttr(p.image_alt || '')}"/>
+\t\t\t\t</div>
+\t\t\t\t<div class="field">
+\t\t\t\t\t<label>Image dimensions</label>
+\t\t\t\t\t<div style="display:flex;gap:8px">
+\t\t\t\t\t\t<input id="f-image-width" type="number" min="0" name="image_width" value="${escapeAttr(p.image_width || '')}" placeholder="W (px)"/>
+\t\t\t\t\t\t<input id="f-image-height" type="number" min="0" name="image_height" value="${escapeAttr(p.image_height || '')}" placeholder="H (px)"/>
+\t\t\t\t\t</div>
+\t\t\t\t</div>
+\t\t\t</div>
+\t\t\t<div class="field">
+\t\t\t\t<label for="f-body">Body (HTML)</label>
+\t\t\t\t<div class="body-area">
+\t\t\t\t\t<textarea id="f-body" name="body_html">${escapeHtml(p.body_html || '')}</textarea>
+\t\t\t\t\t<div class="preview" id="f-preview"></div>
+\t\t\t\t</div>
+\t\t\t</div>
+\t\t\t<details style="margin-bottom:16px">
+\t\t\t\t<summary style="cursor:pointer;font-size:13px;color:#888;margin-bottom:10px">Advanced</summary>
+\t\t\t\t<div class="field">
+\t\t\t\t\t<label for="f-external">External link <span class="hint">e.g. original X post URL</span></label>
+\t\t\t\t\t<input id="f-external" name="external_link" value="${escapeAttr(p.external_link || p.link || '')}" placeholder="https://x.com/trythreews/status/..."/>
+\t\t\t\t</div>
+\t\t\t\t<div class="field-row">
+\t\t\t\t\t<div class="field">
+\t\t\t\t\t\t<label for="f-og-title">OG title override</label>
+\t\t\t\t\t\t<input id="f-og-title" name="og_title" value="${escapeAttr(p.og_title || '')}"/>
+\t\t\t\t\t</div>
+\t\t\t\t\t<div class="field">
+\t\t\t\t\t\t<label for="f-og-desc">OG description override</label>
+\t\t\t\t\t\t<input id="f-og-desc" name="og_description" value="${escapeAttr(p.og_description || '')}"/>
+\t\t\t\t\t</div>
+\t\t\t\t</div>
+\t\t\t</details>
+\t\t\t<div class="field">
+\t\t\t\t<label class="toggle"><input id="f-published" type="checkbox" ${p.published !== false ? 'checked' : ''}/> <span>Published</span></label>
+\t\t\t</div>
+\t\t\t<div class="actions">
+\t\t\t\t<div class="actions-left">
+\t\t\t\t\t${activeId !== null ? '<button type="button" class="btn btn-danger" id="delete-btn">Delete</button>' : ''}
+\t\t\t\t</div>
+\t\t\t\t<div class="actions-right">
+\t\t\t\t\t<button type="button" class="btn" id="cancel-btn">Cancel</button>
+\t\t\t\t\t<button type="submit" class="btn btn-primary" id="save-btn">Save</button>
+\t\t\t\t</div>
+\t\t\t</div>
+\t\t</form>
+\t`;
+\tupdatePreview();
+\twireEditor();
+}
+
+function updatePreview() {
+\tconst body = $('#f-body');
+\tconst pre = $('#f-preview');
+\tif (!body || !pre) return;
+\tpre.innerHTML = body.value;
+}
+
+function wireEditor() {
+\tconst form = $('#editor-form');
+\tform.addEventListener('input', () => { dirty = true; updatePreview(); });
+\t$('#cancel-btn').addEventListener('click', () => {
+\t\tif (dirty && !confirm('Discard unsaved changes?')) return;
+\t\tactiveId = null;
+\t\tdirty = false;
+\t\trenderEditorEmpty();
+\t\trenderList();
+\t});
+\tform.addEventListener('submit', async (e) => {
+\t\te.preventDefault();
+\t\tawait save();
+\t});
+\tconst del = $('#delete-btn');
+\tif (del) {
+\t\tdel.addEventListener('click', async () => {
+\t\t\tif (!confirm(`Delete "${$('#f-title').value}"? This cannot be undone.`)) return;
+\t\t\tawait deletePost();
+\t\t});
+\t}
+\t$('#upload-btn').addEventListener('click', () => $('#image-file').click());
+\t$('#image-file').addEventListener('change', async (e) => {
+\t\tconst f = e.target.files[0];
+\t\tif (!f) return;
+\t\tawait uploadImage(f);
+\t});
+}
+
+function renderEditorEmpty() {
+\t$('#editor-title').textContent = 'Select a post or create a new one';
+\t$('#editor-pane').innerHTML = `<div class="empty-state"><h2>Nothing selected</h2><p>Click a post on the left to edit, or hit <span class="kbd">+ New post</span> to start one.</p></div>`;
+}
+
+function readForm() {
+\tconst tags = $('#f-tags').value.split(',').map((t) => t.trim().toLowerCase()).filter(Boolean);
+\tconst dateLocal = $('#f-date').value;
+\tconst date = dateLocal ? new Date(dateLocal).toISOString() : new Date().toISOString();
+\tconst wInt = parseInt($('#f-image-width').value, 10);
+\tconst hInt = parseInt($('#f-image-height').value, 10);
+\tconst item = {
+\t\tid: $('#f-id').value.trim(),
+\t\tslug: $('#f-slug').value.trim(),
+\t\ttitle: $('#f-title').value.trim(),
+\t\tdate,
+\t\tauthor: $('#f-author').value.trim(),
+\t\ttags,
+\t\tsummary: $('#f-summary').value.trim(),
+\t\tbody_html: $('#f-body').value,
+\t\timage: $('#f-image').value.trim(),
+\t\timage_alt: $('#f-image-alt').value.trim(),
+\t\timage_width: Number.isFinite(wInt) ? wInt : '',
+\t\timage_height: Number.isFinite(hInt) ? hInt : '',
+\t\tog_title: $('#f-og-title').value.trim(),
+\t\tog_description: $('#f-og-desc').value.trim(),
+\t\texternal_link: $('#f-external').value.trim(),
+\t\tpublished: $('#f-published').checked,
+\t};
+\t// Strip empty optional fields so JSON stays clean
+\tfor (const k of Object.keys(item)) if (item[k] === '' || item[k] == null) delete item[k];
+\t// id, title, date, body_html are required — re-add if stripped above
+\tif (!item.id) item.id = $('#f-id').value.trim();
+\tif (!item.body_html) item.body_html = $('#f-body').value;
+\titem.published = $('#f-published').checked;
+\treturn item;
+}
+
+async function save() {
+\tconst btn = $('#save-btn');
+\tbtn.disabled = true;
+\tbtn.textContent = 'Saving…';
+\ttry {
+\t\tconst item = readForm();
+\t\tconst { item: saved, rebuild } = await api('save', { item });
+\t\ttoast(`Saved "${saved.title}" (${rebuild.written} page${rebuild.written === 1 ? '' : 's'} rebuilt)`);
+\t\tdirty = false;
+\t\tactiveId = saved.id;
+\t\tawait refresh();
+\t\tloadEditor(saved.id);
+\t} catch (e) {
+\t\ttoast('Save failed: ' + e.message, 'err');
+\t} finally {
+\t\tbtn.disabled = false;
+\t\tbtn.textContent = 'Save';
+\t}
+}
+
+async function deletePost() {
+\tconst id = $('#f-id').value.trim();
+\ttry {
+\t\tconst { rebuild } = await api('delete', { id });
+\t\ttoast(`Deleted (${rebuild.written} page${rebuild.written === 1 ? '' : 's'} rebuilt)`);
+\t\tactiveId = null;
+\t\tdirty = false;
+\t\tawait refresh();
+\t\trenderEditorEmpty();
+\t} catch (e) {
+\t\ttoast('Delete failed: ' + e.message, 'err');
+\t}
+}
+
+async function uploadImage(file) {
+\tif (file.size > 4 * 1024 * 1024) { toast('Image too large (max 4 MB)', 'err'); return; }
+\tconst reader = new FileReader();
+\treader.onload = async () => {
+\t\ttry {
+\t\t\tconst { path } = await api('upload-image', { filename: file.name, data_base64: reader.result });
+\t\t\t$('#f-image').value = path;
+\t\t\tdirty = true;
+\t\t\t// Probe image to auto-fill width/height
+\t\t\tconst img = new Image();
+\t\t\timg.onload = () => {
+\t\t\t\tif (!$('#f-image-width').value) $('#f-image-width').value = img.naturalWidth;
+\t\t\t\tif (!$('#f-image-height').value) $('#f-image-height').value = img.naturalHeight;
+\t\t\t};
+\t\t\timg.src = path;
+\t\t\ttoast(`Uploaded ${file.name}`);
+\t\t} catch (e) {
+\t\t\ttoast('Upload failed: ' + e.message, 'err');
+\t\t}
+\t};
+\treader.readAsDataURL(file);
+}
+
+$('#new-btn').addEventListener('click', () => {
+\tif (dirty && !confirm('Discard unsaved changes?')) return;
+\tloadEditor(null);
+});
+window.addEventListener('beforeunload', (e) => {
+\tif (dirty) { e.preventDefault(); e.returnValue = ''; }
+});
+
+refresh();
+</script>
+</body>
+</html>
diff --git a/scripts/build-news.mjs b/scripts/build-news.mjs
index fac781b0f..92d7a2daa 100644
--- a/scripts/build-news.mjs
+++ b/scripts/build-news.mjs
@@ -349,24 +349,23 @@ async function ensureDir(dir) {
await mkdir(dir, { recursive: true });
}
-async function main() {
- const items = await loadCuratedItems();
- if (!items.length) {
- console.warn('No curated items found — skipping news page generation.');
- return;
- }
- await ensureDir(OUT_DIR);
- await ensureDir(path.dirname(ROUTES_FILE));
+// Write all permalink HTML pages + listing index + sitemap routes file
+// from a pre-loaded items array. Exported so the admin handler can
+// regenerate output on save without spawning a subprocess.
+export async function writeAllPages(items, { outDir = OUT_DIR, routesFile = ROUTES_FILE } = {}) {
+ if (!items.length) return { written: 0, routes: 0 };
+ await ensureDir(outDir);
+ await ensureDir(path.dirname(routesFile));
let written = 0;
for (const item of items) {
const html = renderArticlePage(item);
- await writeFile(path.join(OUT_DIR, `${item.slug}.html`), html, 'utf8');
+ await writeFile(path.join(outDir, `${item.slug}.html`), html, 'utf8');
written++;
}
const indexHtml = renderIndexPage(items);
- await writeFile(path.join(OUT_DIR, 'index.html'), indexHtml, 'utf8');
+ await writeFile(path.join(outDir, 'index.html'), indexHtml, 'utf8');
const routes = [
{
@@ -386,13 +385,29 @@ async function main() {
changefreq: 'yearly',
})),
];
- await writeFile(ROUTES_FILE, JSON.stringify(routes, null, 2) + '\n', 'utf8');
+ await writeFile(routesFile, JSON.stringify(routes, null, 2) + '\n', 'utf8');
+
+ return { written, routes: routes.length };
+}
+export { renderArticlePage, renderIndexPage };
+
+async function main() {
+ const items = await loadCuratedItems();
+ if (!items.length) {
+ console.warn('No curated items found — skipping news page generation.');
+ return;
+ }
+ const { written, routes } = await writeAllPages(items);
console.log(`Wrote ${written} article page(s) + index to ${OUT_DIR}`);
- console.log(`Wrote ${routes.length} route(s) to ${ROUTES_FILE}`);
+ console.log(`Wrote ${routes} route(s) to ${ROUTES_FILE}`);
}
-main().catch((err) => {
- console.error('[build-news] failed:', err);
- process.exit(1);
-});
+// Run main() only when invoked as a script (preserves CLI behavior;
+// admin handler imports writeAllPages without triggering this).
+if (import.meta.url === `file://${process.argv[1]}`) {
+ main().catch((err) => {
+ console.error('[build-news] failed:', err);
+ process.exit(1);
+ });
+}