~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
70 lines · 3.1 KB Raw History
/// <reference types="node" />
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { readFileSync } from 'node:fs';
import { defineConfig, type Plugin } from 'vite';

// The tokens of src/tokens.css: the light ones, those at the top level, and
// the dark ones, those under `prefers-color-scheme: dark`, each with every
// `var(--x)` in it resolved, and rem as px, as mail clients read neither.
function tokens(): { light: Map<string, string>; dark: Map<string, string> } {
	const css = readFileSync(new URL('src/tokens.css', import.meta.url), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
	const read = (block: string) => new Map([...block.matchAll(/(--[\w-]+)\s*:\s*([^;]+);/g)].map((m) => [m[1], m[2].trim()]));
	const darkAt = css.indexOf('@media (prefers-color-scheme: dark)');
	const darkEnd = css.indexOf('\n}', darkAt);
	const light = read(css.slice(0, darkAt) + css.slice(darkEnd).replace(/@media[^{]*\{[\s\S]*?\n\}/g, ''));
	const dark = new Map([...light, ...read(css.slice(darkAt, darkEnd))]);
	const resolve = (map: Map<string, string>) => {
		const value = (name: string, seen: string[] = []): string => {
			const v = map.get(name);
			if (v === undefined || seen.includes(name)) throw new Error(`src/email/email.html: no token ${name} in src/tokens.css`);
			return v
				.replace(/var\((--[\w-]+)\)/g, (_, n) => value(n, [...seen, name]))
				.replace(/(-?[\d.]+)rem\b/g, (_, n) => `${Number(n) * 16}px`);
		};
		return new Map([...map.keys()].map((k) => [k, value(k)]));
	};
	return { light: resolve(light), dark: resolve(dark) };
}

// The HTML part of the server's emails (spec/EMAIL.md, "The message"):
// src/email/email.html with each token written in as its value, to
// dist/email.html, which pds-server embeds beside the pages.
function email(): Plugin {
	return {
		name: 'email',
		generateBundle() {
			const { light, dark } = tokens();
			const source = readFileSync(new URL('src/email/email.html', import.meta.url), 'utf8')
				.replace(/<!--(?!\[if)[\s\S]*?-->\s*/g, '')
				.replace(/\/\*[\s\S]*?\*\/\s*/g, '')
				.replace(/\b(var|dark)\((--[\w-]+)\)/g, (_, which: string, name: string) => {
					const v = (which === 'dark' ? dark : light).get(name);
					if (v === undefined) throw new Error(`src/email/email.html: no token ${name} in src/tokens.css`);
					return v.replaceAll('"', "'");
				});
			this.emitFile({ type: 'asset', fileName: 'email.html', source });
		}
	};
}

// The pages are served by pds from what this writes to dist/: its assets
// at /oauth/assets/<name>, each name with a hash of the file, and
// dist/.vite/manifest.json, which pds-server reads at compile time to name
// the entry's script and stylesheets in each page (spec/OAUTH-PAGES.md);
// and dist/email.html, the emails' HTML part.
export default defineConfig({
	base: '/oauth/',
	plugins: [svelte({ compilerOptions: { runes: true } }), email()],
	build: {
		outDir: 'dist',
		assetsDir: 'assets',
		emptyOutDir: true,
		manifest: true,
		// One stylesheet, and no style a script injects: the pages'
		// Content-Security-Policy allows only stylesheets from 'self'.
		cssCodeSplit: false,
		assetsInlineLimit: 0,
		modulePreload: { polyfill: false },
		rollupOptions: { input: 'src/main.ts' }
	}
});