Files
gerbeur/vite.config.ts
khannurien 7960d74c55 v4: weekly digests and monthly recaps go out by email, every email is written once as Markdown in the app's one catalog, and a review of the last two commits removes what they stated twice — users get a weekly digest (what happened to them, what the people and playlists they follow posted, the week's top dumps, the community) and a monthly recap (the month's top dumps and the community), both on by default, in their own style and scheme. digest-service sends what is due every quarter of an hour from digest_schedule (migration 0020), which holds each user's rolling 7- or 30-day period; existing users' first periods are spread over the coming week or month, a digest more than a period late covers the last full one, an empty one isn't sent, and an address like admin@localhost is skipped. Each digest carries a one-click unsubscribe (List-Unsubscribe and List-Unsubscribe-Post, POST /api/users/unsubscribe) and a link to the new /unsubscribe page, which asks before turning that cadence off, since mail scanners open every link; the token (lib/jwt) names the user and the cadence and never expires. The welcome email now says the digests are on. The emails' words moved out of a hand-written api/mail/strings.ts into the Lingui catalogs the interface uses: lingui extracts api/mail/ too, the catalogs moved to a top-level locales/ that both halves read, compile emits ES modules the server imports (api/mail/i18n.ts), messages take ICU plurals, and the labels the settings tab, the unsubscribe page and the emails share are one message each (their French had already drifted apart). Each template writes its email once as Markdown, which is the plain-text part, and EmailKit.render draws its blocks in the style (a lone link is a button, a list item starting with an image a thumbnail row, a numbered list a ranking, --- the footer), so no string is declared for an HTML and a text version; user text is escaped for Markdown, which the welcome body didn't do for usernames, whose _ read as emphasis. paint() set colors before a border-top shorthand that reset them, so every divider was black. The review also gave one home to what was written twice: the locale list (shared/locale.ts, read by lingui.config, the client, the server and its catalog loader), the base style and default scheme (shared/theme.ts), an email's look (lookOf, which digest-service, welcome and reset share), whether email is on (EMAIL_ENABLED, read by email-service and index.html), a setting's column and its default in the digests' SQL (SETTINGS_COLUMNS, DEFAULT_SETTINGS), the unsubscribe token (made once, not parsed back from a URL), AuthProvider's compare-and-store, ThemeProvider's twin style and scheme code (useThemeChoice), the test JWT encoder, and duplicate digest messages. The email palettes stay a flattened copy of the themes' tokens, now under a test that caught Times' secondary and link colors drifting. The Dockerfile copies api/mail and locales so the build extracts the emails' messages and the server finds its catalogs, and deno.json maps @lingui/core for the runtime image. 236 backend tests (new: digest building, sending, catch-up, scheduling and unsubscribing; the Markdown renderer; French from the catalog; palettes against themes; the stagger migration; unsubscribe tokens) and 661 frontend tests (new: the unsubscribe page) pass, and tsc, eslint, doc:lint, deno check, deno lint and deno fmt are clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:14:46 +00:00

145 lines
5.6 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { defineConfig, type Plugin } from "vite";
import react from "@vitejs/plugin-react-swc";
import { lingui } from "@lingui/vite-plugin";
import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { brotliCompressSync, constants as zlib, gzipSync } from "node:zlib";
import linguiConfig from "./lingui.config.ts";
import { BASE_STYLE, isStyleName } from "./shared/theme.ts";
const SITE_NAME = process.env.GERBEUR_SITE_NAME || "gerbeur";
const SITE_EMOJI = process.env.GERBEUR_SITE_EMOJI || "🚚";
const BANDCAMP_PLAYER = process.env.GERBEUR_BANDCAMP_PLAYER?.trim() === "native" ? "native" : "embed";
const DEFAULT_STYLE = isStyleName(process.env.GERBEUR_DEFAULT_STYLE?.trim()) ? process.env.GERBEUR_DEFAULT_STYLE!.trim() : BASE_STYLE;
const EMAIL_ENABLED = process.env.GERBEUR_SMTPS_URL?.trim() ? "on" : "off";
// Cache-busting token for the favicon URLs (see index.html). Changes when the
// emoji changes, so browsers don't keep serving a stale cached icon. Mirrors
// Twemoji's filename convention (kept trivial here to avoid the frontend build
// depending on backend code; the canonical version lives in api/lib/site-icons.ts).
function emojiToCodepoint(emoji: string): string {
const cleaned = emoji.includes("‍") ? emoji : emoji.replace(/️/g, "");
return [...cleaned].map((ch) => ch.codePointAt(0)!.toString(16)).join("-");
}
const ICON_VERSION = emojiToCodepoint(SITE_EMOJI);
// The emoji picker (frimousse) reads emojibase-data from ${url}/${locale}/{data,messages}.json.
// It is served from here rather than a CDN; the version is in the path so the
// files can be cached for good, and bumping the package moves the URL.
const EMOJIBASE_DIR = resolve("node_modules/emojibase-data");
const EMOJIBASE_VERSION = JSON.parse(readFileSync(join(EMOJIBASE_DIR, "package.json"), "utf8")).version;
const EMOJIBASE_URL = `/emojibase/${EMOJIBASE_VERSION}`;
const EMOJIBASE_FILES = linguiConfig.locales.flatMap((locale) => [`${locale}/data.json`, `${locale}/messages.json`]);
function emojibase(): Plugin {
return {
name: "emojibase",
configureServer(server) {
server.middlewares.use(EMOJIBASE_URL, (req, res, next) => {
const file = req.url?.split("?")[0].slice(1) ?? "";
if (!EMOJIBASE_FILES.includes(file)) return next();
res.setHeader("Content-Type", "application/json");
res.end(readFileSync(join(EMOJIBASE_DIR, file)));
});
},
generateBundle() {
for (const file of EMOJIBASE_FILES) {
this.emitFile({
type: "asset",
fileName: `${EMOJIBASE_URL.slice(1)}/${file}`,
source: readFileSync(join(EMOJIBASE_DIR, file)),
});
}
},
};
}
// Writes .br and .gz next to every compressible file in the build, which Oak's
// send() serves in place of the original when the browser accepts them. The
// server itself compresses nothing. index.html is left out: the server fills in
// its placeholders at runtime (see api/lib/static.ts).
const COMPRESSIBLE = /\.(js|css|json|svg|webmanifest)$/;
function precompress(): Plugin {
let outDir = "";
return {
name: "precompress",
apply: "build",
configResolved(config) {
outDir = resolve(config.root, config.build.outDir);
},
closeBundle() {
const walk = (dir: string) => {
for (const name of readdirSync(dir)) {
const path = join(dir, name);
if (statSync(path).isDirectory()) walk(path);
else if (COMPRESSIBLE.test(name)) compress(path);
}
};
const compress = (path: string) => {
const raw = readFileSync(path);
if (raw.length < 1024) return;
const br = brotliCompressSync(raw, {
params: { [zlib.BROTLI_PARAM_QUALITY]: 11, [zlib.BROTLI_PARAM_SIZE_HINT]: raw.length },
});
const gz = gzipSync(raw, { level: 9 });
if (br.length < raw.length * 0.9) writeFileSync(`${path}.br`, br);
if (gz.length < raw.length * 0.9) writeFileSync(`${path}.gz`, gz);
};
walk(outDir);
},
};
}
export default defineConfig({
define: {
"import.meta.env.VITE_EMOJIBASE_URL": JSON.stringify(EMOJIBASE_URL),
},
server: {
port: 3000,
watch: {
ignored: ["**/api/**"],
},
},
build: {
rollupOptions: {
output: {
// Only the framework, which every page needs and which changes least, gets
// a chunk of its own so it stays cached across deploys. Everything else is
// left to the bundler, so libraries only the lazy chunks use (the emoji
// picker, forms) stay out of the first load.
manualChunks(id) {
if (/node_modules\/(react|react-dom|scheduler|react-router)\//.test(id)) {
return "vendor";
}
},
},
},
},
plugins: [
{
// In dev the API server isn't serving index.html, so replace the placeholders here.
// In production the Oak server does the replacement at runtime (see api/lib/static.ts).
name: "inject-site-name",
transformIndexHtml: {
order: "pre",
handler: (html, ctx) =>
ctx.server
? html
.replaceAll("__SITE_NAME__", SITE_NAME)
.replaceAll("__SITE_EMOJI__", SITE_EMOJI)
.replaceAll("__ICON_VERSION__", ICON_VERSION)
.replaceAll("__BANDCAMP_PLAYER__", BANDCAMP_PLAYER)
.replaceAll("__DEFAULT_STYLE__", DEFAULT_STYLE)
.replaceAll("__EMAIL_ENABLED__", EMAIL_ENABLED)
: html,
},
},
emojibase(),
precompress(),
lingui(),
react({
plugins: [["@lingui/swc-plugin", {}]],
}),
],
});