Add per-page search metadata, link previews and a sitemap
Page requests now go through the API (routes/pages.js), which fills the built index.html in for that path before the app loads: title, description, preview image, canonical URL, and structured data (Organization, Event, BlogPosting). Shared links preview the page itself. Unlisted records are noindex; missing ones return 404. /sitemap.xml lists every public, listed page. site.json is the one place for the site's name, address, default description and preview image, and each static page's title and intro, which the pages now read too. Indexing is switched on: robots.txt allows all but /admin and /api and names the sitemap. The browser tab title follows the page. nginx setup, with a fallback to the plain page if the API is down, is in docs/seo.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
71a470b66f
commit
64cb2ec56a
21 changed files with 777 additions and 29 deletions
|
|
@ -23,6 +23,7 @@ import history from "./routes/history.js";
|
|||
import home from "./routes/home.js";
|
||||
import directory from "./routes/directory.js";
|
||||
import blog from "./routes/blog.js";
|
||||
import pages from "./routes/pages.js";
|
||||
import feedback from "./routes/feedback.js";
|
||||
import auth from "./routes/auth.js";
|
||||
import admin from "./routes/admin.js";
|
||||
|
|
@ -102,6 +103,10 @@ app.use(
|
|||
}),
|
||||
);
|
||||
|
||||
// Last: every other GET that isn't /api is a page of the site, sent
|
||||
// with its metadata filled in (routes/pages.js).
|
||||
app.route("/", pages);
|
||||
|
||||
startSessionSweeper(db);
|
||||
|
||||
app.notFound((c) => c.json({ error: "Not found" }, 404));
|
||||
|
|
|
|||
447
server/src/pageMeta.js
Normal file
447
server/src/pageMeta.js
Normal file
|
|
@ -0,0 +1,447 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PAGE METADATA
|
||||
|
||||
What a page's HTML should say about it before any JavaScript
|
||||
runs: title, description, preview image, canonical address,
|
||||
whether search engines may index it, and structured data. Link
|
||||
previews (Facebook, iMessage, Slack, Discord, X) never run the
|
||||
app's JavaScript, so this is the only way a shared event shows
|
||||
the event rather than the site's defaults.
|
||||
|
||||
routes/pages.js puts it into the built index.html for each
|
||||
request, and serves /sitemap.xml from the same rules.
|
||||
|
||||
── Where it comes from ──
|
||||
/site.json (SITE_CONFIG): the site's name, address, default
|
||||
description and image, and each static page's title and
|
||||
description. The pages read the same file for their heading and
|
||||
intro, so the two can't drift.
|
||||
The database: records' names, taglines, first paragraphs and
|
||||
images. A blank site description falls back to the front page's
|
||||
subhead.
|
||||
|
||||
── Rules ──
|
||||
published, listed indexed, in the sitemap
|
||||
published, unlisted noindex: reachable by link, not by search
|
||||
unpublished, missing 404 and noindex, with the site defaults
|
||||
/admin noindex
|
||||
|
||||
Image paths resolve like src/lib/media.ts does: a bare filename
|
||||
lives in that record kind's public/ directory, anything starting
|
||||
with / or a scheme is used as it is. Keep DIRS in step with it.
|
||||
An SVG isn't used as a preview image (the big sites won't show
|
||||
one), so it falls back to the site default.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { loadBlocks, paragraphs } from "./shape.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const SITE_CONFIG = path.resolve(process.env.SITE_CONFIG ?? path.join(here, "../../site.json"));
|
||||
|
||||
const DESCRIPTION_CHARS = 160;
|
||||
|
||||
/* Where a bare filename lives, per kind. Mirrors src/lib/media.ts. */
|
||||
const DIRS = {
|
||||
person: "/people",
|
||||
eventLogo: "/event-logos",
|
||||
eventBackground: "/event-backgrounds",
|
||||
organization: "/org-logos",
|
||||
team: "/team-logos",
|
||||
award: "/award-logos",
|
||||
blog: "/blog",
|
||||
};
|
||||
|
||||
/* ── site.json, reread when it changes ─────────────────────── */
|
||||
|
||||
let cached = { mtime: 0, site: null };
|
||||
|
||||
export function loadSite() {
|
||||
const mtime = statSync(SITE_CONFIG).mtimeMs;
|
||||
if (cached.site && cached.mtime === mtime) return cached.site;
|
||||
const site = JSON.parse(readFileSync(SITE_CONFIG, "utf8"));
|
||||
cached = { mtime, site };
|
||||
return site;
|
||||
}
|
||||
|
||||
const origin = (site) => (site.url ?? "").replace(/\/$/, "");
|
||||
|
||||
/* ── Helpers ───────────────────────────────────────────────── */
|
||||
|
||||
/* Text as a description: the formatting marks content blocks allow
|
||||
(**bold**, *italic*, [text](url)) taken out, whitespace folded,
|
||||
cut on a word near DESCRIPTION_CHARS. */
|
||||
export function plainText(text) {
|
||||
if (!text) return null;
|
||||
const flat = String(text)
|
||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
||||
.replace(/\*\*(.+?)\*\*/g, "$1")
|
||||
.replace(/\*(.+?)\*/g, "$1")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
if (!flat) return null;
|
||||
if (flat.length <= DESCRIPTION_CHARS) return flat;
|
||||
const cut = flat.slice(0, DESCRIPTION_CHARS);
|
||||
const space = cut.lastIndexOf(" ");
|
||||
return `${(space > DESCRIPTION_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
|
||||
}
|
||||
|
||||
const first = (...values) => values.find((v) => v != null && String(v).trim() !== "") ?? null;
|
||||
|
||||
function imageUrl(site, file, kind) {
|
||||
if (!file || /\.svg(\?|#|$)/i.test(file)) return null;
|
||||
// A bare filename is in that kind's directory, or at the site's
|
||||
// root for the site's own default (kind null).
|
||||
const pathOrUrl = /^(https?:|\/)/.test(file) ? file : kind ? `${DIRS[kind]}/${file}` : `/${file}`;
|
||||
return /^https?:/.test(pathOrUrl) ? pathOrUrl : `${origin(site)}${pathOrUrl}`;
|
||||
}
|
||||
|
||||
function firstParagraph(db, ownerKind, id, slot) {
|
||||
return paragraphs(loadBlocks(db, ownerKind, [id], slot).get(id) ?? [])[0] ?? null;
|
||||
}
|
||||
|
||||
/* ── One page ──────────────────────────────────────────────── */
|
||||
|
||||
const ORG_ROUTES = { region: "/regions", chapter: "/chapters", partner: "/partners", national: "/organizations" };
|
||||
|
||||
function defaults(site, db, pathname) {
|
||||
const home = db.prepare(`SELECT headline, subhead FROM front_page WHERE id = 'home'`).get();
|
||||
return {
|
||||
status: 200,
|
||||
title: site.title,
|
||||
description: plainText(first(site.description, home?.subhead)),
|
||||
image: imageUrl(site, site.openGraph?.image, null),
|
||||
canonical: `${origin(site)}${pathname === "/" ? "/" : pathname}`,
|
||||
type: "website",
|
||||
noindex: false,
|
||||
jsonLd: null,
|
||||
};
|
||||
}
|
||||
|
||||
function notFound(meta) {
|
||||
return { ...meta, status: 404, noindex: true, title: `Page not found | ${meta.title}` };
|
||||
}
|
||||
|
||||
/* Title for a record page: "Name | Site". */
|
||||
const titled = (site, name) => `${name} | ${site.title}`;
|
||||
|
||||
function eventMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM v_events WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
|
||||
const when = [row.date_label, row.location_label].filter(Boolean).join(" · ");
|
||||
const image =
|
||||
imageUrl(site, row.card_image, "eventBackground") ??
|
||||
imageUrl(site, row.event_logo, "eventLogo") ??
|
||||
imageUrl(site, row.effective_org_logo, "organization") ??
|
||||
meta.image;
|
||||
const description = plainText(first(row.tagline, firstParagraph(db, "event", id, "card"), when, row.theme));
|
||||
|
||||
const place = row.is_online
|
||||
? { "@type": "VirtualLocation", url: meta.canonical }
|
||||
: {
|
||||
"@type": "Place",
|
||||
name: first(row.venue, row.location_label, row.locality),
|
||||
address: {
|
||||
"@type": "PostalAddress",
|
||||
streetAddress: row.address ?? undefined,
|
||||
addressLocality: row.locality ?? undefined,
|
||||
addressRegion: row.state_code ?? undefined,
|
||||
addressCountry: row.country ?? undefined,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.title),
|
||||
description,
|
||||
image,
|
||||
noindex: row.is_listed !== 1,
|
||||
jsonLd: row.starts_on
|
||||
? {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Event",
|
||||
name: row.title,
|
||||
description: description ?? undefined,
|
||||
startDate: row.starts_on,
|
||||
endDate: row.ends_on ?? undefined,
|
||||
eventStatus:
|
||||
row.effective_status === "cancelled"
|
||||
? "https://schema.org/EventCancelled"
|
||||
: "https://schema.org/EventScheduled",
|
||||
eventAttendanceMode: row.is_online
|
||||
? "https://schema.org/OnlineEventAttendanceMode"
|
||||
: "https://schema.org/OfflineEventAttendanceMode",
|
||||
location: place,
|
||||
image: image ? [image] : undefined,
|
||||
organizer: row.host_name ? { "@type": "Organization", name: row.host_name } : undefined,
|
||||
url: meta.canonical,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function organizationMeta(site, db, id, kind, meta) {
|
||||
const row = db.prepare(`SELECT * FROM organizations WHERE id = ? AND is_published = 1`).get(id);
|
||||
// /regions/x must be a region: the same slug under the wrong route
|
||||
// is a page the site doesn't have.
|
||||
if (!row || (kind && row.kind !== kind)) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.name),
|
||||
description: plainText(first(row.tagline, firstParagraph(db, "organization", id, "card"))),
|
||||
image: imageUrl(site, row.logo, "organization") ?? meta.image,
|
||||
canonical: `${origin(site)}${ORG_ROUTES[row.kind] ?? "/organizations"}/${row.id}`,
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function teamMeta(site, db, id, meta) {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT t.* FROM teams t
|
||||
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
|
||||
WHERE t.id = ? AND t.is_published = 1`,
|
||||
)
|
||||
.get(id);
|
||||
if (!row) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.name),
|
||||
description: plainText(first(row.tagline, firstParagraph(db, "team", id, "card"))),
|
||||
image: imageUrl(site, row.logo, "team") ?? meta.image,
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function awardMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM awards WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.name),
|
||||
description: plainText(row.description),
|
||||
image: imageUrl(site, row.logo, "award") ?? meta.image,
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function personMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM people WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.display_name),
|
||||
description: plainText(first(row.tagline, row.bio, firstParagraph(db, "person", id, "card"))),
|
||||
image: imageUrl(site, row.photo, "person") ?? meta.image,
|
||||
type: "profile",
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function blogMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
const authors = db
|
||||
.prepare(
|
||||
`SELECT p.display_name AS name
|
||||
FROM blog_post_authors a
|
||||
JOIN people p ON p.id = a.person_id AND p.is_published = 1
|
||||
WHERE a.post_id = ? ORDER BY a.sort_order`,
|
||||
)
|
||||
.all(id)
|
||||
.map((a) => a.name);
|
||||
if (row.guest_author) authors.push(row.guest_author);
|
||||
|
||||
const description = plainText(first(row.excerpt, firstParagraph(db, "blog_post", id, "body")));
|
||||
const image = imageUrl(site, row.cover_image, "blog") ?? meta.image;
|
||||
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.title),
|
||||
description,
|
||||
image,
|
||||
type: "article",
|
||||
noindex: row.is_listed !== 1,
|
||||
jsonLd: {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BlogPosting",
|
||||
headline: row.title,
|
||||
description: description ?? undefined,
|
||||
datePublished: row.published_on ?? undefined,
|
||||
dateModified: row.updated_at ? row.updated_at.replace(" ", "T") + "Z" : undefined,
|
||||
author: authors.length ? authors.map((name) => ({ "@type": "Person", name })) : undefined,
|
||||
image: image ? [image] : undefined,
|
||||
publisher: { "@type": "Organization", name: site.title, url: `${origin(site)}/` },
|
||||
mainEntityOfPage: meta.canonical,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/* The metadata for one request path. */
|
||||
export function metaFor(db, rawPath) {
|
||||
const site = loadSite();
|
||||
// Canonical form: no trailing slash (but "/" itself), no query.
|
||||
const pathname = rawPath.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") || "/";
|
||||
const meta = defaults(site, db, pathname);
|
||||
|
||||
if (pathname === "/") {
|
||||
return {
|
||||
...meta,
|
||||
jsonLd: {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Organization",
|
||||
name: site.title,
|
||||
url: `${origin(site)}/`,
|
||||
logo: meta.image ?? undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
|
||||
|
||||
const page = site.pages?.[pathname];
|
||||
if (page) {
|
||||
return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description };
|
||||
}
|
||||
|
||||
const match = pathname.match(/^\/(events|regions|chapters|partners|organizations|teams|awards|people|blog)\/([^/]+)$/);
|
||||
if (!match) return notFound(meta);
|
||||
|
||||
const [, base, rawId] = match;
|
||||
let id;
|
||||
try {
|
||||
id = decodeURIComponent(rawId);
|
||||
} catch {
|
||||
return notFound(meta);
|
||||
}
|
||||
|
||||
switch (base) {
|
||||
case "events":
|
||||
return eventMeta(site, db, id, meta);
|
||||
case "regions":
|
||||
return organizationMeta(site, db, id, "region", meta);
|
||||
case "chapters":
|
||||
return organizationMeta(site, db, id, "chapter", meta);
|
||||
case "partners":
|
||||
return organizationMeta(site, db, id, "partner", meta);
|
||||
case "organizations":
|
||||
return organizationMeta(site, db, id, null, meta);
|
||||
case "teams":
|
||||
return teamMeta(site, db, id, meta);
|
||||
case "awards":
|
||||
return awardMeta(site, db, id, meta);
|
||||
case "people":
|
||||
return personMeta(site, db, id, meta);
|
||||
case "blog":
|
||||
return blogMeta(site, db, id, meta);
|
||||
}
|
||||
return notFound(meta);
|
||||
}
|
||||
|
||||
/* ── Into the HTML ─────────────────────────────────────────── */
|
||||
|
||||
const escapeHtml = (value) =>
|
||||
String(value)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, """)
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
|
||||
/* The tags the build put in (vite.config.ts's site plugin) that this
|
||||
replaces, so a page never says two different things. */
|
||||
const REPLACED = [
|
||||
/<title>[\s\S]*?<\/title>\s*/i,
|
||||
/<meta\s+(?:name|property)="(?:description|robots|og:[^"]+|twitter:[^"]+)"[^>]*>\s*/gi,
|
||||
/<link\s+rel="canonical"[^>]*>\s*/gi,
|
||||
/<script\s+type="application\/ld\+json"[^>]*>[\s\S]*?<\/script>\s*/gi,
|
||||
];
|
||||
|
||||
export function renderPage(html, meta) {
|
||||
const site = loadSite();
|
||||
let out = html;
|
||||
for (const pattern of REPLACED) out = out.replace(pattern, "");
|
||||
|
||||
const tags = [
|
||||
`<title>${escapeHtml(meta.title)}</title>`,
|
||||
meta.description && `<meta name="description" content="${escapeHtml(meta.description)}">`,
|
||||
meta.noindex && `<meta name="robots" content="noindex">`,
|
||||
meta.status === 200 && `<link rel="canonical" href="${escapeHtml(meta.canonical)}">`,
|
||||
`<meta property="og:site_name" content="${escapeHtml(site.title)}">`,
|
||||
`<meta property="og:type" content="${meta.type}">`,
|
||||
`<meta property="og:title" content="${escapeHtml(meta.title)}">`,
|
||||
meta.description && `<meta property="og:description" content="${escapeHtml(meta.description)}">`,
|
||||
meta.status === 200 && `<meta property="og:url" content="${escapeHtml(meta.canonical)}">`,
|
||||
meta.image && `<meta property="og:image" content="${escapeHtml(meta.image)}">`,
|
||||
`<meta name="twitter:card" content="${meta.image ? "summary_large_image" : "summary"}">`,
|
||||
meta.image && `<meta name="twitter:image" content="${escapeHtml(meta.image)}">`,
|
||||
// "</" can't appear inside the script, or the browser would
|
||||
// end the element there.
|
||||
meta.jsonLd &&
|
||||
`<script type="application/ld+json">${JSON.stringify(meta.jsonLd).replace(/</g, "\\u003c")}</script>`,
|
||||
].filter(Boolean);
|
||||
|
||||
// A blocked site (site.json robots.index false) stays blocked on
|
||||
// every page, whatever the record says.
|
||||
if (site.robots?.index === false && !meta.noindex) {
|
||||
tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`);
|
||||
}
|
||||
|
||||
return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n </head>`);
|
||||
}
|
||||
|
||||
/* ── Sitemap ───────────────────────────────────────────────── */
|
||||
|
||||
export function sitemap(db) {
|
||||
const site = loadSite();
|
||||
const base = origin(site);
|
||||
const day = (value) => (value ? String(value).slice(0, 10) : null);
|
||||
|
||||
const entries = [
|
||||
{ loc: "/" },
|
||||
...Object.keys(site.pages ?? {}).map((loc) => ({ loc })),
|
||||
...db
|
||||
.prepare(`SELECT id, updated_at FROM events WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/events/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(`SELECT id, kind, updated_at FROM organizations WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `${ORG_ROUTES[r.kind] ?? "/organizations"}/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(
|
||||
`SELECT t.id, t.updated_at FROM teams t
|
||||
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
|
||||
WHERE t.is_published = 1 AND t.is_listed = 1`,
|
||||
)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/teams/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(`SELECT id FROM awards WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/awards/${r.id}` })),
|
||||
...db
|
||||
.prepare(`SELECT id, updated_at FROM people WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/people/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(`SELECT id, updated_at FROM blog_posts WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/blog/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
];
|
||||
|
||||
const xml = entries
|
||||
.map(
|
||||
(e) =>
|
||||
` <url><loc>${escapeHtml(base + e.loc.split("/").map(encodeURIComponent).join("/"))}</loc>` +
|
||||
(e.lastmod ? `<lastmod>${e.lastmod}</lastmod>` : "") +
|
||||
`</url>`,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${xml}\n</urlset>\n`;
|
||||
}
|
||||
79
server/src/routes/pages.js
Normal file
79
server/src/routes/pages.js
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PAGE ROUTES: the site's HTML, with each page's metadata
|
||||
|
||||
GET /sitemap.xml every public, listed page
|
||||
GET /anything the built index.html, its title, description,
|
||||
preview image, canonical link and structured
|
||||
data filled in for that path (pageMeta.js)
|
||||
|
||||
In production nginx serves files that exist (the JS, CSS,
|
||||
uploads) itself and sends everything else here, so a shared link
|
||||
carries the right preview; see docs/seo.md for the block. The app
|
||||
in the page then takes over as usual. In development Vite serves
|
||||
index.html itself and this is never reached.
|
||||
|
||||
SITE_INDEX is the built index.html (default: dist/ at the repo
|
||||
root). It's reread when the file changes, so a deploy needs no
|
||||
restart for the page to update. A record that doesn't exist gets
|
||||
the app's own not-found page with a 404 status, so search engines
|
||||
drop it.
|
||||
|
||||
Mounted last, after every /api and /uploads route; an unknown
|
||||
/api path is still the API's JSON 404.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { metaFor, renderPage, sitemap } from "../pageMeta.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const SITE_INDEX = path.resolve(
|
||||
process.env.SITE_INDEX ?? path.join(here, "../../../dist/index.html"),
|
||||
);
|
||||
|
||||
const CACHE = "public, max-age=60, stale-while-revalidate=300";
|
||||
|
||||
let cached = { mtime: 0, html: null };
|
||||
|
||||
function indexHtml() {
|
||||
const mtime = statSync(SITE_INDEX).mtimeMs;
|
||||
if (cached.html && cached.mtime === mtime) return cached.html;
|
||||
cached = { mtime, html: readFileSync(SITE_INDEX, "utf8") };
|
||||
return cached.html;
|
||||
}
|
||||
|
||||
const pages = new Hono();
|
||||
|
||||
pages.get("/sitemap.xml", (c) =>
|
||||
c.body(sitemap(c.get("db")), 200, {
|
||||
"Content-Type": "application/xml; charset=utf-8",
|
||||
"Cache-Control": CACHE,
|
||||
}),
|
||||
);
|
||||
|
||||
pages.get("*", (c, next) => {
|
||||
const pathname = c.req.path;
|
||||
// The API's own paths, and an upload that isn't there, stay plain
|
||||
// 404s rather than becoming a page.
|
||||
if (/^\/(api|uploads)(\/|$)/.test(pathname)) return next();
|
||||
|
||||
let html;
|
||||
try {
|
||||
html = indexHtml();
|
||||
} catch (err) {
|
||||
console.error(`pages: can't read ${SITE_INDEX}: ${err.message}`);
|
||||
return c.text("The site hasn't been built.", 503);
|
||||
}
|
||||
|
||||
const meta = metaFor(c.get("db"), pathname);
|
||||
return c.html(renderPage(html, meta), meta.status, {
|
||||
"Cache-Control": meta.status === 200 ? CACHE : "no-store",
|
||||
});
|
||||
});
|
||||
|
||||
export default pages;
|
||||
Loading…
Add table
Add a link
Reference in a new issue