feat(website): the four templates and the public site
Heritage, Bold, Community and Clean drawing all 26 section variants with their headers, homepage order and style settings; colours made safe (WCAG AA) by the backend; fonts and corners from the shared brand style. Publishing into numbered versions, the content API with live messages and events and the church profile from Accounts, uploads, every page kind, simple event pages, Coming soon, 404, sitemap, SEO basics and the church's JSON-LD. The demo church (npm run demo) and Playwright e2e: every template's pages pass axe and the SEO checks. website.sh builds packages/seo. Decision 17 (first Owner) recorded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,7 +14,8 @@
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status"
|
||||
"prisma:status": "prisma migrate status",
|
||||
"demo": "tsx scripts/demo.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Loads the demo church (src/demo/demoChurch.ts) into a template and publishes it.
|
||||
*
|
||||
* npm run demo -- --template heritage|bold|community|clean [--force]
|
||||
*
|
||||
* It replaces the site's content, so a site that has been published needs --force.
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { websiteTemplateSchema } from '@crosscode/contracts';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { loadDemo } from '../src/demo/demoChurch.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
|
||||
const arg = (name: string) => {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
return i > 0 ? process.argv[i + 1] : undefined;
|
||||
};
|
||||
const template = websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
|
||||
if (!template.success) {
|
||||
console.error('Usage: npm run demo -- --template heritage|bold|community|clean [--force]');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const ctx = createCtx(loadConfig(), db);
|
||||
const published = await db.siteVersion.findFirst({ where: { NOT: { publishedBy: 'demo' } } });
|
||||
if (published && !process.argv.includes('--force')) {
|
||||
console.error('This site has been published by its admins: loading the demo would replace their content. Add --force to do it anyway.');
|
||||
await db.$disconnect();
|
||||
process.exit(1);
|
||||
}
|
||||
const version = await loadDemo(ctx, template.data);
|
||||
console.log(`Demo church loaded on ${template.data} and published (version ${version.number}).`);
|
||||
await db.$disconnect();
|
||||
@@ -4,13 +4,15 @@
|
||||
*
|
||||
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
|
||||
* /api/v1/site/… the public site (what visitors see: the latest published version)
|
||||
* /api/uploads/… the church's uploaded images
|
||||
* /api/auth/… signing in to the admin through the church's Accounts
|
||||
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
|
||||
* /api/links/v1/… Connect and Disconnect with the church's other products
|
||||
* /api/v1/admin/… the admin (signed in, by role)
|
||||
*
|
||||
* To come (§1): the admin's content, publish and preview links, /api/uploads/…, the event feed.
|
||||
* To come (§1): the admin's content, publish and preview links, uploading, the event feed.
|
||||
*/
|
||||
import path from 'node:path';
|
||||
import express from 'express';
|
||||
import type { Ctx } from './context.js';
|
||||
import { authRouter } from './auth/routes.js';
|
||||
@@ -19,6 +21,8 @@ import { dbUp } from './hub/client.js';
|
||||
import { ApiError, handle, sendError } from './http.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
import { linksRouter } from './links/routes.js';
|
||||
import { defaultUploadDir } from './demo/demoChurch.js';
|
||||
import { siteContent } from './site/content.js';
|
||||
import { siteStatus } from './site/status.js';
|
||||
|
||||
export function createApp(ctx: Ctx) {
|
||||
@@ -41,8 +45,22 @@ export function createApp(ctx: Ctx) {
|
||||
|
||||
const site = express.Router();
|
||||
site.get('/status', handle(() => siteStatus(ctx)));
|
||||
site.get('/content', handle(async (_req, res) => {
|
||||
// Short: Publish shows within a minute even where a proxy caches.
|
||||
res.set('Cache-Control', 'public, max-age=30');
|
||||
return siteContent(ctx);
|
||||
}));
|
||||
app.use('/api/v1/site', site);
|
||||
|
||||
// Uploaded files: never a directory listing, never outside the folder (express.static checks).
|
||||
app.use('/api/uploads', express.static(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), {
|
||||
index: false, dotfiles: 'deny', fallthrough: false, maxAge: '7d',
|
||||
setHeaders: (res) => {
|
||||
// An uploaded SVG is shown as an image, never run as a page.
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||
},
|
||||
}));
|
||||
|
||||
app.use('/api', authRouter(ctx));
|
||||
app.use('/api', linksRouter(ctx));
|
||||
|
||||
@@ -58,8 +76,11 @@ export function createApp(ctx: Ctx) {
|
||||
|
||||
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
if (res.headersSent) return next(err);
|
||||
const e = err as { type?: string };
|
||||
if (err instanceof ApiError) return sendError(res, err);
|
||||
const e = err as { type?: string; status?: number };
|
||||
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
|
||||
// A missing upload (express.static), or another known client error.
|
||||
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
|
||||
return sendError(res, err);
|
||||
});
|
||||
return app;
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* The church profile (`crosscode.church/1`) from the church's Accounts (WEBSITE-1.0-PLAN §2): name,
|
||||
* logo, colours, brand style, service times, contact, social, the church's other sites. Accounts
|
||||
* owns it; the Website shows it and never stores it (§2: shared facts aren't drafts). As Events
|
||||
* 3.7's accounts/church.ts: kept in memory for 10 minutes, the last copy kept while Accounts can't
|
||||
* be reached (tried again after a minute).
|
||||
*
|
||||
* Before the Website is linked to Accounts (and in local development) the profile saved in
|
||||
* AppSetting `church_profile_local` is used, if any (`npm run demo` saves the demo church's).
|
||||
*/
|
||||
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { accountsLink } from '../auth/accounts.js';
|
||||
|
||||
const FRESH_MS = 10 * 60e3;
|
||||
const RETRY_MS = 60e3;
|
||||
const TIMEOUT_MS = 5000;
|
||||
|
||||
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
|
||||
const caches = new WeakMap<Ctx, { cached: Cached | null; pending: Promise<Church | null> | null }>();
|
||||
|
||||
async function fetchProfile(accountsUrl: string): Promise<Church> {
|
||||
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
|
||||
const parsed = churchSchema.safeParse(await res.json());
|
||||
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async function localProfile(ctx: Ctx): Promise<Church | null> {
|
||||
const raw = await ctx.settings.json<unknown>('church_profile_local', null);
|
||||
const parsed = raw ? churchSchema.safeParse(raw) : null;
|
||||
return parsed?.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
/** The church's profile, or null when there's none yet. Never throws. */
|
||||
export async function churchProfile(ctx: Ctx): Promise<Church | null> {
|
||||
let link;
|
||||
try {
|
||||
link = await accountsLink(ctx);
|
||||
} catch {
|
||||
link = null;
|
||||
}
|
||||
if (!link) return localProfile(ctx).catch(() => null);
|
||||
let state = caches.get(ctx);
|
||||
if (!state) caches.set(ctx, (state = { cached: null, pending: null }));
|
||||
const { cached } = state;
|
||||
const url = link.url;
|
||||
if (cached && cached.url === url && ctx.now().getTime() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!state.pending) {
|
||||
const last = cached?.url === url ? cached.church : null;
|
||||
const s = state;
|
||||
s.pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
s.cached = { url, church, at: ctx.now().getTime(), ok: true };
|
||||
return church;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
s.cached = { url, church: last, at: ctx.now().getTime(), ok: false };
|
||||
return last;
|
||||
})
|
||||
.finally(() => { s.pending = null; });
|
||||
}
|
||||
return state.pending;
|
||||
}
|
||||
|
||||
/** `church.changed` from Accounts: fetched again next time (the last copy is shown meanwhile). */
|
||||
export function churchChanged(ctx: Ctx): void {
|
||||
const state = caches.get(ctx);
|
||||
if (state?.cached) state.cached = { ...state.cached, at: 0 };
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* The demo church (WEBSITE-1.0-PLAN §11, "Demo church"): a fictional church, fictional people and
|
||||
* illustrated images (no photos of anyone), loaded into a template for development, the Hub's demo
|
||||
* sites and the crosscode-site screenshots. `npm run demo -- --template bold`.
|
||||
*
|
||||
* It replaces the Website's content (never the admins), so the script refuses on a site that has
|
||||
* been published unless told otherwise.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { CHURCH_SCHEMA, type Church, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { SectionData } from '../site/sections.js';
|
||||
import { publish } from '../site/snapshot.js';
|
||||
import { defaultDesign } from '../site/variants.js';
|
||||
|
||||
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
|
||||
|
||||
export function demoProfile(publicUrl: string): Church {
|
||||
return {
|
||||
schema: CHURCH_SCHEMA,
|
||||
customerId: '00000000-0000-4000-8000-000000000001',
|
||||
updatedAt: '2026-11-25T08:00:00.000Z',
|
||||
name: 'Acacia Hill Church',
|
||||
shortName: 'Acacia Hill',
|
||||
timezone: 'Africa/Johannesburg',
|
||||
locale: 'en-ZA',
|
||||
branding: { logoUrl: null, iconUrl: null, colours: DEMO_COLOURS, style: { fontPairing: null, corners: null } },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: 'sunday', time: '08:30', label: 'Early service', campus: null, note: null },
|
||||
{ day: 'sunday', time: '10:00', label: 'Family service', campus: null, note: 'Kids church during the service' },
|
||||
{ day: 'wednesday', time: '18:30', label: 'Midweek prayer', campus: null, note: null },
|
||||
],
|
||||
contact: {
|
||||
email: 'hello@acaciahill.example',
|
||||
phone: '+27125550123',
|
||||
whatsapp: '+27825550123',
|
||||
address: { line1: '12 Acacia Avenue', line2: null, suburb: 'Westridge', city: 'Pretoria', province: 'Gauteng', postalCode: '0181', country: 'ZA', geo: { lat: -25.7461, lng: 28.1881 } },
|
||||
},
|
||||
social: [
|
||||
{ network: 'facebook', url: 'https://www.facebook.com/acaciahill.example' },
|
||||
{ network: 'youtube', url: 'https://www.youtube.com/@acaciahill.example' },
|
||||
],
|
||||
links: { website: publicUrl, events: null, app: null, accounts: 'https://accounts.acaciahill.example' },
|
||||
} as Church;
|
||||
}
|
||||
|
||||
/** An illustrated "photo": hills, a sun and a path in the church's colours (SVG, no people). */
|
||||
function illustration(seed: number, w = 1600, h = 1000): string {
|
||||
const hues = [DEMO_COLOURS.primary, DEMO_COLOURS.accent, '#7fb7be', '#f3e3c3', '#284b52'];
|
||||
const c = (i: number) => hues[(seed + i) % hues.length];
|
||||
const y = (f: number) => Math.round(h * f);
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">
|
||||
<defs><linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${c(3)}"/><stop offset="1" stop-color="#fffaf0"/></linearGradient></defs>
|
||||
<rect width="${w}" height="${h}" fill="url(#sky)"/>
|
||||
<circle cx="${Math.round(w * (0.2 + (seed % 5) * 0.15))}" cy="${y(0.3)}" r="${Math.round(h * 0.12)}" fill="${c(1)}" opacity="0.85"/>
|
||||
<path d="M0 ${y(0.62)} Q ${w * 0.25} ${y(0.45)} ${w * 0.5} ${y(0.6)} T ${w} ${y(0.55)} V ${h} H 0 Z" fill="${c(2)}"/>
|
||||
<path d="M0 ${y(0.75)} Q ${w * 0.35} ${y(0.6)} ${w * 0.7} ${y(0.74)} T ${w} ${y(0.7)} V ${h} H 0 Z" fill="${c(0)}"/>
|
||||
<path d="M${w * 0.45} ${h} C ${w * 0.5} ${y(0.85)} ${w * 0.6} ${y(0.8)} ${w * 0.62} ${y(0.72)}" stroke="${c(3)}" stroke-width="${Math.round(h * 0.03)}" fill="none" stroke-linecap="round"/>
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
type Ids = Record<string, string>;
|
||||
|
||||
async function demoMedia(ctx: Ctx, uploadDir: string): Promise<Ids> {
|
||||
const items: [string, string, number][] = [
|
||||
['hero', 'The hills behind Acacia Hill at sunrise (illustration)', 0],
|
||||
['collage2', 'A path through the veld (illustration)', 1],
|
||||
['collage3', 'Evening over the valley (illustration)', 2],
|
||||
['welcome', 'The church garden (illustration)', 3],
|
||||
['pastor', 'Illustration standing in for the pastor\'s photo', 4],
|
||||
['invite', 'A sunny Sunday morning (illustration)', 5],
|
||||
['kids', 'Illustration for Kids church', 6],
|
||||
['youth', 'Illustration for Youth', 7],
|
||||
['care', 'Illustration for Care and prayer', 8],
|
||||
['music', 'Illustration for Worship', 9],
|
||||
];
|
||||
const ids: Ids = {};
|
||||
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
|
||||
for (const [key, alt, seed] of items) {
|
||||
const filename = `demo/${key}.svg`;
|
||||
const svg = illustration(seed);
|
||||
fs.writeFileSync(path.join(uploadDir, filename), svg);
|
||||
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt } });
|
||||
ids[key] = row.id;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
|
||||
|
||||
/** Replaces the content with the demo church's on `template`, then publishes it. */
|
||||
export async function loadDemo(ctx: Ctx, template: WebsiteTemplate, opts: { uploadDir?: string; publishedBy?: string } = {}) {
|
||||
const db = ctx.db;
|
||||
const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir();
|
||||
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'mediaAsset', 'siteVersion', 'siteDesign'] as const) {
|
||||
await (db[m] as unknown as { deleteMany: (a?: object) => Promise<unknown> }).deleteMany({});
|
||||
}
|
||||
const img = await demoMedia(ctx, uploadDir);
|
||||
const design = defaultDesign(template);
|
||||
await db.siteDesign.create({ data: { id: 1, template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
|
||||
await ctx.settings.set('church_profile_local', JSON.stringify(demoProfile(ctx.config.publicUrl)));
|
||||
|
||||
const home: SectionData = {
|
||||
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: { label: 'Plan your visit', href: '/visit' } },
|
||||
serviceTimes: { heading: 'Join us this Sunday', note: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.' },
|
||||
welcome: {
|
||||
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
|
||||
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
|
||||
imageId: img.welcome!, pastor: { name: 'Pastor Thandi Mokoena', role: 'Lead pastor', quote: 'We would love to meet you. Come and say hello at the welcome table.', photoId: img.pastor! },
|
||||
},
|
||||
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
|
||||
team: { heading: 'Our team', intro: null },
|
||||
events: { heading: 'Coming up', count: 3 },
|
||||
latestMessage: { heading: 'Latest message' },
|
||||
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' }, imageId: img.invite! },
|
||||
};
|
||||
const pages: { kind: string; slug: string; title: string; position: number; description: string; sections: { type: string; variant?: string; data: unknown }[] }[] = [
|
||||
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.', sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
|
||||
{
|
||||
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: 'What to expect on your first Sunday at Acacia Hill Church.', sections: [
|
||||
{ type: 'text', data: { heading: 'What to expect', body: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.' } },
|
||||
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.', imageId: img.kids, button: null } },
|
||||
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Send us a WhatsApp and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'about', slug: 'about', title: 'About us', position: 2, description: 'Our story, what we believe and what we value.', sections: [
|
||||
{ type: 'text', data: { heading: 'Our story', body: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.' } },
|
||||
{ type: 'quote', data: { quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' } },
|
||||
],
|
||||
},
|
||||
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: 'Kids, youth, worship, care and prayer at Acacia Hill.', sections: [] },
|
||||
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: 'The team who lead Acacia Hill Church.', sections: [] },
|
||||
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: 'What is coming up at Acacia Hill Church.', sections: [] },
|
||||
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: 'Sunday messages from Acacia Hill Church.', sections: [] },
|
||||
{
|
||||
kind: 'give', slug: 'give', title: 'Give', position: 7, description: 'How to give to Acacia Hill Church.', sections: [
|
||||
{ type: 'text', data: { heading: 'Giving', body: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).' } },
|
||||
],
|
||||
},
|
||||
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: 'Find Acacia Hill Church in Westridge, Pretoria.', sections: [] },
|
||||
];
|
||||
for (const p of pages) {
|
||||
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: p.position, description: p.description } });
|
||||
let i = 0;
|
||||
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, variant: s.variant ?? null, position: i++, data: s.data as never } });
|
||||
}
|
||||
|
||||
const ministries: [string, string, string, string][] = [
|
||||
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.', img.kids!],
|
||||
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.', img.youth!],
|
||||
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.', img.music!],
|
||||
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.', img.care!],
|
||||
];
|
||||
let n = 0;
|
||||
for (const [slug, name, summary, imageId] of ministries) await db.ministry.create({ data: { slug, name, summary, imageId, position: n++ } });
|
||||
const leaders: [string, string, string | null][] = [
|
||||
['Thandi Mokoena', 'Lead pastor', img.pastor!],
|
||||
['Pieter van Wyk', 'Associate pastor', null],
|
||||
['Lerato Dlamini', 'Kids and families', null],
|
||||
['Johan Botha', 'Worship', null],
|
||||
];
|
||||
n = 0;
|
||||
for (const [name, role, photoId] of leaders) await db.leader.create({ data: { name, role, photoId, position: n++ } });
|
||||
|
||||
const now = ctx.now();
|
||||
const day = 864e5;
|
||||
const series = await db.messageSeries.create({ data: { slug: 'hope-for-today', title: 'Hope for today' } });
|
||||
const messages: [string, string, number][] = [['hope-that-holds', 'A hope that holds', 3], ['bread-for-the-road', 'Bread for the road', 10], ['the-good-shepherd', 'The good shepherd', 17]];
|
||||
for (const [slug, title, ago] of messages) {
|
||||
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker: 'Pastor Thandi Mokoena', passage: 'Psalm 23', seriesId: series.id, publishedAt: now } });
|
||||
}
|
||||
const events: [string, string, number, string][] = [
|
||||
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
|
||||
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
|
||||
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
|
||||
];
|
||||
for (const [slug, title, inDays, description] of events) {
|
||||
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
|
||||
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: 'Acacia Hill Church', description, publishedAt: now } });
|
||||
}
|
||||
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, `Demo church on ${template}`);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* Everything the public site needs to draw a page (WEBSITE-1.0-PLAN §1): the latest published
|
||||
* snapshot, the church profile from Accounts, the colours made safe, the fonts and corners, and
|
||||
* the messages and events (which publish on their own, so they're read live). Before the first
|
||||
* publish: Coming soon, from the profile alone (§5).
|
||||
*/
|
||||
import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { buildPalette, type Palette } from './palette.js';
|
||||
import { mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
|
||||
|
||||
export type SiteEvent = {
|
||||
title: string;
|
||||
summary: string | null;
|
||||
startsAt: string;
|
||||
endsAt: string | null;
|
||||
allDay: boolean;
|
||||
location: string | null;
|
||||
image: Image | null;
|
||||
/** The event's page: on this site, or at its origin (Cross Events, for registering). */
|
||||
url: string;
|
||||
from: 'website' | 'events' | 'app';
|
||||
registration: { status: string; priceFromCents: number | null } | null;
|
||||
};
|
||||
|
||||
export type SiteMessage = {
|
||||
slug: string;
|
||||
title: string;
|
||||
date: string;
|
||||
speaker: string | null;
|
||||
series: string | null;
|
||||
passage: string | null;
|
||||
source: 'youtube' | 'spotify';
|
||||
/** For the embed (youtube-nocookie) or the Spotify player, loaded only when clicked. */
|
||||
embedUrl: string | null;
|
||||
url: string;
|
||||
thumbnail: string | null;
|
||||
};
|
||||
|
||||
type Common = {
|
||||
church: Church | null;
|
||||
palette: Palette;
|
||||
/** The shared brand style, else what the template suggests (§3). */
|
||||
style: { fontPairing: string; corners: string };
|
||||
};
|
||||
|
||||
export type SiteContent =
|
||||
| (Common & { mode: 'coming-soon'; template: WebsiteTemplate; comingSoonText: string })
|
||||
| (Common & {
|
||||
mode: 'published';
|
||||
version: number;
|
||||
snapshot: Snapshot;
|
||||
/** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */
|
||||
transparentHeader: Record<string, boolean>;
|
||||
messages: SiteMessage[];
|
||||
events: SiteEvent[];
|
||||
});
|
||||
|
||||
const DEFAULT_COLOUR = '#1f4e79';
|
||||
|
||||
function brandFor(church: Church | null, template: WebsiteTemplate) {
|
||||
return {
|
||||
palette: buildPalette(church?.branding.colours.primary ?? DEFAULT_COLOUR, church?.branding.colours.accent ?? null),
|
||||
style: {
|
||||
fontPairing: church?.branding.style?.fontPairing ?? TEMPLATE_FONT_PAIRINGS[template][0],
|
||||
corners: church?.branding.style?.corners ?? TEMPLATE_STYLE[template].suggestedCorners,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** `https://www.youtube.com/watch?v=abc` → its id; null for anything else. */
|
||||
export function youtubeId(url: string): string | null {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (u.hostname === 'youtu.be') return u.pathname.slice(1) || null;
|
||||
if (/(^|\.)youtube(-nocookie)?\.com$/.test(u.hostname)) return u.searchParams.get('v') ?? (/^\/(embed|shorts|live)\/([\w-]+)/.exec(u.pathname)?.[2] ?? null);
|
||||
} catch {
|
||||
// Not a URL.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** `https://open.spotify.com/episode/abc` → the embed address; null for anything else. */
|
||||
export function spotifyEmbed(url: string): string | null {
|
||||
const m = /^https:\/\/open\.spotify\.com\/(episode|show)\/([A-Za-z0-9]+)/.exec(url);
|
||||
return m ? `https://open.spotify.com/embed/${m[1]}/${m[2]}` : null;
|
||||
}
|
||||
|
||||
async function liveMessages(ctx: Ctx): Promise<SiteMessage[]> {
|
||||
const rows = await ctx.db.message.findMany({ where: { hidden: false, publishedAt: { not: null } }, orderBy: { date: 'desc' }, take: 24, include: { series: true } });
|
||||
return rows.map((m) => {
|
||||
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
|
||||
return {
|
||||
slug: m.slug, title: m.title, date: m.date.toISOString(), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage,
|
||||
source: m.source === 'spotify' ? 'spotify' : 'youtube',
|
||||
embedUrl: yt ? `https://www.youtube-nocookie.com/embed/${yt}?autoplay=1` : spotifyEmbed(m.mediaUrl),
|
||||
url: m.mediaUrl,
|
||||
thumbnail: m.thumbnailUrl ?? (yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
const now = ctx.now();
|
||||
const [simple, imported, media] = await Promise.all([
|
||||
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, cancelled: false, OR: [{ startsAt: { gte: now } }, { endsAt: { gte: now } }] }, orderBy: { startsAt: 'asc' }, take: 50 }),
|
||||
ctx.db.importedEvent.findMany({ where: { startsAt: { gte: new Date(now.getTime() - 7 * 864e5) } }, orderBy: { startsAt: 'asc' }, take: 50 }),
|
||||
ctx.db.mediaAsset.findMany(),
|
||||
]);
|
||||
const image = (id: string | null) => {
|
||||
const m = id ? media.find((x) => x.id === id) : null;
|
||||
return m ? { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } : null;
|
||||
};
|
||||
const own: SiteEvent[] = simple.map((e) => ({
|
||||
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
|
||||
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, from: 'website', registration: null,
|
||||
}));
|
||||
const copies: SiteEvent[] = imported.flatMap((row) => {
|
||||
const e = row.data as unknown as CrosscodeEvent;
|
||||
if (!e?.title || (e.endsAt ? new Date(e.endsAt) < now : new Date(e.startsAt) < now)) return [];
|
||||
return [{
|
||||
title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null,
|
||||
image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, from: e.origin.product,
|
||||
registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null,
|
||||
} satisfies SiteEvent];
|
||||
});
|
||||
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
|
||||
}
|
||||
|
||||
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
|
||||
if (!published) {
|
||||
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
|
||||
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
|
||||
return {
|
||||
mode: 'coming-soon', template, church, ...brandFor(church, template),
|
||||
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
|
||||
};
|
||||
}
|
||||
const { snapshot } = published;
|
||||
const template = snapshot.design.template;
|
||||
const transparentHeader = Object.fromEntries(snapshot.pages.map((p) => {
|
||||
const hero = p.sections[0]?.type === 'hero' ? (p.sections[0].variant as Variant<'hero'>) : null;
|
||||
return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)];
|
||||
}));
|
||||
const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]);
|
||||
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), messages, events };
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* The site's colours from the church's two (WEBSITE-1.0-PLAN §3, "Colours from the church, made
|
||||
* safe"): tints and shades, the text colour on each, all checked against WCAG AA (4.5:1 for text).
|
||||
* A colour that fails is darkened (or lightened) until it passes, and the admin is told why.
|
||||
*/
|
||||
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
const AA = 4.5;
|
||||
const WHITE: Rgb = [255, 255, 255];
|
||||
const INK: Rgb = [17, 24, 39];
|
||||
|
||||
export function hexToRgb(hex: string): Rgb {
|
||||
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
|
||||
const n = parseInt(m ? m[1]! : '1f4e79', 16);
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
}
|
||||
|
||||
export const rgbToHex = (c: Rgb) => `#${c.map((x) => Math.round(x).toString(16).padStart(2, '0')).join('')}`;
|
||||
|
||||
/** "31 78 121": for Tailwind's `rgb(var(--brand) / <alpha-value>)`. */
|
||||
export const triple = (c: Rgb) => c.map((x) => Math.round(x)).join(' ');
|
||||
|
||||
function luminance([r, g, b]: Rgb): number {
|
||||
const lin = (v: number) => {
|
||||
const s = v / 255;
|
||||
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
||||
}
|
||||
|
||||
export function contrast(a: Rgb, b: Rgb): number {
|
||||
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number];
|
||||
return (x + 0.05) / (y + 0.05);
|
||||
}
|
||||
|
||||
/** `c` mixed with `to` by `t` (0 = c, 1 = to). */
|
||||
export const mix = (c: Rgb, to: Rgb, t: number): Rgb => [0, 1, 2].map((i) => c[i]! + (to[i]! - c[i]!) * t) as Rgb;
|
||||
|
||||
/** The nearest shade of `c` (towards black) that reaches `ratio` against `against`. */
|
||||
function darkenUntil(c: Rgb, against: Rgb, ratio = AA): Rgb {
|
||||
for (let t = 0; t <= 1; t += 0.02) {
|
||||
const d = mix(c, [0, 0, 0], t);
|
||||
if (contrast(d, against) >= ratio) return d;
|
||||
}
|
||||
return [0, 0, 0];
|
||||
}
|
||||
|
||||
export type Palette = {
|
||||
/** The church's colour as a background (buttons, bands), with `onBrand` text on it. */
|
||||
brand: string;
|
||||
brandDark: string;
|
||||
onBrand: string;
|
||||
/** The church's colour as text or a link on white: darkened when it's too light to read. */
|
||||
brandText: string;
|
||||
/** A soft background in the church's colour (Section colour "Tinted"). */
|
||||
brandTint: string;
|
||||
accent: string;
|
||||
onAccent: string;
|
||||
/** What was changed and why, for the admin (§3: "the admin is told why"). */
|
||||
notes: string[];
|
||||
};
|
||||
|
||||
export function buildPalette(primaryHex: string, accentHex: string | null): Palette {
|
||||
const notes: string[] = [];
|
||||
const primary = hexToRgb(primaryHex);
|
||||
const accent = accentHex ? hexToRgb(accentHex) : mix(primary, WHITE, 0.25);
|
||||
|
||||
// Text on the brand colour: white when it reads, else dark ink; if neither reaches AA, the
|
||||
// background is darkened until white does.
|
||||
let brand = primary;
|
||||
let onBrand = contrast(WHITE, brand) >= AA ? WHITE : contrast(INK, brand) >= AA ? INK : null;
|
||||
if (!onBrand) {
|
||||
brand = darkenUntil(primary, WHITE);
|
||||
onBrand = WHITE;
|
||||
notes.push(`Your main colour ${rgbToHex(primary)} is darkened to ${rgbToHex(brand)} behind text, so the text on buttons and bands can be read.`);
|
||||
}
|
||||
|
||||
const brandTextRgb = contrast(primary, WHITE) >= AA ? primary : darkenUntil(primary, WHITE);
|
||||
if (brandTextRgb !== primary) notes.push(`Links and headings in your main colour use a darker shade (${rgbToHex(brandTextRgb)}), so they can be read on white.`);
|
||||
|
||||
const onAccent = contrast(WHITE, accent) >= AA ? WHITE : INK;
|
||||
if (contrast(onAccent, accent) < AA) notes.push(`Your accent colour ${rgbToHex(accent)} is only used for decoration: text on it would be hard to read.`);
|
||||
|
||||
return {
|
||||
brand: triple(brand),
|
||||
brandDark: triple(mix(brand, [0, 0, 0], 0.2)),
|
||||
onBrand: triple(onBrand),
|
||||
brandText: triple(brandTextRgb),
|
||||
brandTint: triple(mix(primary, WHITE, 0.92)),
|
||||
accent: triple(accent),
|
||||
onAccent: triple(onAccent),
|
||||
notes,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* What an admin fills in for each homepage section (WEBSITE-1.0-PLAN §2: "every section stores its
|
||||
* data, validated with a zod schema per section type"). Never tied to a template: every template
|
||||
* draws every variant from the same data (§3). Lists (ministries, leaders, events, messages) come
|
||||
* from their own tables; the section only holds its heading and intro.
|
||||
*
|
||||
* Images are media ids here; the published snapshot turns them into `{ url, alt }`.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { SectionType } from './variants.js';
|
||||
|
||||
const text = (max: number) => z.string().trim().max(max);
|
||||
const optional = (max: number) => text(max).nullable().default(null);
|
||||
const mediaId = z.string().uuid();
|
||||
/** A link on the site (`/visit`) or elsewhere (https only). */
|
||||
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
|
||||
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
|
||||
|
||||
export const SECTION_SCHEMAS = {
|
||||
hero: z.object({
|
||||
headline: text(120).min(1),
|
||||
subline: optional(300),
|
||||
/** `photo` and `split` use the first; `collage` up to three. */
|
||||
images: z.array(mediaId).max(3).default([]),
|
||||
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
|
||||
videoId: mediaId.nullable().default(null),
|
||||
button,
|
||||
}),
|
||||
serviceTimes: z.object({
|
||||
heading: optional(80),
|
||||
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
|
||||
note: optional(300),
|
||||
}),
|
||||
welcome: z.object({
|
||||
heading: optional(120),
|
||||
/** The mission line, above the introduction in every variant (§3). */
|
||||
mission: optional(200),
|
||||
body: text(4000).default(''),
|
||||
imageId: mediaId.nullable().default(null),
|
||||
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
|
||||
}),
|
||||
ministries: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
team: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
|
||||
latestMessage: z.object({ heading: optional(80) }),
|
||||
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
|
||||
} as const satisfies Record<SectionType, z.ZodType>;
|
||||
|
||||
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
|
||||
|
||||
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
|
||||
export const BLOCK_SCHEMAS = {
|
||||
text: z.object({ heading: optional(120), body: text(20000) }),
|
||||
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
|
||||
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
|
||||
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
|
||||
} as const;
|
||||
|
||||
export type BlockType = keyof typeof BLOCK_SCHEMAS;
|
||||
export const isBlockType = (t: string): t is BlockType => t in BLOCK_SCHEMAS;
|
||||
|
||||
/** A section's or block's data, checked; null when it doesn't fit (it's then left out, never shown broken). */
|
||||
export function parseSectionData(type: string, data: unknown): Record<string, unknown> | null {
|
||||
const schema = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
|
||||
if (!schema) return null;
|
||||
const r = schema.safeParse(data ?? {});
|
||||
return r.success ? (r.data as Record<string, unknown>) : null;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Published versions (WEBSITE-1.0-PLAN §4): Publish copies the working copy into an immutable
|
||||
* snapshot (`SiteVersion.snapshot`), and visitors always see the latest. The snapshot holds the
|
||||
* site's design and every page with its sections, ministries and leaders, with images already
|
||||
* turned into `{ url, alt }`, so showing the site never reads the working copy.
|
||||
*
|
||||
* Messages and simple events aren't in it: they publish on their own (decision 9) and are read
|
||||
* live (content.ts).
|
||||
*/
|
||||
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { parseSectionData } from './sections.js';
|
||||
import { defaultDesign, isVariant, SECTION_TYPES, type SectionType, type SiteDesign } from './variants.js';
|
||||
|
||||
export const SNAPSHOT_VERSION = 1;
|
||||
|
||||
export type Image = { url: string; alt: string; width: number | null; height: number | null };
|
||||
|
||||
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> };
|
||||
|
||||
export type SnapshotPage = {
|
||||
kind: string;
|
||||
slug: string;
|
||||
/** `/` for home, else `/<slug>`. */
|
||||
path: string;
|
||||
title: string;
|
||||
seoTitle: string | null;
|
||||
description: string | null;
|
||||
navLabel: string;
|
||||
inNav: boolean;
|
||||
image: Image | null;
|
||||
sections: SnapshotSection[];
|
||||
};
|
||||
|
||||
export type Snapshot = {
|
||||
v: typeof SNAPSHOT_VERSION;
|
||||
design: SiteDesign;
|
||||
pages: SnapshotPage[];
|
||||
ministries: { slug: string; name: string; summary: string | null; body: string | null; image: Image | null }[];
|
||||
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
|
||||
/** Every image the sections refer to, by media id. */
|
||||
media: Record<string, Image>;
|
||||
};
|
||||
|
||||
export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`;
|
||||
|
||||
/** The design as saved, made safe: an unknown template, variant or section falls back to the default. */
|
||||
export function cleanDesign(saved: { template: string; variants: unknown; home: unknown; style: unknown } | null): SiteDesign {
|
||||
const template: WebsiteTemplate = saved && (WEBSITE_TEMPLATES as readonly string[]).includes(saved.template) ? (saved.template as WebsiteTemplate) : 'heritage';
|
||||
const base = defaultDesign(template);
|
||||
if (!saved) return base;
|
||||
const variants = { ...base.variants } as Record<SectionType, string>;
|
||||
const v = (saved.variants ?? {}) as Record<string, unknown>;
|
||||
for (const s of SECTION_TYPES) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string;
|
||||
const home = Array.isArray(saved.home)
|
||||
? (saved.home as { section?: unknown; hidden?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ section: e.section as SectionType, hidden: !!e.hidden }))
|
||||
: base.home;
|
||||
// Every section listed once: any missing one is added at the end, hidden.
|
||||
for (const s of SECTION_TYPES) if (!home.some((e) => e.section === s)) home.push({ section: s, hidden: true });
|
||||
const style = { ...base.style, ...Object.fromEntries(Object.entries((saved.style ?? {}) as Record<string, unknown>).filter(([, x]) => typeof x === 'string')) };
|
||||
return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style };
|
||||
}
|
||||
|
||||
/** The working copy as a snapshot. */
|
||||
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
const db = ctx.db;
|
||||
const [design, pages, ministries, leaders, media] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.mediaAsset.findMany(),
|
||||
]);
|
||||
const images = new Map(media.map((m) => [m.id, { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } satisfies Image]));
|
||||
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
|
||||
const used: Record<string, Image> = {};
|
||||
const collect = (data: unknown) => {
|
||||
// Every media id anywhere in a section's data (images, videoId, imageId, photoId).
|
||||
const walk = (x: unknown) => {
|
||||
if (typeof x === 'string' && images.has(x)) used[x] = images.get(x)!;
|
||||
else if (Array.isArray(x)) x.forEach(walk);
|
||||
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
|
||||
};
|
||||
walk(data);
|
||||
};
|
||||
const d = cleanDesign(design);
|
||||
const snapshotPages: SnapshotPage[] = pages.map((p) => {
|
||||
const sections: SnapshotSection[] = [];
|
||||
if (p.kind === 'home') {
|
||||
// The homepage: the design's order and variants, each section's data from the page.
|
||||
const byType = new Map(p.sections.map((s) => [s.type, s]));
|
||||
for (const entry of d.home) {
|
||||
if (entry.hidden) continue;
|
||||
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
|
||||
}
|
||||
} else {
|
||||
for (const s of p.sections) {
|
||||
if (s.hidden) continue;
|
||||
const data = parseSectionData(s.type, s.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: s.type, variant: s.variant, data });
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: p.kind, slug: p.slug, path: p.kind === 'home' ? '/' : `/${p.slug}`, title: p.title, seoTitle: p.seoTitle, description: p.description,
|
||||
navLabel: p.navLabel || p.title, inNav: p.inNav && p.kind !== 'home', image: image(p.imageId), sections,
|
||||
};
|
||||
});
|
||||
return {
|
||||
v: SNAPSHOT_VERSION,
|
||||
design: d,
|
||||
pages: snapshotPages,
|
||||
ministries: ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
|
||||
leaders: leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
|
||||
media: used,
|
||||
};
|
||||
}
|
||||
|
||||
/** Publish (§4): the whole working copy becomes the next version, at once. */
|
||||
export async function publish(ctx: Ctx, by: { id: string; role: string }, note: string | null = null) {
|
||||
const snapshot = await buildSnapshot(ctx);
|
||||
const last = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true } });
|
||||
const version = await ctx.db.siteVersion.create({
|
||||
data: { number: (last?.number ?? 0) + 1, snapshot: snapshot as never, note, publishedBy: by.id, publishedAt: ctx.now() },
|
||||
});
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'site_published', targetType: 'site_version', targetId: String(version.number), metadata: { note } });
|
||||
return version;
|
||||
}
|
||||
|
||||
/** The latest published snapshot, or null before the first publish (Coming soon). */
|
||||
export async function publishedSnapshot(ctx: Ctx): Promise<{ number: number; publishedAt: Date; snapshot: Snapshot } | null> {
|
||||
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } });
|
||||
if (!latest) return null;
|
||||
const snap = latest.snapshot as unknown as Snapshot;
|
||||
if (!snap || snap.v !== SNAPSHOT_VERSION) return null;
|
||||
return { number: latest.number, publishedAt: latest.publishedAt, snapshot: { ...snap, design: cleanDesign(snap.design as never) } };
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import { loadDemo } from '../src/demo/demoChurch.js';
|
||||
import { siteContent, spotifyEmbed, youtubeId } from '../src/site/content.js';
|
||||
import { buildPalette, contrast, hexToRgb } from '../src/site/palette.js';
|
||||
import { parseSectionData } from '../src/site/sections.js';
|
||||
import { buildSnapshot, cleanDesign, publish } from '../src/site/snapshot.js';
|
||||
import { defaultDesign } from '../src/site/variants.js';
|
||||
import { harness } from './support/harness.js';
|
||||
|
||||
const rgb = (triple: string) => triple.split(' ').map(Number) as [number, number, number];
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-'));
|
||||
|
||||
describe('colours from the church, made safe (§3)', () => {
|
||||
it('keeps a dark colour as it is, with white text', () => {
|
||||
const p = buildPalette('#1d5c63', '#e0a458');
|
||||
assert.equal(p.brand, '29 92 99');
|
||||
assert.equal(p.onBrand, '255 255 255');
|
||||
assert.deepEqual(p.notes, []);
|
||||
});
|
||||
|
||||
it('darkens a light colour for text on white, and says why', () => {
|
||||
const p = buildPalette('#f5c542', null);
|
||||
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5);
|
||||
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5);
|
||||
assert.ok(p.notes.some((n) => n.includes('darker shade')));
|
||||
});
|
||||
|
||||
it('always gives readable text on the brand colour, whatever the church picks', () => {
|
||||
for (const hex of ['#ff0000', '#00ff00', '#0000ff', '#888888', '#ffffff', '#000000', '#ff8800', '#00aaaa']) {
|
||||
const p = buildPalette(hex, hex);
|
||||
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5, hex);
|
||||
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5, hex);
|
||||
}
|
||||
assert.deepEqual(hexToRgb('nonsense'), [31, 78, 121]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('section data', () => {
|
||||
it('fills defaults and refuses what doesn\'t fit', () => {
|
||||
assert.deepEqual(parseSectionData('latestMessage', {}), { heading: null });
|
||||
assert.equal(parseSectionData('hero', { headline: '' }), null);
|
||||
assert.equal(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: 'javascript:alert(1)' } }), null);
|
||||
assert.ok(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: '/visit' } }));
|
||||
assert.equal(parseSectionData('nothing', {}), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('publishing (§4)', () => {
|
||||
it('makes an unknown template, variant or section safe', () => {
|
||||
const d = cleanDesign({ template: 'fancy', variants: { hero: 'spinning', team: 'list' }, home: [{ section: 'team' }, { section: 'nope' }], style: { spacing: 'compact', bad: 3 } });
|
||||
assert.equal(d.template, 'heritage');
|
||||
assert.equal(d.variants.hero, 'photo');
|
||||
assert.equal(d.variants.team, 'list');
|
||||
assert.equal(d.home[0]!.section, 'team');
|
||||
assert.equal(d.home.length, 8);
|
||||
assert.ok(d.home.slice(1).every((e) => e.hidden));
|
||||
assert.equal(d.style.spacing, 'compact');
|
||||
});
|
||||
|
||||
it('draws the homepage in the design\'s order and variants, leaving out hidden and broken sections', async () => {
|
||||
const h = await harness();
|
||||
const design = defaultDesign('clean');
|
||||
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: design.variants, home: design.home, style: design.style } });
|
||||
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'hero', data: { headline: 'Welcome' } } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'invitation', data: { heading: '' } } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'team', data: {} } });
|
||||
const snap = await buildSnapshot(h.ctx);
|
||||
const types = snap.pages[0]!.sections.map((s) => s.type);
|
||||
assert.deepEqual(types, ['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage'], 'Clean hides Team; the empty invitation is left out');
|
||||
assert.equal(snap.pages[0]!.sections[0]!.variant, 'text');
|
||||
assert.equal(snap.pages[0]!.path, '/');
|
||||
});
|
||||
|
||||
it('numbers versions and keeps every one', async () => {
|
||||
const h = await harness();
|
||||
await publish(h.ctx, { id: 'u1', role: 'owner' }, 'First');
|
||||
const v2 = await publish(h.ctx, { id: 'u1', role: 'owner' });
|
||||
assert.equal(v2.number, 2);
|
||||
assert.equal(await h.db.siteVersion.count(), 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the public site\'s content', () => {
|
||||
it('is Coming soon before the first publish, from the church profile', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const c = await siteContent(h.ctx);
|
||||
assert.equal(c.mode, 'coming-soon');
|
||||
assert.equal(c.church, null);
|
||||
assert.equal(c.style.fontPairing, 'classic', 'Heritage\'s default pairing');
|
||||
assert.equal(c.style.corners, 'sharp');
|
||||
});
|
||||
|
||||
for (const template of WEBSITE_TEMPLATES) {
|
||||
it(`loads and publishes the demo church on ${template}`, async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const dir = tmp();
|
||||
await loadDemo(h.ctx, template, { uploadDir: dir });
|
||||
const c = await siteContent(h.ctx);
|
||||
assert.equal(c.mode, 'published');
|
||||
if (c.mode !== 'published') return;
|
||||
assert.equal(c.snapshot.design.template, template);
|
||||
assert.equal(c.church?.name, 'Acacia Hill Church');
|
||||
assert.equal(c.snapshot.pages.length, 9);
|
||||
assert.equal(c.snapshot.ministries.length, 4);
|
||||
assert.equal(c.messages.length, 3);
|
||||
assert.equal(c.events.length, 3);
|
||||
assert.ok(c.events[0]!.startsAt < c.events[1]!.startsAt);
|
||||
assert.equal(c.transparentHeader['/'], template === 'bold', 'only Bold\'s header sits over the hero');
|
||||
const hero = c.snapshot.pages[0]!.sections[0]!;
|
||||
assert.equal(hero.type, 'hero');
|
||||
const firstImage = (hero.data.images as string[])[0]!;
|
||||
assert.match(c.snapshot.media[firstImage]!.url, /^\/api\/uploads\/demo\/hero\.svg$/);
|
||||
assert.ok(fs.existsSync(path.join(dir, 'demo', 'hero.svg')));
|
||||
});
|
||||
}
|
||||
|
||||
it('serves the uploads, never a folder or outside it, and the content over HTTP', async () => {
|
||||
const dir = tmp();
|
||||
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
|
||||
await loadDemo(h.ctx, 'community', { uploadDir: dir });
|
||||
const svg = await request(h.app).get('/api/uploads/demo/hero.svg');
|
||||
assert.equal(svg.status, 200);
|
||||
assert.match(String(svg.headers['content-security-policy']), /sandbox/);
|
||||
assert.equal((await request(h.app).get('/api/uploads/demo/')).status, 404);
|
||||
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/..%2f..%2fpackage.json')).status));
|
||||
assert.equal((await request(h.app).get('/api/uploads/missing.png')).status, 404);
|
||||
const content = await request(h.app).get('/api/v1/site/content');
|
||||
assert.equal(content.body.mode, 'published');
|
||||
assert.equal(content.body.snapshot.design.template, 'community');
|
||||
});
|
||||
});
|
||||
|
||||
describe('message links', () => {
|
||||
it('finds YouTube ids and Spotify embeds', () => {
|
||||
assert.equal(youtubeId('https://www.youtube.com/watch?v=aqz-KE-bpKQ'), 'aqz-KE-bpKQ');
|
||||
assert.equal(youtubeId('https://youtu.be/abc123'), 'abc123');
|
||||
assert.equal(youtubeId('https://www.youtube.com/live/xyz'), 'xyz');
|
||||
assert.equal(youtubeId('https://example.com/watch?v=abc'), null);
|
||||
assert.equal(spotifyEmbed('https://open.spotify.com/episode/4rOoJ6Egrf8K2IrywzwOMk?si=1'), 'https://open.spotify.com/embed/episode/4rOoJ6Egrf8K2IrywzwOMk');
|
||||
assert.equal(spotifyEmbed('https://evil.example/episode/x'), null);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,9 @@ import crypto from 'node:crypto';
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const DEFAULTS: Record<string, () => Row> = {
|
||||
ministry: () => ({ summary: null, body: null, imageId: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
leader: () => ({ role: null, bio: null, photoId: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
messageSeries: () => ({ summary: null, imageId: null }),
|
||||
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
|
||||
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
|
||||
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
|
||||
|
||||
Reference in New Issue
Block a user